How do I get the number of processors available to the JVM?

The Runtime.getRuntime().availableProcessors() method returns the maximum number of processors available to the Java virtual machine, the value will never be smaller than one. Knowing the number of available processor you can use it for example to limit the number of thread in your application when you are writing a multi-thread code.

package org.kodejava.lang;

public class NumberProcessorExample {
    public static void main(String[] args) {
        final int processors = Runtime.getRuntime().availableProcessors();
        System.out.println("Number of processors = " + processors);
    }
}

Running the code snippet give you something like:

Number of processors = 8

How do I create a generic class in Java?

In this example you will learn how to create a generic class in Java. In some previous post in this blog you might have read how to use generic for working with Java collection API such as List, Set and Map. Now it is time to learn to create a simple generic class.

As an example in this post will create a class called GenericMachine and we can plug different type of engine into this machine that will be use by the machine to operate. For this demo we will create two engine type, a DieselEngine and a JetEngine. So let’s see how the classes are implemented in generic.

package org.kodejava.generics;

public class GenericMachine<T> {
    private final T engine;

    public GenericMachine(T engine) {
        this.engine = engine;
    }

    public static void main(String[] args) {
        // Creates a generic machine with diesel engine.
        GenericMachine<DieselEngine> machine = new GenericMachine<>(new DieselEngine());
        machine.start();

        // Creates another generic machine with jet engine.
        GenericMachine<JetEngine> anotherMachine = new GenericMachine<>(new JetEngine());
        anotherMachine.start();
    }

    private void start() {
        System.out.println("This machine running on: " + engine);
    }
}

Now, for the two engine class we will only create an empty class so that the GenericMachine class can be compiled successfully. And here are the engine classes:

package org.kodejava.generics;

public class DieselEngine {
}
package org.kodejava.generics;

public class JetEngine {
}

The <T> in the class declaration tell that we want the GenericMachine class to have type parameter. We also use the T type parameter at the class constructor to pass the engine.

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 do I convert number into Roman Numerals?

You want to convert numbers into their Roman numerals representation and vice versa. The solution here is to tackle the problem as a unary problem where the Roman numerals represented as a single element, the “I” character. We start by representing the number as a repeated sequence of the “I” characters. And then replace the characters according to next bigger symbol in roman numeral.

To convert from the Roman numerals to numbers we reverse the process. By the end of the process we will get a sequence of repeated “I” characters. The length of the final string returned by this process is the result of the roman numeral conversion to number.

In the code snippet below we create two methods. The toRoman(int number) method for converting number to roman numerals and the toNumber(String roman) method for converting from roman numerals to number. Both of this method utilize the String.replace() method for calculating the conversion result.

Let’s see the code in action.

package org.kodejava.lang;

public class RomanNumber {
    public static void main(String[] args) {
        for (int n = 1; n <= 4999; n++) {
            String roman = RomanNumber.toRoman(n);
            int number = RomanNumber.toNumber(roman);

            System.out.println(number + " = " + roman);
        }
    }

    private static String toRoman(int number) {
        return String.valueOf(new char[number]).replace('\0', 'I')
                .replace("IIIII", "V")
                .replace("IIII", "IV")
                .replace("VV", "X")
                .replace("VIV", "IX")
                .replace("XXXXX", "L")
                .replace("XXXX", "XL")
                .replace("LL", "C")
                .replace("LXL", "XC")
                .replace("CCCCC", "D")
                .replace("CCCC", "CD")
                .replace("DD", "M")
                .replace("DCD", "CM");
    }

    private static Integer toNumber(String roman) {
        return roman.replace("CM", "DCD")
                .replace("M", "DD")
                .replace("CD", "CCCC")
                .replace("D", "CCCCC")
                .replace("XC", "LXL")
                .replace("C", "LL")
                .replace("XL", "XXXX")
                .replace("L", "XXXXX")
                .replace("IX", "VIV")
                .replace("X", "VV")
                .replace("IV", "IIII")
                .replace("V", "IIIII").length();
    }
}

The 10 randoms result of the conversion listed below:

18 = XVIII
208 = CCVIII
843 = DCCCXLIII
1995 = MCMXCV
2000 = MM
2017 = MMXVII
2562 = MMDLXII
3276 = MMMCCLXXVI
4067 = MMMMLXVII
4994 = MMMMCMXCIV

How do I align string print out in left, right, center alignment?

The following code snippet will teach you how to align string in left, right or center alignment when you want to print out string to a console. We will print the string using the printf(String format, Object... args) method. The format specifier / parameter defines how the string will be formatted for output and the args is the value that will be formatted.

The format parameter / specifier include flags, width, precision and conversion-characters in the order shown below. The square brackets in the notation means the part is an optional parameter.

% [flags] [width] [.precision] conversion-character
Flags Description
- left-align the output, when not specified the default is to right-align
+ print (+) or (-) sign for numeric value
0 zero padded a numeric value
, comma grouping separator for number greater that 1000
space will output a (-) symbol for negative value and a space if positive
Conversion Description
s string, use capital S to uppercase the strings
c character, use capital C to uppercase the characters
d integer: byte, short, integer, long
f floating point number: float, double
n new line

Width: Defines the field width for printing out the value of argument. It also represents the minimum number of characters to
be printed out to the output.

Precision: For floating-point conversion the precision define the number of digits of precision in a floating point value. For string value this will extract the substring.

To center the string for output we use the StringUtils.center() method from the Apache Commons Lang library. This method will center-align the string str in a larger string of size using the default space character (‘ ‘). You can supply the third parameter to define your own space character / string.

package org.kodejava.lang;

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class StringAlignment {
    private static final Object[][] people = {
            {"Alice", LocalDate.of(2000, Month.JANUARY, 1)},
            {"Bob", LocalDate.of(1989, Month.DECEMBER, 15)},
            {"Carol", LocalDate.of(1992, Month.JULY, 24)},
            {"Ted", LocalDate.of(2006, Month.MARCH, 13)},
    };

    public static void main(String[] args) {
        String nameFormat = "| %1$-20s | ";
        String dateFormat = " %2$tb %2$td, %2$tY  | ";
        String ageFormat = " %3$3s |%n";
        String format = nameFormat.concat(dateFormat).concat(ageFormat);
        String line = new String(new char[48]).replace('\0', '-');

        System.out.println(line);
        System.out.printf("|%s|%s|%s|%n",
                StringUtils.center("Name", 22),
                StringUtils.center("Birth Date", 16),
                StringUtils.center("Age", 6));
        System.out.println(line);

        for (Object[] data : people) {
            System.out.printf(format,
                    data[0], data[1],
                    ChronoUnit.YEARS.between((LocalDate) data[1], LocalDate.now()));
        }

        System.out.println(line);
    }
}

Here is the output of our code snippet above:

------------------------------------------------
|         Name         |   Birth Date   | Age  |
------------------------------------------------
| Alice                |  Jan 01, 2000  |   17 |
| Bob                  |  Dec 15, 1989  |   27 |
| Carol                |  Jul 24, 1992  |   24 |
| Ted                  |  Mar 13, 2006  |   10 |
------------------------------------------------

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.12.0/commons-lang3-3.12.0.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Maven Central

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%.