CODE
class PrintSubstring
{
public static void main(String arg[])
{
StringBuffer name = new StringBuffer("Soundarya");
String firstPart = name.substring(0, 5);
String secondPart = name.substring(5);
System.out.println(firstPart);
System.out.println(secondPart);
// String thirdPart = name.substring(0, 10); // Won't work // LINE A
}
}
Sound
arya
This program shows the two forms of substring
of StringBuffer
class. The first output line is using the first form of substring
i.e substring(int startindex, int endindex)
. So the output will be Sound i.e starting from 0 position of name
to position 5 of name
("Soundarya") but not including position 5
The second output line is using the second form of substring
i.e using substring(int startindex)
. The output will be arya which implies string starting at position 5 of name
to end of string name
.
LINE A
- to see the
StringIndexOutOfBoundsException
, Since the endIndex 10 is greater than the length of name