There are two forms of String.substring() methods.
- String substring(int beginIndex) - Returns a string that is a substring of this string.
- String substring(int beginIndex, int endIndex) - Returns a string that is a substring of this string.
These methods throw IndexOutOfBoundsException- if beginIndex is negative or larger than the length of this String object.
This is a complete example to demonstrate the usage of both substring() methods.
public class SubStringExample {
public static void main(String[] args) {
String str = "javaguides";
// substring from start to end
String subStr = str.substring(0, str.length());
System.out.println("substring from 0 to length of the string : " + subStr);
subStr = str.substring(4);
System.out.println("Sub string starts from index 4 : " + subStr);
// Remember index starts from 0
System.out.println(str.substring(1));
System.out.println("unhappy".substring(2));
System.out.println("Harbison".substring(3));
System.out.println("emptiness".substring(8));
}
}
Output:
substring from 0 to length of the string: javaguides Sub string starts from index 4: guides avaguides happy bison s
Reference
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course