How to check if the string begins with specific substring in Java?


A String class can be used to represent the character strings, all the string literals in a Java program are implemented as an instance of a String class. The Strings are constants and their values cannot be changed (immutable) once created.

We can use the startsWith() method of String class to check whether a string begins with a specific string or not, it returns a boolean, true or false.

Syntax

public boolean startsWith(String prefix)

Example

public class StringStartsWithSubStringTest {
   public static void main(String[] args) {
      String str = "WelcomeToTutorialsPoint";
      if(str.startsWith("Welcome")) {
         System.out.println("Begins with the specified word!");
      } else {
         System.out.println("Does not begin with the specified word!");
      }
   }
}

Output

Begins with the specified word!
raja
Published on 09-Sep-2019 11:01:58
Advertisements