How to convert java.time.LocalDate to java.util.Date?

The following code snippet demonstrate how to convert java.time.LocalDate to java.util.Date and vice versa. In the first part of the code snippet we convert LocalDate to Date and back to LocalDate object. On the second part we convert LocalDateTime to Date and back to LocalDateTime object.

package org.kodejava.example.datetime;

import java.time.*;
import java.util.Date;

public class LocalDateToDate {
    public static void main(String[] args) {
        // Convert java.time.LocalDate to java.util.Date and back to
        // java.time.LocalDate
        LocalDate localDate =;
        System.out.println("LocalDate = " + localDate);

        Date date1 = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        System.out.println("Date      = " + date1);

        localDate = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        System.out.println("LocalDate = " + localDate);

        // Convert java.time.LocalDateTime to java.util.Date and back to
        // java.time.LocalDateTime
        LocalDateTime localDateTime =;
        System.out.println("LocalDateTime = " + localDateTime);

        Date date2 = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        System.out.println("Date          = " + date2);

        localDateTime = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        System.out.println("LocalDateTime = " + localDateTime);

The result of the code snippet:

LocalDate = 2017-02-14
Date      = Tue Feb 14 00:00:00 WITA 2017
LocalDate = 2017-02-14

LocalDateTime = 2017-02-14T10:34:49.562
Date          = Tue Feb 14 10:34:49 WITA 2017
LocalDateTime = 2017-02-14T10:34:49.562

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 numerals 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.example.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
1995 = MCMXCV
2000 = MM
2017 = MMXVII
2562 = MMDLXII

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 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.example.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 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', '-');

  "Name", 22),
  "Birth Date", 16),
  "Age", 6));

        for (Object[] data : people) {
                data[0], data[1],
                ChronoUnit.YEARS.between((LocalDate) data[1],;


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

<!-- -->

How do I generate random string?


import java.util.Random;

public class RandomString {
    public static final String SOURCES =

    public static void main(String[] args) {
        RandomString rs = new RandomString();
        System.out.println(rs.generateString(new Random(), SOURCES, 10));
        System.out.println(rs.generateString(new Random(), SOURCES, 10));
        System.out.println(rs.generateString(new SecureRandom(), SOURCES, 15));
        System.out.println(rs.generateString(new SecureRandom(), SOURCES, 15));

     * Generate a random string.
     * @param random the random number generator.
     * @param characters the characters for generating string.
     * @param length the length of the generated string.
     * @return
    public String generateString(Random random, String characters, int length) {
        char[] text = new char[length];
        for (int i = 0; i < length; i++) {
            text[i] = characters.charAt(random.nextInt(characters.length()));
        return new String(text);

Example string produced by the code snippets are:


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 method 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.example.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 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.");

    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) {

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

    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.util.Objects.requireNonNull(
    at org.kodejava.example.util.ObjectsNullCheckDemo.(
    at org.kodejava.example.util.ObjectsNullCheckDemo.main(
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(
    at com.intellij.rt.execution.application.AppMain.main(
    at java.util.Objects.requireNonNull(
    at org.kodejava.example.util.ObjectsNullCheckDemo.main(
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(
    at com.intellij.rt.execution.application.AppMain.main(

How do I create a custom TemporalAdjuster?

In this example we are going to learn how to implement a custom TemporalAdjuster. We are going to create TemporalAdjuster to find the next working day from a specified date. We will use 5 working days, from Monday to Friday.

The custom temporal adjuster class should implement the TemporalAdjuster interface, which define a single method that we must implement, the adjustInto(Temporal) method.

package org.kodejava.example.datetime;

import java.time.DayOfWeek;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;

public class NextWorkingDayAdjuster implements TemporalAdjuster {
    public Temporal adjustInto(Temporal temporal) {
        int field = temporal.get(ChronoField.DAY_OF_WEEK);
        DayOfWeek dayOfWeek = DayOfWeek.of(field);

        int daysToAdd = 1;
        if (DayOfWeek.FRIDAY.equals(dayOfWeek)) {
            daysToAdd = 3;
        } else if (DayOfWeek.SATURDAY.equals(dayOfWeek)) {
            daysToAdd = 2;
        return, ChronoUnit.DAYS);

The NextWorkingDayAdjuster move the temporal object a day forward. Except if it is on Friday or Saturday, which will move the temporal object three days or two days forward respectively. This will make it return Monday as the next working day.

After creating the custom adjuster, now let’s create an example that use the NextWorkingDayAdjuster class.

package org.kodejava.example.datetime;

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

public class NextWorkingDayAdjusterDemo {
    public static void main(String[] args) {
        TemporalAdjuster nextWorkingDay = new NextWorkingDayAdjuster();

        LocalDate now =;
        LocalDate nextDay = now.with(nextWorkingDay);
        System.out.println("now            = " + now);
        System.out.println("nextWorkingDay = " + nextDay);

        LocalDate friday = LocalDate.of(2016, Month.MARCH, 11);
        nextDay = friday.with(nextWorkingDay);
        System.out.println("friday         = " + friday);
        System.out.println("nextWorkingDay = " + nextDay);

        LocalDate saturday = LocalDate.of(2016, Month.MARCH, 12);
        nextDay = saturday.with(nextWorkingDay);
        System.out.println("saturday       = " + saturday);
        System.out.println("nextWorkingDay = " + nextDay);

And here are the results of our code:

now            = 2016-03-10
nextWorkingDay = 2016-03-11
friday         = 2016-03-11
nextWorkingDay = 2016-03-14
saturday       = 2016-03-12
nextWorkingDay = 2016-03-14

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 user 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.example.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 manipulate LocalDate object using TemporalAdjuster?

In the previous example we manipulate the value of LocalDate by adding or subtracting the value of date object by days, months, years using methods like plusMonths() or minusDays(). Or by changing the year or the month of the date object using methods like withYear() or withMonth().

But there are times that we want to manipulate the date object so that we can get the first day of the month or the last day of the month. We want to manipulate the date value to advance the date to the first Monday after the current day or the last the of the year.

To manipulate the date object in this way we can use the with() method and pass a TemporalAdjuster object as an argument. Fortunately, the Date and Time API already provide some commonly used TemporalAdjuster. These TemporalAdjuster are provided as a static factory methods that we can find in the java.time.temporal.TemporalAdjusters class.

The following example is a code snippet to manipulate the date object using TemporalAdjuster / TemporalAdjusters class.

package org.kodejava.example.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public class DateManipulationWithTemporalAdjuster {
    public static void main(String[] args) {
        LocalDate date =;
        System.out.println("Current date       = " + date);

        LocalDate date1 = date.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("First day of month = " + date1);

        LocalDate date2 = date.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("Last day of month  = " + date2);

        LocalDate date3 = date.with(;
        System.out.println("Next Monday        = " + date3);

        LocalDate date4 = date.with(TemporalAdjusters.lastDayOfYear());
        System.out.println("Last day of year   = " + date4);

The result of the code snippet are:

Current date       = 2016-03-06
First day of month = 2016-03-01
Last day of month  = 2016-03-31
Next Monday        = 2016-03-07
Last day of year   = 2016-12-31

The table below shows the complete of static factory method provided by the TemporalAdjusters class.

Method Name Method Description
dayOfWeekInMonth Returns a new date in the same month with the ordinal day-of-week.
firstDayOfMonth Returns a new date set to the first day of the current month.
firstDayOfNextMonth Returns a new date set to the first day of the next month.
firstDayOfNextYear Returns a new date set to the first day of the next year.
firstDayOfYear Returns a new date set to the first day of the current year.
firstInMonth Returns a new date in the same month with the first matching day-of-week.
lastDayOfMonth Returns a new date set to the last day of the current month.
lastDayOfYear Returns a new date set to the last day of the current year.
lastInMonth Returns a new date in the same month with the last matching day-of-week.
next Returns the next day-of-week adjuster.
nextOrSame Returns the next-or-same day-of-week adjuster.
ofDateAdjuster Returns user-written adjuster.
previous Returns the previous day-of-week adjuster.
previousOrSame Returns the previous-or-same day-of-week adjuster.

How do I manipulate the value of LocalDate object?

In the following example we will learn how to manipulate a LocalDate object. There are many methods available for us to change the value of a LocalDate object. For example we can change the year, month and day of LocalDate object. We can use methods like withYear(), withDayOfMonth(), plusYears(), minusMonths(), etc. All these methods will return a new LocalDate object, the original LocalDate will stay unchanged.

Let’s see the following code example for demonstration on how to manipulate the value of LocalDate object.

package org.kodejava.example.datetime;

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

public class LocalDateManipulation {
    public static void main(String[] args) {

    private static void relativeAttributeManipulations() {
        LocalDate date1 = LocalDate.of(2015, Month.AUGUST, 17);
        LocalDate date2 = date1.minusYears(70);
        LocalDate date3 = date2.plusMonths(10);
        LocalDate date4 = date3.minusDays(15);
        LocalDate date5 = date4.plusWeeks(52);
        LocalDate date6 = date5.minus(52, ChronoUnit.WEEKS);

        System.out.println("of(2015, Month.AUGUST, 17)        => " + date1);
        System.out.println("date1.minusYears(70)              => " + date2);
        System.out.println("date1.plusMonths(10)              => " + date3);
        System.out.println("date3.minusDays(15)               => " + date4);
        System.out.println("date4.plusWeeks(52)               => " + date5);
        System.out.println("date5.minus(52, ChronoUnit.WEEKS) => " + date6);


    private static void absoluteAttributeManipulations() {
        LocalDate date1 = LocalDate.of(2016, Month.JANUARY, 1);
        LocalDate date2 = date1.withYear(2010);
        LocalDate date3 = date2.withMonth(Month.DECEMBER.getValue());
        LocalDate date4 = date3.withDayOfMonth(15);
        LocalDate date5 = date4.with(ChronoField.DAY_OF_YEAR, 100);

        System.out.println("of(2016, Month.JANUARY, 1)                 => " + date1);
        System.out.println("date1.withYear(2010)                       => " + date2);
        System.out.println("date2.withMonth(Month.DECEMBER.getValue()) => " + date3);
        System.out.println("date3.withDayOfMonth(15)                   => " + date4);
        System.out.println("date4.with(ChronoField.DAY_OF_YEAR, 100)   => " + date5);

The results of this code snippet are:

of(2016, Month.JANUARY, 1)                 => 2016-01-01
date1.withYear(2010)                       => 2010-01-01
date2.withMonth(Month.DECEMBER.getValue()) => 2010-12-01
date3.withDayOfMonth(15)                   => 2010-12-15
date4.with(ChronoField.DAY_OF_YEAR, 100)   => 2010-04-10

of(2015, Month.AUGUST, 17)        => 2015-08-17
date1.minusYears(70)              => 1945-08-17
date1.plusMonths(10)              => 1946-06-17
date3.minusDays(15)               => 1946-06-02
date4.plusWeeks(52)               => 1947-06-01
date5.minus(52, ChronoUnit.WEEKS) => 1946-06-02

How do I load file from resource directory?

In the following code snippet we will learn how to load files from resource directory or folder. Resource files can be in a form of image, audio, text, etc. Text resource file for example can be use 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.


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.


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 {
    Properties properties = new Properties();

    // Load resource relatively to the LoadResourceFile package.
    // This actually load resource from 
    // "/org/kodejava/example/lang/database.conf".
    URL resource = getClass().getResource("database.conf");
    properties.load(new FileReader(new File(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");
    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 {
    Properties properties = new Properties();

    // When using the ClassLoader method the resource name should
    // not 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(new File(resource.getFile())));
    System.out.println("JDBC URL: " + properties.get("jdbc.url"));

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

Below is the main program that calls the methods above.

package org.kodejava.example.lang;

import java.util.Properties;

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

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





The result of this code snippet are:

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

JDBC URL: jdbc:mysql://localhost/kodejava
JDBC URL: jdbc:mysql://localhost/kodejava