How to find substring in Java | Java substring() Method

Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the following String methods. which will construct a new copy of the string with your modifications complete. In this tutorial, we will learn how to find substring in Java. A substring is a part of the string. The substring(int startIndex) method of the String class is used to find the substring in java. There are two forms of the substring method. Here, we can discuss only the first form and we will discuss the second form in our next tutorial. It throws StringIndexOutOfBoundsException if the specified index is negative or larger than the length of this String object.

Syntax: The syntax of the substring(int startIndex) method in java is given below:

public String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin. It returns a new string that is a substring of this string. It returns the string from the specified index to the end of the string.



Example of Substring in Java:

class SubString{
	public static void main(String args[]){
		String str = "String Tutorial by Javastudypoint";
		//returns Tutorial by Javastudypoint.
		System.out.println(str.substring(7));
	}
}

Output:

Tutorial by Javastudypoint


Note: Remember that, this method throws StringIndexOutOfBoundsException if the specified index is negative or larger than the length of the string. Let's see the example.

class SubString{
	public static void main(String args[]){
		String str = "String Tutorial by Javastudypoint";
		//throws StringIndexOutOfBoundsException
		//if specified index is negative or 
		//larger than the length of the string.
		System.out.println(str.substring(-1));
		
	}
}

Output:
substring in java
How to find substring in Java | Java substring() Method How to find substring in Java | Java substring() Method Reviewed by Prashant Srivastava on January 06, 2020 Rating: 5

No comments:

Powered by Blogger.