Java String.startsWith() Method Example

1. Introduction

The String.startsWith() method in Java is used to check if a string starts with a specified prefix. It is a straightforward way to evaluate whether a string begins with certain characters, making it very useful for conditional checks, filtering data, and implementing search features. This tutorial will illustrate how to use the startsWith() method.

Key Points

- startsWith() checks if this string starts with the given prefix.

- It returns a boolean value: true if the string starts with the specified prefix, otherwise false.

- Overloaded methods allow checking from a specified index in the string.

2. Program Steps

1. Declare a string.

2. Check if the string starts with a specific prefix.

3. Print the result.

3. Code Program

public class StringStartsWithExample {
    public static void main(String[] args) {
        // String to check
        String str = "Hello, Java!";
        // Check if the string starts with "Hello"
        boolean startsWithHello = str.startsWith("Hello");
        // Print the result
        System.out.println("Does the string start with 'Hello'? " + startsWithHello);


Does the string start with 'Hello'? true


1. String str = "Hello, Java!": Declares and initializes a String variable str.

2. boolean startsWithHello = str.startsWith("Hello"): Calls the startsWith() method to check if str starts with the prefix "Hello".

3. System.out.println("Does the string start with 'Hello'? " + startsWithHello): Prints the result of the check, displaying true because str does start with "Hello".