Home >>Java String Methods >Java String substring() Method

Java String substring() Method

Java String substring() Method

Java substring() method in java string is used to returns a part of the string.

In the java substring method, where start index is inclusive and end index is exclusive, we pass begin index and end index number position. In other words, start index begins from 0 while end index begins from 1.

Internal implementation

public String substring(int beginIndex) 
{  
       if (beginIndex < 0) 
	   {  
           throw new StringIndexOutOfBoundsException(beginIndex);  
       }  
       int subLen = value.length - beginIndex;  
       if (subLen < 0) 
	   {  
           throw new StringIndexOutOfBoundsException(subLen);  
       }  
       return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);  
   }  

Syntax

public String substring(int startIndex)  

public String substring(int startIndex, int endIndex)  

Parameters

startIndex - This parameter is used to starting index is inclusive

endIndex - This parameter is used to ending index is exclusive

Returns

It is used to returns a specified string

Throws

StringIndexOutOfBoundsException if start index is negative value or end index is lower than starting index.

Java String substring() Method Example 1


public class SubstringExample1
{  
public static void main(String args[])
{  
String strln1="Phptpoint";  
System.out.println(strln1.substring(2,4)); 
System.out.println(strln1.substring(2));
}
}  

Output:
pt
ptpoint

Java String substring() Method Example 2


public class SubstringExample2 
{ 
	public static void main(String args[]) 
	{ 
		String n1 = new String("Welcome to phptpoint");
		System.out.print("The extracted substring is : "); 
		System.out.println(n1.substring(10)); 
	} 
}

Output:
The extracted substring is : phptpoint

No Sidebar ads