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
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
and extends to the character at index
(endIndex - 1)
Get Substring from String
public static void main(String arg)
String s1 = "Welcome to Merit Campus";
String s2 = s1.substring(11); // LINE A
String s3 = s1.substring(11, 17); // LINE B
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
16 i.e. (
17 - 1) is returned.
THINGS TO TRY
LINE B, give same value for both
endIndex (An empty string is returned).