Java String.startsWith() Method Example

There are two forms of String.startsWith() methods.
  • startsWith(String prefix)  - Tests if this string starts with the specified prefix.
  • boolean startsWith(String prefix, int toffset)  - Tests if the substring of this string beginning at the specified index starts with the specified prefix.
The startsWith()  method determines whether a given String begins with a specified string.

Java String.startsWith() Method Example

This is a complete example to demonstrate the usage of startsWith()  methods.
public class StartsWithExample {
    public static void main(String[] args) {
        String str = "javaguides";
        boolean startWith = str.startsWith("ja");
        System.out.println("startWith :: " +startWith);
         // Remember index starts from 0
        boolean startWithOffset = str.startsWith("guides", 4);
        System.out.println("startWithOffset :: " + startWithOffset);
    }
}

Output:
startWith:: true startWithOffset:: true 

Reference


Comments