Menu
Topics Index
...
`

Get Substring from String - Java Example Program


Get Substring from String
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);    
    }
}
OUTPUT

Merit Campus
Merit

DESCRIPTION

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.

THINGS TO TRY
  • Place the below shown code at LINE A and check the output.
    String s2 = s1.substring(24);
    An IndexOutOfBoundsException is thrown, since the index value is greater than the string length.
  • In LINE B, give same value for both beginIndex and endIndex (An empty string is returned).
  • Place the below code at LINE B and check the output.
    String s2 = s1.substring(11, 10);
    IndexOutOfBoundsException is thrown. Since the endIndex is lesser than the beginIndex.

© meritcampus 2019

All Rights Reserved.

Open In App