CODE
class Substring
{
public static void main(String arg[])
{
String s1 = "Welcome to Merit Campus";
String s2 = s1.substring(11); // LINE A
System.out.println(s2);
String s3 = s1.substring(11, 17); // LINE B
System.out.println(s3);
}
}
Merit Campus
Merit
The program shows the two variants of substring
method. In LINE A
, a new string containing characters from index 11
till the end of s1
is returned. In LINE B
, a string containing characters from index 11
to 16
i.e. (17 - 1
) is returned.
LINE A
and check the output. String s2 = s1.substring(24);
IndexOutOfBoundsException
is thrown, since the index value is greater than the string length.
LINE B
, give same value for both beginIndex
and endIndex
(An empty string is returned).LINE B
and check the output.String s2 = s1.substring(11, 10);
IndexOutOfBoundsException
is thrown. Since the endIndex
is lesser than the beginIndex
.