java.lang.String substring()
Description :
This java tutorial shows how to use the substring() method of java.lang.String class. This method returns a String datatype which corresponds to a portion of the original string starting from the begin index until the endIndex. If the endIndex is not specified, it is imperative that the endIndex is the String length. Note that since we are dealing with String, the index starts at 0.
Method Syntax :
public String substring(int beginIndex)
public String substring(int beginIndex,int endIndex)
Parameter Input :
DataType | Parameter | Description |
---|---|---|
int | beginIndex | the starting index or position where want to start to cut or substring our String |
int | endIndex | the end index or position where we want to end our cutting or substring our String |
Method Returns :
This method returns a String datatype which corresponds to the part of our string which we cut. If no endIndex is specified, then the end index is assumed to be String length -1.
Exception :
IndexOutOfBoundsException is thrown if the beginIndex is negative or it is larger than the length of the String
Java Code Example :
This example source code demonstrates the use of substring() method of String class. Basically this source code just prints the resultant string after using the substring method of String class. Always remember that the string would never change once it is instantiated thus the expression this.substring(index) would not change the value of String. If we want the value out of the substring method, we should assign it to a new variable.
package com.javatutorialhq.java.tutorial.string; /* * Example java source code on String substring() method */ public class StringSubstringDemo { public static void main(String[] args) { String strExample = "this is an example string"; System.out.println(strExample.substring(5)); System.out.println(strExample.substring(2, 5)); strExample.substring(6); System.out.println("strExample value = "+strExample); String str = strExample.substring(5); System.out.println("str value = "+str); } }
Sample Output :
Running the substring() method example source code of java.lang.String class will give you the following output
Exception Scenario :
Exception in thread "main" is an example string java.lang.StringIndexOutOfBoundsException: String index out of range: -2 at java.lang.String.substring(Unknown Source) at com.teknoscope.java.tutorial.string.StringSubstringDemo.main(StringSubstringDemo.java:13)