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

How do I check a string starts with a specific word?

To test if a string starts with a specific prefix we can use the String.startsWith(String prefix) method. This method returns a boolean true as the result if the string starts with that specified prefix. The String.startsWith() method checks the prefix in case-sensitive manner.

The following code snippet give us a small example how to use this method, but instead of just straightly checks using the startsWith() method, we add a scanner that allows us to input the prefix that we want to test.

package org.kodejava.lang;

import java.util.Scanner;

import static java.lang.System.in;

public class StringStartsWithExample {
    private static final Scanner scanner = new Scanner(in);

    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog";
        System.out.println("Text: " + text);

        System.out.print("Type the prefix to test: ");
        String search = scanner.nextLine();

        // Check if the text start with the search text.
        if (text.startsWith(search)) {
            System.out.println("Yes, the fox is the quick one");
        } else {
            System.out.println("The fox is a slow fox");
        }
    }
}

The code snippet print the following output:

Text: The quick brown fox jumps over the lazy dog
Type the prefix to test: The quick brown fox
Yes, the fox is the quick one

How do I check a string ends with a specific word?

The String.endsWith() method can be used to check if a string ends with a specific word. It will return a boolean true if the suffix is found at the end of the string object.

In this example we will start the code by creating a class called StringEndsWithExample. This class has a standard main() method that makes the class executable. In the main() method we create a string variable called str and assign a text to it.

On the following line you can see an if conditional statement to check it the str string ends with "lazy dog". If it ends with that words then the corresponding block in the if statement will be executed.

package org.kodejava.lang;

public class StringEndsWithExample {
    public static void main(String[] args) {
        String str = "The quick brown fox jumps over the lazy dog";

        // well, does the fox jumps over a lazy dog?
        if (str.endsWith("lazy dog")) {
            System.out.println("The dog is a lazy dog");
        } else {
            System.out.println("Good dog!");
        }

        // Ends with empty string.
        if (str.endsWith("")) {
            System.out.println("true");
        }

        // Ends with the same string.
        if (str.endsWith(str)) {
            System.out.println("true");
        }
    }
}

Another thing that you need to know is that the endsWith() method will return true if you pass in an empty string or another string that is equals to this string as the argument. This method is also case-sensitive.

When you run the code snippet above you can see the following lines printed out:

The dog is a lazy dog
true
true

How do I know the length of a string?

To get the length of a String object we can use the String.length() method. This method returns the string length as an int value. The length of the string is equals to the length of the sequence of characters represented by this string object, and it is equals to the number of 16-bit Unicode characters in the string.

The following code snippet shows how to use the length() method. We create a string object name and assign a text to it. Call the method and store the length returned to the length variable and print it out. We can also use the length() method to check if the string is empty by checking if the length is equals to zero.

package org.kodejava.lang;

public class StringLengthExample {
    public static void main(String[] args) {
        String name = "Kode Java - Learn Java by Examples";

        // Get the length of the string specified by the name
        // variable.
        int length = name.length();
        System.out.println("Length = " + length);

        // Set name to an empty string and test if it is empty.
        name = "";
        length = name.length();
        if (length == 0) {
            System.out.println("The string is empty!");
        }
    }
}

If you run this code you will get the following output:

Length = 34
The string is empty!

How do I check string for equality?

To compare strings for their content equality we must use the String.equals() method. This method ensures that it will compare the content of both string instead of the object reference of the both string. This method returns true if both string in comparison have the same content.

Do not, never, use the == operator to compare string for its content. The == operator check for object reference equality, it returns true only if both objects point to the same reference. This operator returns false if the object doesn’t point to the same references.

package org.kodejava.lang;

public class StringEquals {
    public static void main(String[] args) {
        String s1 = "Hello World";
        String s2 = new String("Hello World");

        // This is good!
        if (s1.equals(s2)) {
            System.out.println("1. Both strings are equals.");
        } else {
            System.out.println("1. Both strings are not equals.");
        }

        // This is bad!
        if (s1 == s2) {
            System.out.println("2. Both strings are equals.");
        } else {
            System.out.println("2. Both strings are not equals.");
        }
    }
}

In the example above we deliberately create an instance of s2 string using the new operator to make sure that we have a different object reference. When you run the program it will give you the following result:

1. Both strings are equals.
2. Both strings are not equals.