Menu
Topics Index
...
`

SubstringExample String Buffer - Java Example Program


SubstringExample String Buffer
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    
    }
}
OUTPUT

Sound
arya

DESCRIPTION

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.

THINGS TO TRY
  • Print substrings using various indices like (0, 8), (0, 9)
  • Uncomment LINE A - to see the StringIndexOutOfBoundsException, Since the endIndex 10 is greater than the length of name

© meritcampus 2019

All Rights Reserved.

Open In App