Java String: substring() Method
public String substring(int beginIndex)
The substring() method returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
Examples:
"unhappy".substring(2) returns "happy" "Harbison".substring(3) returns "bison" "emptiness".substring(9) returns "" (an empty string)
Java Platform: Java SE 8
Syntax:
substring(int beginIndex)
Parameters:
Name | Description | Type |
---|---|---|
beginIndex | the beginning index, inclusive. | String |
Return Value : the specified substring.
Return Value Type: int
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
Pictorial presentation of Java String substring() Method
Example: Java String substring() Method
The following example shows the usage of java String() method.
public class Example {
public static void main(String[] args)
{
String str = "The quick brown fox jumps over the lazy dog.";
// Get a substring of the above string starting from
// index 10 and ending at index 26.
String new_str = str.substring(10, 26);
System.out.println();
// Display the two strings for comparison.
System.out.println("old = " + str);
System.out.println("new = " + new_str);
System.out.println();
}
}
Output:
old = The quick brown fox jumps over the lazy dog. new = brown fox jumps
Example of Throws: substring(int beginIndex) Method
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
Let
String new_str = str.substring(-10, 26);
in the above example.
Output:
Exception in thread "main" java.lang.StringIndexOutOfBo undsException: String index out of range: -10 at java.lang.String.substring(String.java:1960) at Exercise.main(Exercise.java:9)
Java Code Editor:
Previous:subSequence Method
Next:toCharArray Method
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-tutorial/string/string_substring.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics