String
slicing is about fetching a sub string from given string. Java String class
provides subString method to fetch a sub string from given string.
subString method
is available in below overloaded forms.
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
Get the
substring from starting index
‘substring(int
beginIndex)’ 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. Here the beginIndex is inclusive.
String str1 = "hello world";
String subStr1 = str1.substring(6);
'subString' method throws StringIndexOutOfBoundsException, if beginIndex is negative or
larger than the length of this String object.
Get the
substring between start and end indexes
‘substring(int beginIndex, int endIndex)’ method
returns a string that is a substring of this string. The substring begins at
the specified beginIndex and extends to the character at index endIndex - 1.
Thus the length of the substring is endIndex-beginIndex. Here the the beginning
index is inclusive and endIndex is exclusive.
String str2 = "Java is a high level programming language";
String subStr2 = str2.substring(10, 14);
'subString' method throws StringIndexOutOfBoundsException, if the beginIndex is negative,
or endIndex is larger than the length of this String object, or beginIndex is
larger than endIndex.
Find the
below working application.
SubStringDemo1.java
package com.sample.app.strings;
public class SubStringDemo1 {
public static void main(String[] args) {
String str1 = "hello world";
String subStr1 = str1.substring(6);
System.out.println("str1 : " + str1);
System.out.println("subStr1 : " + subStr1);
try {
str1.substring(-1);
} catch (StringIndexOutOfBoundsException e) {
System.err.println(e);
}
try {
str1.substring(100);
} catch (StringIndexOutOfBoundsException e) {
System.err.println(e);
}
String str2 = "Java is a high level programming language";
String subStr2 = str2.substring(10, 14);
System.out.println("\nstr2 : " + str2);
System.out.println("subStr2 : '" + subStr2 + "'");
try {
str2.substring(-1, 5);
} catch (StringIndexOutOfBoundsException e) {
System.err.println(e);
}
try {
str2.substring(5, 100);
} catch (StringIndexOutOfBoundsException e) {
System.err.println(e);
}
try {
str2.substring(5, 1);
} catch (StringIndexOutOfBoundsException e) {
System.err.println(e);
}
}
}
Output
str1 : hello world
subStr1 : world
java.lang.StringIndexOutOfBoundsException: begin -1, end 11, length 11
java.lang.StringIndexOutOfBoundsException: begin 100, end 11, length 11
str2 : Java is a high level programming language
subStr2 : 'high'
java.lang.StringIndexOutOfBoundsException: begin -1, end 5, length 41
java.lang.StringIndexOutOfBoundsException: begin 5, end 100, length 41
java.lang.StringIndexOutOfBoundsException: begin 5, end 1, length 41
References
https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/String.html
Previous
Next
Home