They have the following general forms:
boolean startsWith(<code class="code">String</code> str)
boolean endsWith(<code class="code">String</code> str)
str
is the string that is checked for in the beginning and ending of the invoking string in the respective methods.
There is a second form of
startsWith
method that allows you to specify an index of the invoking string as a starting point.
boolean startsWith(<code class="code">String</code> str, int index)
Here it searches for
str
at the index of the invoking string.
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"));
}
}
OUTPUTstatus string starts with Merit
status string contains substring learn that starts at index 33
status string ends with compete
status starts with merit : false
DESCRIPTIONThe 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
.