Menu
Topics Index
...
`

startsWith and endsWithString - Java Example Program


startsWith and endsWithString
class StartsWithAndEndsWith
{
    public static void main(String arg[])
    {
        String status = "Merit Campus is a great place to learn, practise and compete";
        if (status.startsWith("Merit")) // LINE A
        {
            System.out.println("status string starts with Merit");
        }
        else
        {
            System.out.println("status string does not start with Merit");
        }
        if (status.startsWith("learn", 33)) // LINE B
        {
            System.out.println("status string contains  substring learn that starts at index 33");
        }
        else
        {
            System.out.println("status string does not contain substring learn");
        }
        if (status.endsWith("compete")) // LINE C
        {
            System.out.println("status string ends with compete");
        }
        else
        {
            System.out.println("status string does not end with compete");
        }
        System.out.println("status starts with merit : " + status.startsWith("merit"));    
    }
}
OUTPUT

status string starts with Merit
status string contains  substring learn that starts at index 33
status string ends with compete
status starts with merit : false

DESCRIPTION

The above program explains the two forms of startswith method and the endswith method. At LINE A, since the String status starts with "Merit", true is returned and hence is the first line of output. At LINE B, status starts with "learn" when a search is done from index 33 and so true is returned. In LINE C, true is returned as status ends with "compete”. In the last line of output false is returned. Since status doesn't start with merit instead it starts with Merit.

THINGS TO TRY
  • What will be the result if an empty string is passed as the argument to these methods? (Always true is returned)
  • Are these methods case-sensitive? Yes, change the argument in LINE A to "MERIT" and observe the result. (false is returned because of the differences in case)
  • Change the parameter compete at LINE C to Compete. This string does not end with compete will be printed. Since there is case difference between c and C.

© meritcampus 2019

All Rights Reserved.

Open In App