In this guide, you will learn about the String substring() method in Java programming and how to use it with an example.
1. String substring() Method Overview
Definition:
The substring() method of Java's String class returns a new string that is a substring of the given string.
Syntax:
1. str.substring(int beginIndex)
2. str.substring(int beginIndex, int endIndex)
Parameters:
- beginIndex: the starting index, inclusive.
- endIndex: the ending index, exclusive.
Key Points:
- The substring starts with the character at the specified beginIndex and extends to the end of the string or up to endIndex - 1 if the second argument is given.
- If beginIndex equals endIndex, the method returns an empty string.
- Indexes are 0-based.
- Throws IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of the string, or beginIndex is larger than endIndex.
2. String substring() Method Example
public class SubstringExample {
public static void main(String[] args) {
String sample = "JavaProgrammingIsFun";
// Extracting substring from index 4 to the end
String sub1 = sample.substring(4);
System.out.println("Substring from index 4: " + sub1);
// Extracting substring from index 4 to 15 (exclusive)
String sub2 = sample.substring(4, 15);
System.out.println("Substring from index 4 to 15: " + sub2);
// Using identical beginIndex and endIndex
String sub3 = sample.substring(5, 5);
System.out.println("Substring from index 5 to 5: '" + sub3 + "'");
}
}
Output:
Substring from index 4: ProgrammingIsFun Substring from index 4 to 15: Programming Substring from index 5 to 5: ''
Explanation:
In the example:
1. The first usage of substring() extracts the substring starting from index 4 to the end of the string, resulting in "ProgrammingIsFun".
2. The second usage extracts a substring starting from index 4 and ending at index 15 (exclusive). This results in the substring "Programming".
3. The third usage demonstrates how using identical values for beginIndex and endIndex yields an empty string.
Related Java String Class method examples
- Java String charAt() example
- Java String concat() example
- Java String contains() example
- Java String endsWith() example
- Java String equals() example
- Java String equalsIgnoreCase() example
- Java String getBytes() example
- Java String indexOf() example
- Java String isEmpty() example
- Java String lastIndexOf() example
- Java String length() example
- Java String replace() example
- Java String split() example
- Java String startsWith() example
- Java String substring() example
- Java String toLowerCase() example
- Java String toUpperCase() example
- Java String trim() example
- Java String valueOf() example
Comments
Post a Comment
Leave Comment