Java Program to check the beginning of a string

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Dec-2018 11:42:05
Advertisements