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 load file from resource directory?

In the following code snippet we will learn how to load files from resource directory. Resource files can be in a form of image, audio, text, etc. Text resource file for example can be used to store application configurations, such as database configuration.

To load this resource file you can use a couple methods utilizing the java.lang.Class methods or the java.lang.ClassLoader methods. Both Class and ClassLoader provides getResource() and getResourceAsStream() methods to load resource file. The first method return a URL object while the second method return an InputStream.

When using the Class method, if the resource name started with “/” that identifies it is an absolute name. Absolute name means that it will load from the specified directory name or package name. While if it is not started with “/” then it is identified as a relative name. This means that it will look in the same package as the class that tries to load the resource.

App.class.getResource("database.conf");

The snippet will attempt to load the resource file from the same package as the App class. If the App class package is org.kodejava then the database.conf file must be located at /org/kodejava/. This is the relative resource name.

App.class.getResource("/org/kodejava/conf/database.conf"):

The snippet will attempt to load the resource file from the given package name. You should place the configuration file under /org/kodejava/conf/ to enable the application to load it. This is the absolute resource name.

Below is a snippet that use the Class method to load resources.

private void loadUsingClassMethod() throws IOException {
    System.out.println("LoadResourceFile.loadUsingClassMethod");
    Properties properties = new Properties();

    // Load resource relatively to the LoadResourceFile package.
    // This actually load resource from
    // "/org/kodejava/lang/database.conf".
    URL resource = getClass().getResource("database.conf");
    properties.load(new FileReader(Objects.requireNonNull(resource).getFile()));
    System.out.println("JDBC Driver: " + properties.get("jdbc.driver"));

    // Load resource using absolute name. This will read resource
    // from the root of the package. This will load "/database.conf".
    InputStream is = getClass().getResourceAsStream("/database.conf");
    properties.load(is);
    System.out.println("JDBC Driver: " + properties.get("jdbc.driver"));
}

When we use the ClassLoader method the resource name should not begins with a “/“. This method will not apply any absolute / relative transformation to the resource name like the Class method. Here a snippet of a method that use the ClassLoader method.

private void loadUsingClassLoaderMethod() throws IOException {
    System.out.println("LoadResourceFile.loadUsingClassLoaderMethod");
    Properties properties = new Properties();

    // When using the ClassLoader method, the resource name should
    // not be started with "/". This method will not apply any
    // absolute/relative transformation to the resource name.
    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource("database.conf");
    properties.load(new FileReader(Objects.requireNonNull(resource).getFile()));
    System.out.println("JDBC URL: " + properties.get("jdbc.url"));

    InputStream is = classLoader.getResourceAsStream("database.conf");
    properties.load(is);
    System.out.println("JDBC URL: " + properties.get("jdbc.url"));
}

Below is the main program that calls the methods above.

package org.kodejava.lang;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;

public class LoadResourceFile {
    public static void main(String[] args) throws Exception {
        LoadResourceFile demo = new LoadResourceFile();
        demo.loadUsingClassMethod();
        demo.loadUsingClassLoaderMethod();
    }
}

In the snippet above we load two difference resources. One contains Oracle database configuration and the other is MySQL database configuration.

/resources/org/kodejava/lang/database.conf

jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.username=kodejava
jdbc.password=kodejava123

/resources/database.conf

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/kodejava
jdbc.username=kodejava
jdbc.password=kodejava123

The result of this code snippet are:

LoadResourceFile.loadUsingClassMethod
JDBC Driver: oracle.jdbc.driver.OracleDriver
JDBC Driver: com.mysql.jdbc.Driver

LoadResourceFile.loadUsingClassLoaderMethod
JDBC URL: jdbc:mysql://localhost/kodejava
JDBC URL: jdbc:mysql://localhost/kodejava

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 escape / display percent sign in printf statement?

You have a problem displaying the % sign when you want to print a number in percentage format using the printf() method. Because the % sign is use as a prefix of format specifiers, you need to escape it if you want to display the % sign as part of the output string.

To escape the percent sign (%) you need to write it twice, like %%. It will print out a single % sign as part of your printf() method output. Let see an example in the code snippet below:

package org.kodejava.lang;

public class EscapePercentSignExample {
    public static void main(String[] args) {
        String format = "The current bank interest rate is %6.2f%%.%n";
        System.out.printf(format, 10f);
    }
}

In the code snippet above we use the following format %6.2f%%.%n which can be explained as:

  • %6.2f format the number (10f) as six characters in width, right justified, with two places after decimal point. The f conversion character means it accept a float value.
  • %% will escape the % sign and print it as part of the output.
  • %n will print out a new line character.

When you execute the code, it will print:

The current bank interest rate is  10.00%.