Java String startsWith() example

In this guide, you will learn about the String startsWith() method in Java programming and how to use it with an example.

1. String startsWith() Method Overview

Definition:

The startsWith() method of Java's String class checks if the string starts with the specified prefix. It returns a boolean value indicating the result.

Syntax:

1. str.startsWith(String prefix)

2. str.startsWith(String prefix, int offset)

Parameters:

- prefix: the substring to be matched.

- offset: the index from where to begin looking for the prefix in the string.

Key Points:

- The method is case-sensitive, meaning "JAVA" and "java" are treated as different prefixes.

- When the offset parameter is used, the method checks if the substring of this string beginning at the specified index starts with the specified prefix.

2. String startsWith() Method Example

public class StartsWithExample {
    public static void main(String[] args) {
        String sample = "JavaProgrammingIsFun";

        // Checking if the string starts with "Java"
        boolean startsWithJava = sample.startsWith("Java");
        System.out.println("String starts with 'Java'? " + startsWithJava);

        // Checking if the string starts with "JAVA"
        boolean startsWithJAVA = sample.startsWith("JAVA");
        System.out.println("String starts with 'JAVA'? " + startsWithJAVA);

        // Using offset to check if the string from index 4 starts with "Programming"
        boolean startsWithProgramming = sample.startsWith("Programming", 4);
        System.out.println("Substring from index 4 starts with 'Programming'? " + startsWithProgramming);
    }
}

Output:

String starts with 'Java'? true
String starts with 'JAVA'? false
Substring from index 4 starts with 'Programming'? true

Explanation:

In the example:

1. We check if the string starts with the prefix "Java". The method returns true because the string indeed begins with "Java".

2. We then check if the string starts with the prefix "JAVA". The method returns false because it is case-sensitive, and "JAVA" is not the same as "Java".

3. Finally, we use the offset parameter to check if the substring starting from index 4 (0-based) of our string starts with "Programming". The method returns true as "Programming" is the substring starting from the 4th index of the string.

Related Java String Class method examples

Comments