Sub string in Java

Method substring() is used for getting a substring of a particular String. There are two variants of this method:

String substring(int beginIndex): Returns the substring starting from the specified index(beginIndex) till the end of the string. For e.g. "Chaitanya".substring(2) would return "aitanya". This method throws IndexOutOfBoundsException If the beginIndex is less than zero or greater than the length of String (beginIndex<0||> length of String).

String substring(int beginIndex, int endIndex): Returns the substring starting from the given index(beginIndex) till the specified index(endIndex). For e.g. "Chaitanya".substring(2,5) would return "ait". It throws IndexOutOfBoundsException If the beginIndex is less than zero OR beginIndex > endIndex OR endIndex is greater than the length of String.

You can get substring from the given string object by one of the two methods:

  1. public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).

  2. public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.

In case of string:

  • startIndex: inclusive
  • endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.

String s="hello"; System.out.println(s.substring(0,2));//he
Example of java substring
public class TestSubstring { public static void main(String args[]){ String s="RamaKrishna"; System.out.println(s.substring(4)); System.out.println(s.substring(0,4)); } }


Output:
Krishna Rama
Another Example of java substring
public class SubStringExample{ public static void main(String args[]) { String str= new String("quick brown fox jumps over the lazy dog"); System.out.println("Substring starting from index 15:"); System.out.println(str.substring(15)); System.out.println("Substring starting from index 15 and ending at 20:"); System.out.println(str.substring(15, 20)); } }


Output:
Substring starting from index 15: jumps over the lazy dog Substring starting from index 15 and ending at 20: jump



Instagram