The substring()
method in Java returns a portion of a string and is used to get substrings in java.
There are two variants for the substring()
method implementation​ in Java.
We specify a start index and the returned substring includes​ characters starting from the specified start index, of the input string, until the end of the string.
stringName.substring(int startIndex)
A visualization​ of this is shown below:
class HelloWorld {public static void main( String args[] ) {String str="edpresso";System.out.println( str.substring(2) );}}
We specify the start index and the end index, ​and the returned substring includes characters including and between the specified indexes. The character at the start index is included, but the character at the end index is not included while getting the substring. So, the characters in the extracted substring begin from start index to end index-1
stringName.substring(int startIndex, int endIndex)
A visualization​ of this is shown below:
class HelloWorld {public static void main( String args[] ) {String str="edpresso";System.out.println( str.substring(2,7) );}}
Note:
substring()
method does not change the original string.
Substring extraction is useful for prefix and suffix extraction. For example, it is helpful in extracting the family name from a name.
Free Resources