Java String substring() method example

HQ » Java Tutorial » java.lang » String » substring() method example
Java String substring() method example 2018-02-19T13:04:18+00:00

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.

Sample Output :

Running the substring() method example source code of java.lang.String class will give you the following output

string substring method example

string substring method example

Exception Scenario :

Suggested Reading List :

 

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close