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

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.