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

To test if a string starts with a specific word we can use the String.startsWith() method. This method returns a boolean true as the result if the string starts with that specific word.

package org.kodejava.example.lang;

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

        // See if the fox is a quick fox.
        if (str.startsWith("The quick")) {
            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:

Yes, the fox is the quick one

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply