Java Data Type How to - Match a String from Start and End








Question

We would like to know how to match a String from Start and End.

Answer

The startsWith() checks if the string starts with the specified argument, whereas endsWith() checks if the string ends with the specified string argument.

Both methods return a boolean value.

public class Main {
  public static void main(String[] args) {
    String str = "This is a test";
/*from w w w . ja  va  2 s.  c  om*/
    // Test str, if it starts with "This"
    if (str.startsWith("This")) {
      System.out.println("String starts with  This");
    } else {
      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");
    }

  }
}

The code above generates the following result.