Home >>Java String Methods >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.
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); }
public String substring(int startIndex) public String substring(int startIndex, int endIndex)
startIndex - This parameter is used to starting index is inclusive
endIndex - This parameter is used to ending index is exclusive
It is used to returns a specified string
StringIndexOutOfBoundsException if start index is negative value or end index is lower than starting index.
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));
}
}
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));
}
}