Java Program to check the beginning of a string



To check the beginning of a string, use the startsWith() method.

Let’s say the following is our string.

String str = "demo";

Now, check for the substring “de” using the startWith() method in an if-else condition.

if(str.startsWith("de")) {
System.out.println("The string begins with the word de");
} else {
System.out.println("The string does not begin with the word de");
}

The following is the complete example with output

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "demo";
      if(str.startsWith("de")) {
         System.out.println("The string begins with the word de");
      } else {
         System.out.println("The string does not begin with the word de");
    }
 }
}

Output

The string begins with the word de
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements