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!

Updated on: 01-Dec-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements