Java String substring() method with Example

In the last tutorial, we will learn how to find substring in Java. Basically, there are two forms of the substring method is used to find the substring in Java. In the previous tutorial, we have learned the first form of the substring method. The first of the substring(int startIndex) method, returns a substring from the specified index to the end of the string. But if you want to return a string that allows you to specify both the beginning and ending index of the substring, then we should go for the second form of the substring method.

The second form of the substring(int startIndex, int endIndex) method returns a new string that is a substring of this string. The substring begins at the specified startIndex and extends to the character at index endIndex-1. Like the first form of the substring(int startIndex) method, it throws StringIndexOutOfBoundsException if the startIndex is negative, or endIndex is larger than the length of this String object, or startIndex is larger than endIndex.

Syntax: The syntax of the second form of the substring method is given below:

public String substring(int startIndex, int endIndex)
Here, startIndex specifies the beginning index, and the endIndex specifies the stopping point.

Example of Java substring() Method:

class SubString{
	public static void main(String args[]){
		String str = "String Tutorial by Javastudypoint is best";
		//returns a new string from specified
		//starting index to ending index.
		//returns Tutorial by Javastudypoint
		System.out.println(str.substring(7,33));
		
	}
}

Output:

Tutorial by Javastudypoint


Note: Remember that it throws StringIndexOutOfBoundsException if the startIndex is negative, or endIndex is larger than the length of this String object, or startIndex is larger than endIndex. Let's see the example:

class SubString{
	public static void main(String args[]){
		String str = "String Tutorial by Javastudypoint is best";
	      //throws exception because in this case
		//starting index is larger than 
		//ending index.
		System.out.println(str.substring(33,7));
	}
}

Output:
Java string substring() method with example

Java String substring() method with Example Java String substring() method with Example Reviewed by Prashant Srivastava on January 06, 2020 Rating: 5

No comments:

Powered by Blogger.