How do I convert String into Date Object in Java?

The following code shows how we can convert a string representation of date into java.util.Date object.

To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.

package org.kodejava.text;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class ConvertStringToDateExample {
    public static void main(String[] args) {
        String pattern = "dd/MM/yyyy";
        String date = "15/09/2021";

        try {
            DateFormat df = new SimpleDateFormat(pattern);
            Date today = df.parse(date);
            System.out.println("Today = " + df.format(today));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // Using Java 8 Date and Time
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDate localDate = LocalDate.parse(date, formatter);
        System.out.println("Today = " + localDate.format(formatter));
    }
}

And here is the result of our code:

Today = 15/09/2021
Today = 15/09/2021

The example starts by creating an instance of SimpleDateFormat with dd/MM/yyyy format which mean that the date string is formatted in day-month-year sequence.

Finally, using the parse(String source) method we can get the Date instance. Because parse method can throw java.text.ParseException exception if the supplied date is not in a valid format; we need to catch it.

Here are the list of defined patterns that can be used to format the date taken from the Java class documentation.

Letter Date / Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800

How do I compare if two arrays are equal?

Using Arrays.equals() methods we can compare if two arrays are equal. Two arrays are considered to be equal if their length, each element in both arrays are equal and in the same order to one another.

package org.kodejava.util;

import java.util.Arrays;

public class CompareArrayExample {
    public static void main(String[] args) {
        String[] abc = {"Kode", "Java", "Dot", "Org"};
        String[] xyz = {"Kode", "Java", "Dot", "Org"};
        String[] java = {"Java", "Dot", "Com"};

        System.out.println(Arrays.equals(abc, xyz));
        System.out.println(Arrays.equals(abc, java));
    }
}

The Arrays.equals() can be used to compare array of any primitive data type and array of Object. If you run this example you will have a result as follows:

true
false

How do I convert primitive data types into String?

There are times when we want to convert data from primitive data types into a string, for instance when we want to format output on the screen or simply mixing it with other string. Using a various static method String.valueOf() we can get a string value of them.

Here is the code sample:

package org.kodejava.lang;

public class StringValueOfExample {
    public static void main(String[] args) {
        boolean b = false;
        char c = 'c';
        int i = 100;
        long l = 100000;
        float f = 3.4f;
        double d = 500.99;

        String u = String.valueOf(b);
        String v = String.valueOf(c);
        String w = String.valueOf(i);
        String x = String.valueOf(l);
        String y = String.valueOf(f);
        String z = String.valueOf(d);
    }
}

When called with boolean argument the String.valueOf() method return true or false string depending on the boolean argument value. When called with char argument, a 1 length sized string returned.

For int, long, float, double the results are the same as calling Integer.toString(), Long.toString(), Float.toString() and Double.toString() respectively.

How do I create a repeated sequence of character?

This example shows you how to create a repeated sequence of characters. To do this, we use the Arrays.fill() method. This method fills an array of char with a character.

package org.kodejava.util;

import java.util.Arrays;

public class RepeatCharacterExample {
    public static void main(String[] args) {
        char c = '*';
        int length = 10;

        // creates a char array with 10 elements
        char[] chars = new char[length];

        // fill each element of the char array with '*'
        Arrays.fill(chars, c);

        // print out the repeated '*'
        System.out.println(String.valueOf(chars));
    }
}

As the result you get the x character repeated 10 times.

**********

For one-liner code, you can use the following code snippet, which will give you the same result.

public class Test {
    public static void main(String[] args) {
        String str = new String(new char[10]).replace('\u0000', '*');
    }
}

Or

import java.util.Collections;

public class Test {
    public static void main(String[] args) {
        String str = String.join("", Collections.nCopies(10, "*"));
    }
}

How do I use StringTokenizer to split a string?

The code below is an example of using StringTokenizer to split a string. In the current JDK this class is discouraged to be used, use the String.split(...) method instead or using the new java.util.regex package.

package org.kodejava.util;

import java.util.StringTokenizer;

public class StringTokenizerExample {
    public static void main(String[] args) {
        StringTokenizer st =
            new StringTokenizer("A StringTokenizer sample");

        // get how many tokens inside st object
        System.out.println("Tokens count: " + st.countTokens());

        // iterate st object to get more tokens from it
        while (st.hasMoreElements()) {
            String token = st.nextElement().toString();
            System.out.println("Token = " + token);
        }

        // split a date string using a forward slash as delimiter
        st = new StringTokenizer("2021/09/14", "/");
        while (st.hasMoreElements()) {
            String token = st.nextToken();
            System.out.println("Token = " + token);
        }
    }
}

Here is the result of this sample code:

Tokens count: 3
Token = A
Token = StringTokenizer
Token = sample
Token = 2021
Token = 09
Token = 14