Join our newsletter for the latest updates.

Java String startsWith()

The Java String startsWith() method checks whether the string begins with the specified string or not.

The syntax of the string startsWith() method is:

string.startsWith(String str, int offset)

Here, string is an object of the String class.


startsWith() Parameters

The startsWith() method can take two parameters.

  • str - check whether string starts with str or not
  • offset (optional) - checks in a substring of string starting from this index.

startsWith() Return Value

  • returns true if the string begins with the given string
  • returns false if the string doesn't begin with the given string

Example 1: Java startsWith() Without Offset Parameter

class Main {
  public static void main(String[] args) {

    String str = "Java Programming";

    System.out.println(str.startsWith("Java")); // true
    System.out.println(str.startsWith("J")); // true
    System.out.println(str.startsWith("Java Program")); // true

    System.out.println(str.startsWith("java")); // false
    System.out.println(str.startsWith("ava")); // false
  }
}

As you can see from the above example, startsWith() takes case (lower case and upper case) into consideration.


Example 2: Java startsWith() With Offset Parameter

class Main {
  public static void main(String[] args) {

    String str = "Java Programming";

    // checks in substring "a Programming"
    System.out.println(str.startsWith("Java", 3)); // false
    System.out.println(str.startsWith("a Pr", 3)); // true
  }
}

Here, we have passed 3 as an offset. Hence, in the above program, startsWith() checks whether "a Programming" begins with the specified string.


If you need to check whether the string ends with the specified string or not, use the Java String endsWith() method.