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

JavaObject Oriented ProgrammingProgramming

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.

Syntax

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.

Example

Live Demo

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

Output

me to Tutorials Point
lco
str value: Welcome to Tutorials Point
str1 value: me to Tutorials Point
raja
Published on 01-Jul-2019 12:09:52
Advertisements