How do I get a part or a substring of a string?

The following code snippet demonstrates how to get some part from a string. To do this we use the String.substring() method. The first substring() method take a single parameter, beginIndex, the index where substring start. This method will return part of string from the beginning index to the end of the string.

The second method, substring(int beginIndex, int endIndex), takes the beginning index, and the end index of the substring operation. The index of this substring() method is a zero-based index, this means that the first character in a string start at index 0.

package org.kodejava.lang;

public class SubstringExample {
    public static void main(String[] args) {
        // This program demonstrates how we can take some part of a string 
        // or what we called as substring. Java String class provides 
        // substring method with some overloaded parameter.
        String sentence = "The quick brown fox jumps over the lazy dog";

        // The first substring method with single parameter beginIndex 
        // will take some part of the string from the beginning index 
        // until the last character in the string.
        String part = sentence.substring(4);
        System.out.println("Part of sentence: " + part);

        // The second substring method take two parameters, beginIndex 
        // and endIndex. This method returns the substring start from 
        // beginIndex to the endIndex.
        part = sentence.substring(16, 30);
        System.out.println("Part of sentence: " + part);
    }
}

This code snippet print out the following result:

Part of sentence: quick brown fox jumps over the lazy dog
Part of sentence: fox jumps over

How do I split a string?

Prior to Java 1.4 we use java.util.StringTokenizer class to split a tokenized string, for example a comma separated string. Starting from Java 1.4 and later the java.lang.String class introduce a String.split(String regex) method that simplify this process.

Below is a code snippet how to do it.

package org.kodejava.lang;

import java.util.Arrays;

public class StringSplit {
    public static void main(String[] args) {
        String data = "1,Diego Maradona,Footballer,Argentina";
        String[] items = data.split(",");

        // Iterates the array to print it out.
        for (String item : items) {
            System.out.println("item = " + item);
        }

        // Or simply use Arrays.toString() when print it out.
        System.out.println("item = " + Arrays.toString(items));
    }
}

The result of the code snippet:

item = 1
item = Diego Maradona
item = Footballer
item = Argentina
item = [1, Diego Maradona, Footballer, Argentina]

How do I check if a string is a valid number?

When building a computer program we will use a lot of string to represent our data. The data might not just information about our customer name, email or address, but will also contain numeric data represented as string. So how do we know if this string contains a valid number?

Java provides some wrappers to the primitive data types that can be used to do the checking. These wrappers come with the parseXXX() method such as Integer.parseInt(), Float.parseFloat() and Double.parseDouble() methods.

package org.kodejava.lang;

public class NumericParsingExample {
    public static void main(String[] args) {
        String age = "15";
        String height = "160.5";
        String weight = "55.9";

        try {
            int theAge = Integer.parseInt(age);
            float theHeight = Float.parseFloat(height);
            double theWeight = Double.parseDouble(weight);

            System.out.println("Age    = " + theAge);
            System.out.println("Height = " + theHeight);
            System.out.println("Weight = " + theWeight);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}

In the example code we use Integer.parseInt(), Float.parseFloat(), Double.parseDouble() methods to check the validity of our numeric data. If the string is not a valid number java.lang.NumberFormatException will be thrown.

The result of our example:

Age    = 15
Height = 160.5
Weight = 55.9

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