Menu
Topics Index
...
`


Strings > Modifying a String >
Siva Nookala - 01 Apr 2016
The substring method can be used to extract some characters from the String. These substrings can be obtained using indices.

This method comes in two forms:
public String substring(int beginIndex)

Returns a new string that is a substring of this string. The substring begins with the character at the beginIndex and extends to the end of this string.
public String substring(int beginIndex, int endIndex)

This returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index (endIndex - 1).
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.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.