Java - String Start and End Matching

Introduction

startsWith() checks if the string starts with the specified argument

endsWith() checks if the string ends with the specified string argument.

Both methods return a boolean value.

Demo

public class Main {
  public static void main(String[] args) {
    String str = "This is a Java program";

    // Test str, if it starts with "This"
    if (str.startsWith("This")) {
      System.out.println("String starts with This");
    } else {/*w w w . j a  va 2s . c o m*/
      System.out.println("String does not start with This");
    }

    // Test str, if it ends with "program"
    if (str.endsWith("program")) {
      System.out.println("String ends with program");
    } else {
      System.out.println("String does not end with program");
    }
  }
}

Result

Exercise