Java String startsWith() Method Tutorial

In this section, we will learn what the String startsWith() method is and how to use it in Java.

What is Java String startsWith() Method?

The `startsWith()` method is used to see if a string value starts with a specific substring.

Java startsWith() Method Syntax:

public boolean startsWith(String str)

boolean startsWith(String str, index fromIndex)

startsWith() Method Parameters:

  • `str`: This is the string that we want to compare it with the target string and see if the target string starts with this string that we set as the argument.
  • `fromIndex`: by default, the comparison starts at the index 0 of the target string. But with this argument we can change the index number. Basically, by this second argument, we can start the comparison from another index of the target string.

startsWith() Method Return Value:

The return value of this method is of type Boolean.

The return value is `true` if they match and `false` otherwise.

startsWith() Method Exceptions:

This method does not throw an exception.

Example: using String startsWith() method

public class Simple {

    public static void main(String[] args)  {
        String w = "Nobody ever drowned in his own sweat";
        System.out.println(w.startsWith("Nobody"));
        System.out.println(w.startsWith("ever",7));
    }
}

Output:

true

true

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies