How do I use the if-then statement?

The if-then is the most basic control flow statement. It will execute the block of statement only if the test expression evaluated equals to true. Let’s see the example below:

package org.kodejava.basic;

public class IfThenDemo {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        // If the evaluation of a > b is true, the if block will be
        // executed. In the block below we just print that the value
        // of "a" is bigger than "b".
        if (a > b) {
            System.out.printf("A(%d) is bigger than B(%d)%n", a, b);
        }

        // When we have only a single command inside a block we can
        // remove the opening and closing braces for the block ({..}).
        // But it is a good practice to always enclose the block with
        // braces, so that we know the block of code to be executed.
        if (b < a)
            System.out.printf("B(%d) is smaller that A(%d)%n", b, a);
    }
}

The result of the above program is:

A(10) is bigger than B(5)
B(5) is smaller that A(10)

How do I count the occurrences of a number in an array?

package org.kodejava.basic;

import java.util.HashMap;
import java.util.Map;

public class NumberOccurrenceInArray {
    public static void main(String[] args) {
        int[] numbers = new int[]{1, 8, 3, 4, 3, 2, 5, 7, 3, 1, 4, 5, 6, 4, 3};

        Map<Integer, Integer> map = new HashMap<>();
        for (int key : numbers) {
            if (map.containsKey(key)) {
                int occurrence = map.get(key);
                occurrence++;
                map.put(key, occurrence);
            } else {
                map.put(key, 1);
            }
        }

        for (Integer key : map.keySet()) {
            int occurrence = map.get(key);
            System.out.println(key + " occur " + occurrence + " time(s).");
        }
    }
}

The result are:

1 occur 2 time(s).
2 occur 1 time(s).
3 occur 4 time(s).
4 occur 3 time(s).
5 occur 2 time(s).
6 occur 1 time(s).
7 occur 1 time(s).
8 occur 1 time(s).

How do I use the double brace initialization?

The double brace initialization {{ ... }} is another way for initializing a collection objects in Java. It is offer a simple syntax for initializing a collection object.

package org.kodejava.lang;

import java.util.ArrayList;
import java.util.List;

public class DoubleBraceInitialization {
    public static void main(String[] args) {
        // Creates a list of colors and add three colors of
        // Red, Green and Blue.
        List<String> colors1 = new ArrayList<>();
        colors1.add("Red");
        colors1.add("Green");
        colors1.add("Blue");

        for (String color : colors1) {
            System.out.println("Color = " + color);
        }

        // Creates another list of colors and add three colors
        // using the double brace initialization.
        List<String> colors2 = new ArrayList<>() {{
            add("Red");
            add("Green");
            add("Blue");
        }};

        for (String color : colors2) {
            System.out.println("Color = " + color);
        }
    }
}

What’s actually happened is: the first brace creates an anonymous inner class and the second brace is an initializer block. Due to the need for creating an inner class the use of double brace initialization is considered to be slower.

Because of this performance issue it’s better not to use this technique for your production code, but using it in your unit testing can make your test looks simpler.

How do I count the number of occurrences of a char in a String?

This example show you how to count the number of a character occurrences in a string. We show two ways to do it, using the String.replaceAll(String regex, String replace) method and creating a loop that check every char in the String and count the matched char.

package org.kodejava.lang;

public class CharCounter {
    public static void main(String[] args) {
        String text = "a,b,c,c,e,f,g,g,g,g,h";

        // Use the CharCounter.countCharOccurrences() method to count.
        int numberOfLetterC = CharCounter.countCharOccurrences(text, 'c');
        System.out.println("Letter c = " + numberOfLetterC);

        // Other solution is to use the String.replaceAll() method. We'll
        // replace the chars other than the counted char with an empty string.
        // To get the char occurrences we count the length of the remaining
        // string.
        int numberOfComma = text.replaceAll("[^,]", "").length();
        System.out.println("Comma    = " + numberOfComma);

        int numberOfLetterG = text.replaceAll("[^g]", "").length();
        System.out.println("Letter g = " + numberOfLetterG);
    }

    /**
     * Count number of specified char occurrences in the specified string.
     */
    private static int countCharOccurrences(String source, char target) {
        int counter = 0;

        // Loop through the string and increment the counter if the
        // target character found in the string. 
        for (int i = 0; i < source.length(); i++) {
            if (source.charAt(i) == target) {
                counter++;
            }
        }
        return counter;
    }
}

How do I count number of weekday between two dates?

The code below helps you find the number of a specified weekday (Monday, Tuesday, Wednesday, etc.) between two dates. The solution we used below is to loop between the two dates and check if the weekday of those dates are equals to the day we want to count.

package org.kodejava.util;

import java.util.Calendar;

public class DaysBetweenDate {
    public static void main(String[] args) {
        Calendar start = Calendar.getInstance();
        start.set(2021, Calendar.OCTOBER, 1);
        Calendar end = Calendar.getInstance();
        end.set(2021, Calendar.OCTOBER, 31);

        System.out.print("Number Monday between " +
                start.getTime() + " and " + end.getTime() + " are: ");

        int numberOfDays = 0;
        while (start.before(end)) {
            if (start.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
                numberOfDays++;
                start.add(Calendar.DATE, 7);
            } else {
                start.add(Calendar.DATE, 1);
            }
        }

        System.out.println(numberOfDays);
    }
}

The result of our program is:

Number Monday between Fri Oct 01 07:55:06 CST 2021 and Sun Oct 31 07:55:06 CST 2021 are: 4