In this section, we will learn what the String substring() method is and how to use it in Java.
What is Java String substring() Method?
The `substring()` method is used when we want to get a portion or substring of a string value.
For example, we have a message like:
“Nobody ever drowned in his own sweat”
And we want to get the “Nobody ever drowned” part of this message and return it as a new string object. This is where we can use the `substring()` method.
Java substring() Method Syntax:
public String substring(int startIndex) public String substring(int startIndex, int endIndex)
substring() Method Parameters:
- `startIndex`: this is the starting index number from which we want to take a substring at that point.
Note: this index is inclusive.
- `endIndex`: this is the end index where the end of the substring will be.
Notes:
- This end index is exclusive.
- Also, if we don’t set the second argument (endIndex), by default the last index of the target string will be considered as the end of the substring as well.
substring() Method Return Value:
The return value of this method is of type string, which is the substring that we wanted to take out from the target string value.
substring() Method Exceptions:
We will get an exception of type `StringIndexOutOfBoundsException` if we set an index number that is out of the range of the target string value.
Example: using String substring() method
public class Simple { public static void main(String[] args) { String w = "Life is amazing!"; String sub1 = w.substring(8); String sub2= w.substring(0,4); System.out.println(sub1); System.out.println(sub2); } }
Output:
amazing Life
Example: Java String substring() method
public class Simple { public static void main(String[] args) { String w = "Nobody ever drowned in his own sweat"; String sub= w.substring(0,19); System.out.println(sub); } }
Output:
Nobody ever drowned