substring() Method In Java

substring in java is said to be a substring when some part of the string taken from the string. In other words, a substring is a part of a string. substring() method returns the substring starting from the start index from the string.

There are two variety of substring() Method

  1. public String substring(int startIndex): It returns the substring starting from the start index.
  2. public String substring(int startIndex, int endIndex): This method returns the substring starting from the start index to the end index.

Note: The end index will not consider. Suppose you take start index 0 and end index 3 the string will be return from 0 to 2. Let’s better understand by the below example.

substring(int startIndex) Example

public class SubstringExample {
	public static void main(String[] args) {
		String str="study4geeks is a best tutorial website"; 
               // return substring starting from 17th index 
		System.out.println(str.substring(17));
		String str1="study4geeks";  
              // return substring starting from 5th index
		System.out.println(str1.substring(5));
	}
}

output:

best tutorial website
4geeks

substring(int startIndex, int endIndex) Example

public class SubstringExample {
	public static void main(String[] args) {
		String str="study4geeks is a best tutorial website";  
		/*return substring starting from 
		 12th index till 21th index*/
		System.out.println(str.substring(12,21));
		String str1="this is a website";  
		/*return substring starting from 
		 5th index till 14th index*/
		System.out.println(str1.substring(5,14));
	}
}

output:

is a best
is a webs
Do you know?
substring() Method In Java This article is contribute by Study4Geeks If you want share your knowledge on Study4Geeks then go to login section.