Java Tutorial Java Advanced Java References

Java String - startsWith() Method



The Java startsWith() method is used to check whether this string or substring of this string beginning at the specified index starts with specified prefix or not. It returns true if this string or substring of this string starts with specified prefix, else returns false.

Syntax

public boolean startsWith(String prefix)
public boolean startsWith(String prefix,
                          int toffset)

Parameters

prefix Specify the prefix.
toffset Specify the offset position where to begin looking in this string.

Return Value

Returns true if this string or substring of this string starts with specified prefix, else returns false.

Exception

NA.

Example:

In the example below, startsWith() method is used to check whether the string called MyString starts with specified prefix or not.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Hello World!.";

    System.out.println(MyString.startsWith("Hello")); 
    System.out.println(MyString.startsWith("world")); 
  }
}

The output of the above code will be:

true
false

Example:

In the example below, startsWith() method is used to check whether the substring of the string called MyString starts with specified prefix or not.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Hello World!.";

    //checking whether the substring starts with "World"
    System.out.println(MyString.startsWith("Hello", 6)); 
    System.out.println(MyString.startsWith("World", 6)); 
  }
}

The output of the above code will be:

false
true

❮ Java String Methods