How do I set the time of java.util.Date instance to 00:00:00?

The following code snippet shows you how to remove time information from the java.util.Date object. The static method removeTime() in the code snippet below will take a Date object as parameter and will return a new Date object where the hour, minute, second and millisecond information have been reset to zero. To do this we use the java.util.Calendar. To remove time information, we set the calendar fields of Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND to zero.

package org.kodejava.util;

import java.util.Calendar;
import java.util.Date;

public class DateRemoveTime {
    public static void main(String[] args) {
        System.out.println("Now = " + removeTime(new Date()));
    }

    private static Date removeTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
}

The result of the code snippet above is:

Now = Sat Nov 20 00:00:00 CST 2021

How to check if an object reference is not null?

Usually, if not always, we use the if statement combined with == or != operators to check if an object reference is null or not. We do this to validate arguments passed to constructors or methods doesn’t contain a null value. These null check can be seen as clutter in our code.

The solution is to use the java.util.Objects class. This static utility class provides methods like requireNonNull(T) and requireNonNull(T, String) to check if the specified object reference is not null. If null, these methods will throw a NullPointerException. Using the second method variant we can customise the exception message.

The example below shows how we use these methods.

package org.kodejava.util;

import java.util.Objects;

public class ObjectsNullCheckDemo {
    private String firstName;
    private String lastName;

    /**
     * Validate constructor arguments. The firstName and lastName
     * arguments can't be null. A NullPointerException with the
     * specified message will be thrown.
     */
    public ObjectsNullCheckDemo(String firstName, String lastName) {
        this.firstName = Objects.requireNonNull(firstName,
                "First name can't be null.");
        this.lastName = Objects.requireNonNull(lastName,
                "Last name can't be null.");
    }

    public static void main(String[] args) {
        // This line is fine.
        ObjectsNullCheckDemo demo = new ObjectsNullCheckDemo("John", "Doe");
        System.out.println("demo = " + demo);

        try {
            // This line produce a NullPointerException
            ObjectsNullCheckDemo demo1 = new ObjectsNullCheckDemo("Alice", null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String name = null;
        try {
            // The line below will throw java.lang.NullPointerException.
            Objects.requireNonNull(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setFirstName(String firstName) {
        // First name can't be null.
        this.firstName = Objects.requireNonNull(firstName,
                "First name can't be null.");
    }

    public void setLastName(String lastName) {
        // Last name can't be null.
        this.lastName = Objects.requireNonNull(lastName,
                "Last name can't be null.");
    }

    @Override
    public String toString() {
        return "ObjectsNullCheckDemo{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}

Running the code above will print the following result:

demo = ObjectsNullCheckDemo{firstName='John', lastName='Doe'}
java.lang.NullPointerException: Last name can't be null.
    at java.base/java.util.Objects.requireNonNull(Objects.java:233)
    at org.kodejava.util.ObjectsNullCheckDemo.<init>(ObjectsNullCheckDemo.java:17)
    at org.kodejava.util.ObjectsNullCheckDemo.main(ObjectsNullCheckDemo.java:28)
java.lang.NullPointerException
    at java.base/java.util.Objects.requireNonNull(Objects.java:208)
    at org.kodejava.util.ObjectsNullCheckDemo.main(ObjectsNullCheckDemo.java:36)

Using format flags to format negative number in parentheses

In this example we are going to learn to use a java.util.Formatter to format negative number in parentheses. The Formatter can use a format flags to format a value. To display a negative number in parentheses we can use the ( flag. This flag display negative number inside parentheses instead of using the - symbol.

The following code snippet below will show you how to do it. We start the example by using the Formatter object and simplified using the format() method of the String class.

package org.kodejava.util;

import java.util.Formatter;
import java.util.Locale;

public class FormatNegativeNumber {
    public static void main(String[] args) {
        // Creates an instance of Formatter, format the number using the
        // format and print out the result.
        Formatter formatter = new Formatter();
        formatter.format("%(,.2f", -199.99f);
        System.out.println("number1 = " + formatter);

        // Use String.format() method instead of creating an instance of
        // Formatter. Format a negative number using Germany locale.
        String number2 = String.format(Locale.GERMANY, "%(,8.2f", -49.99);
        System.out.println("number2 = " + number2);

        // Format number using Indonesian locale. The thousand separator is "."
        // in Indonesian number.
        String number3 = String.format(new Locale("id", "ID"), "%(,d", -10000);
        System.out.println("number3 = " + number3);
    }
}

The result of this code snippet:

number1 = (199.99)
number2 =  (49,99)
number3 = (10.000)

How do I fill array with non-default value?

This code snippet will show you how to create array variable and initialized it with a non-default value. By default, when we create an array of something in Java all entries will have its default value. For primitive types like int, long, float the default value are zero (0 or 0.0). For reference types (anything that holds an object in it) will have null as the default value. For boolean variable it will be false.

If you want to initialize the array to different value you can use the Arrays.fill() method. This method will help you to set the value for every element of the array.

Let see the following code snippet as an example:

package org.kodejava.util;

import java.util.Arrays;

public class ArraysFillExample {
    public static void main(String[] args) {
        // Assign -1 to each element of numbers arrays
        int[] numbers = new int[5];
        Arrays.fill(numbers, -1);
        System.out.println("Numbers: " + Arrays.toString(numbers));

        // Assign 1.0f to each element of prices arrays
        float[] prices = new float[5];
        Arrays.fill(prices, 1.0f);
        System.out.println("Prices : " + Arrays.toString(prices));

        // Assign empty string to each element of words arrays
        String[] words = new String[5];
        Arrays.fill(words, "");
        System.out.println("Words  : " + Arrays.toString(words));

        // Assign 9 to each element of the multi array
        int[][] multi = new int[3][3];
        for (int[] array : multi) {
            Arrays.fill(array, 9);
        }
        System.out.println("Multi  : " + Arrays.deepToString(multi));
    }
}

In the code snippet above we utilize the Arrays.fill() utility method to assign value for each element of the int, float and String array. To change the default value of multidimensional array we can’t directly call the Arrays.fill() method. In the example we use for-loop to set each element of the sub-array using the Arrays.fill() method.

The output of the code snippet above are:

Numbers: [-1, -1, -1, -1, -1]
Prices : [1.0, 1.0, 1.0, 1.0, 1.0]
Words  : [, , , , ]
Multi  : [[9, 9, 9], [9, 9, 9], [9, 9, 9]]

How do I implement equals() and hashCode() method using java.util.Objects?

This example will show you how to implement the equals() and hashCode() object using java.util.Objects class. The Objects class provides a set of utility methods to work with object such as comparing two objects for equality and calculating the hashcode. Other methods include object null check methods, object to string method, etc.

To demonstrate equals() and hash() methods we’ll create a simple POJO called Student with a couple of properties such as id, name and dateOfBirth.

package org.kodejava.util.support;

import java.time.LocalDate;
import java.util.Objects;

public class Student {
    private Long id;
    private String name;
    private LocalDate dateOfBirth;

    public Student() {
    }

    public Student(Long id, String name, LocalDate dateOfBirth) {
        this.id = id;
        this.name = name;
        this.dateOfBirth = dateOfBirth;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public LocalDate getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(LocalDate dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student that = (Student) o;
        return Objects.equals(this.id, that.id)
                && Objects.equals(this.name, that.name)
                && Objects.equals(this.dateOfBirth, that.dateOfBirth);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, dateOfBirth);
    }
}

Using the Objects.equals() and Objects.hash() methods in the Student class makes the implementation of the equals() method and the hashCode() method concise, easy to read and to understand. The Objects utility class will operate in a null-safe way which means that it will check for a null fields of the object.

The code snippet below will demonstrate the use of Student class. Which will compare objects using the equals() method and print out the calculated hashcode of the object.

package org.kodejava.util;

import org.kodejava.util.support.Student;

import java.time.LocalDate;
import java.time.Month;

public class EqualsHashCodeExample {
    public static void main(String[] args) {
        Student student1 = new Student(1L, "Alice", LocalDate.of(1990, Month.APRIL, 1));
        Student student2 = new Student(1L, "Alice", LocalDate.of(1990, Month.APRIL, 1));
        Student student3 = new Student(2L, "Bob", LocalDate.of(1992, Month.DECEMBER, 21));

        System.out.println("student1.equals(student2) = " + student1.equals(student2));
        System.out.println("student1.equals(student3) = " + student1.equals(student3));
        System.out.println("student1.hashCode() = " + student1.hashCode());
        System.out.println("student2.hashCode() = " + student2.hashCode());
        System.out.println("student3.hashCode() = " + student3.hashCode());
    }
}

And here are the result of the code snippet above:

student1.equals(student2) = true
student1.equals(student3) = false
student1.hashCode() = 1967967937
student2.hashCode() = 1967967937
student3.hashCode() = 6188033

Another approach for implementing the equals() and hashCode() method is using the Apache Commons Lang library. And example of it can be seen here: How to implement the hashCode and equals method using Apache Commons?.

How can I insert an element in array at a given position?

As we know an array in Java is a fixed-size object, once it created its size cannot be changed. So if you want to have a resizable array-like object where you can insert an element at a given position you can use a java.util.List object type instead.

This example will show you how you can achieve array insert using the java.util.List and java.util.ArrayList object. Let see the code snippet below.

package org.kodejava.util;

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

public class ArrayInsert {
    public static void main(String[] args) {
        // Creates an array of integer value and prints the original values.
        Integer[] numbers = new Integer[]{1, 1, 2, 3, 8, 13, 21};
        System.out.println("Original numbers: " +
                Arrays.toString(numbers));

        // Creates an ArrayList object and initialize its values with the entire
        // content of numbers array. We use the add(index, element) method to add
        // element = 5 at index = 4.
        List<Integer> list = new ArrayList<>(Arrays.asList(numbers));
        list.add(4, 5);

        // Converts back the list into array object and prints the new values.
        numbers = list.toArray(new Integer[0]);
        System.out.println("After insert    : " + Arrays.toString(numbers));
    }
}

In the code snippet above the original array of Integer numbers will be converted into a List, in this case we use an ArrayList, we initialized the ArrayList by passing all elements of the array into the list constructor. The Arrays.asList() can be used to convert an array into a collection type object.

Next we insert a new element into the List using the add(int index, E element) method. Where index is the insert / add position and element is the element to be inserted. After the new element inserted we convert the List back to the original array.

Below is the result of the code snippet above:

Original numbers: [1, 1, 2, 3, 8, 13, 21]
After insert    : [1, 1, 2, 3, 5, 8, 13, 21]

How to use Preferences API to store program configurations?

The Preferences API provided in the java.util.prefs package can be used to store and retrieve application configurations. The main class is the Preferences class. Using this class you can manage the preference data such as storing, retrieving, removing and clearing the preference data.

Preferences are key-value pairs of data. You can store a string, int, boolean and other primitive data type. You can use the get() method to retrieve value associated with a key from preference node and the put() method to store a value associated with a key in the preference node. To remove a value associated with a key from preference node you can use the remove() method. And if you want to clear the keys from the preference node you can use the clear() method.

The actual storage of these preference data is dependent on the platform. For example in Windows OSes it stored in the Windows Registry. What you have to know that this Preferences API is not intended to use for storing application data, you will only use it to store configurations of your applications.

Let’s see an example of using the Preferences API.

package org.kodejava.util.prefs;

import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

public class PreferencesExample {
    public static void main(String[] args) {
        PreferencesExample demo = new PreferencesExample();
        demo.setPreferences();
    }

    private void setPreferences() {
        // Define a node to store the preference data.
        Preferences pref = Preferences.userRoot().node(getClass().getName());

        String key1 = "KEY1";
        String key2 = "KEY2";
        String key3 = "KEY3";

        // Read the value of KEY1, return an empty string if the value
        // hasn't been set previously.
        String key1Value = pref.get(key1, "");
        System.out.println("KEY1: " + key1Value);

        // Read the value of KEY2 as an integer, if the value hasn't
        // been set previously return -1.
        int key2Value = pref.getInt(key2, -1);
        System.out.println("KEY2: " + key2Value);

        // Read the value of KEY3, return true if no value was set
        // previously.
        boolean key3Value = pref.getBoolean(key3, true);
        System.out.println("KEY3: " + key3Value);

        // Set the values for all the preference key above.
        if (key1Value.equals("")) {
            pref.put(key1, "January");
        }
        if (key2Value == -1) {
            pref.putInt(key2, 1000);
        }
        if (key3Value) {
            pref.putBoolean(key3, false);
        }

        printKeys(pref);

        // Remove KEY1 from the preference data.
        pref.remove(key1);
        printKeys(pref);

        try {
            // Remove all preference data of this node.
            pref.clear();
        } catch (BackingStoreException e) {
            e.printStackTrace();
        }

        printKeys(pref);
    }

    /**
     * Print Keys in the preference node.
     * @param pref Preference node.
     */
    private void printKeys(Preferences pref) {
        System.out.println("PreferencesExample.printKeys");
        try {
            String[] keys = pref.keys();
            for (String key : keys) {
                System.out.println("Key = " + key);
            }
        } catch (BackingStoreException e) {
            e.printStackTrace();
        }
        System.out.println("============================");
    }
}

Here are the output you’ll get when running the example above:

KEY1: 
KEY2: -1
KEY3: true
PreferencesExample.printKeys
Key = KEY1
Key = KEY2
Key = KEY3
============================
PreferencesExample.printKeys
Key = KEY2
Key = KEY3
============================
PreferencesExample.printKeys
============================

How to get random key-value pair from Hashtable?

package org.kodejava.example.util;

import java.util.Hashtable;
import java.util.Random;

public class HashtableGetRandom {
    public static void main(String[] args) {
        // Create a hashtable and put some key-value pair.
        Hashtable<String, String> colors = new Hashtable<>();
        colors.put("black", "#000");
        colors.put("red", "#f00");
        colors.put("green", "#0f0");
        colors.put("blue", "#00f");
        colors.put("white", "#fff");

        // Get a random entry from the hashtable.
        String[] keys = colors.keySet().toArray(new String[colors.size()]);
        String key = keys[new Random().nextInt(keys.length)];
        System.out.println(key + " = " + colors.get(key));
    }
}

How do I clear the content of an array?

In this example you’ll learn how to clear or reset the content of an array. We can use the java.util.Arrays.fill() method to replace to content of each element in the array. In the example below we create two arrays, names and numbers array. We initialize these arrays with some values and then clear the value by assigning null to each element of the array using the Arrays.fill() method.

package org.kodejava.util;

import java.util.Arrays;

public class ArrayClear {
    public static void main(String[] args) {
        String[] names = {"Alice", "Bob", "Carol"};
        System.out.println("Names = " + Arrays.toString(names));

        // Replace the contents of the names array to null for each array
        // element.
        Arrays.fill(names, null);
        System.out.println("Names = " + Arrays.toString(names));

        Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        System.out.println("Numbers = " + Arrays.toString(numbers));

        // Replace the contents of the numbers array to null for each
        // array element.
        Arrays.fill(numbers, null);
        System.out.println("Numbers = " + Arrays.toString(numbers));
    }
}

The output of the code snippet:

Names = [Alice, Bob, Carol]
Names = [null, null, null]
Numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Numbers = [null, null, null, null, null, null, null, null, null, null]

How do I validate input when using Scanner?

This example show you how to validate input when using java.util.Scanner. To validate input the Scanner class provides some hasNextXXX() method that can be use to validate input. For example if we want to check whether the input is a valid integer we can use the hasNextInt() method.

In the code snippet below will demonstrate how to validate whether the user provide a positive integer number. The program will repeat until the correct input is supplied.

package org.kodejava.util;

import java.util.Scanner;

public class ScannerValidateInput {
    public static void main(String[] args) {
        ScannerValidateInput demo = new ScannerValidateInput();
        demo.validatePositiveNumber();
    }

    private void validatePositiveNumber() {
        Scanner scanner = new Scanner(System.in);

        int number;
        do {
            System.out.print("Please enter a positive number: ");
            while (!scanner.hasNextInt()) {
                String input = scanner.next();
                System.out.printf("\"%s\" is not a valid number.%n", input);
            }
            number = scanner.nextInt();
        } while (number < 0);

        System.out.printf("You have entered a positive number %d.%n", number);
    }
}

The output produce by the snippet:

Please enter a positive number: qwerty
"qwerty" is not a valid number.
@@@
"@@@" is not a valid number.
-100
Please enter a positive number: 99
You have entered a positive number 99.

Another example is to validate if user correctly input letters to guest a secret word. In the code snippet below if the user does not enter a letter the code will keep asking for a valid letter. It loops until the length of the inputted letters equals to the length of secret word.

package org.kodejava.util;

import java.util.Scanner;

public class ScannerValidateLetter {
    public static void main(String[] args) {
        ScannerValidateLetter demo = new ScannerValidateLetter();
        demo.validateLetter();
    }

    private void validateLetter() {
        String secretWord = "Hello";
        Scanner scanner = new Scanner(System.in);

        int length = 0;
        StringBuilder guess = new StringBuilder();
        do {
            System.out.print("Enter a letter to guess: ");
            char letter = scanner.next().charAt(0);
            if (Character.isLetter(letter)) {
                guess.append(letter);
                length++;
            }
        } while (length < secretWord.length());

        if (secretWord.equalsIgnoreCase(guess.toString())) {
            System.out.println("You are correct!");
        } else {
            System.out.println("Please try again!");
        }
    }
}
Enter a letter to guess: 1
Enter a letter to guess: 2
Enter a letter to guess: H
Enter a letter to guess: e
Enter a letter to guess: l
Enter a letter to guess: l
Enter a letter to guess: o
You are correct!