Java String startsWith()

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

Example


Syntax of startsWith()

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

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


Example 2: Java startsWith() With Offset Parameter

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.