How to use the substring() method of java.lang.String class in Java?

The substring() method returns a String datatype which corresponds to the original String starting from the begin index until the end Index. If the end index is not specified, it is imperative that the endIndex is the String length. Since we are dealing with the String, the index starts at '0' position.


public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

beginIndex: the starting index or position where we want to start to cut or substring our String.

endIndex:    the end index or position where we want to end our cutting or substring our String.

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 and an IndexOutOfBoundsException is thrown if the beginIndex is negative or it is larger than the length of the String.


Live Demo

public class StringSubstringTest{
   public static void main(String[] args) {
      String str = "Welcome to Tutorials Point";
      System.out.println(str.substring(2, 5));
      System.out.println("str value: "+ str);
      String str1 = str.substring(5);
      System.out.println("str1 value: "+ str1);


me to Tutorials Point
str value: Welcome to Tutorials Point
str1 value: me to Tutorials Point