In this post, we feature a comprehensive Substring Java Example. We will show how to use Java
String substring() API method.
substring() method can be expressed in two ways:
String substring(int start, int end)
String substring(int start)
This parameter is mandatory and it specifies the starting position of the extracted string. Note that first character of string is at index 0 not 1.
This parameter is optional and it specifies the end position of the extraction. Note that the index of end position is not included in the extraction.
end parameter is missing, then the extraction starts from the starting position to the rest of the string.
You can also check the Java String Class Example in the following video:
3. Return value
The return value of
substring() method is the extracted string.
4. Substring Java Example
Create a java class named
SubstringExample.java with the following code:
Initial string is: Javacodegeeks Start position=4 and no end position specified: codegeeks Start position=2 and end position=11: vacodegee Start position=3 and end position=3: true Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2 at java.lang.String.substring(Unknown Source) at SubstringExample.main(SubstringExample.java:22)
As we see in the output, the
substring() method usage is exactly what we described in the previous sections. In the first case, end parameter is omitted, so the extracted string starts from position 2 till the rest of the string.
In the second case, both parameters are defined.
In the third case, we can see that if start position is equal to the end position, then the extracted string is empty.
In the last two cases, we can see that if one of the parameters is less than 0 or start position is greater than end position, then we will have
5. Download the source code
This was an example of Substring Java method.
Download the source code of this example: Substring Java Example
Last updated on Jan. 09, 2020