Home » Java Tutorial » Java Substring

Java Substring


Reading Time - 4 mins

Substring() method of String class in Java is used to retrieve a part of the given string. Java Substring method returns a new string based on the index. Substring in Java used extensively for string operations.

Java Substring Syntax

public String substring(int startIndex, int endIndex);

startIndex – The index from which we need to fetch the part of the string. startIndex always starts with 0 from the start of the string.

endIndex – The index until which we need to retrieve the values. endIndex always starts with 1 from the start of the string.

Return value – New substring

Java Substring Exceptions

Substring in Java throws IndexOutOfBoundException in below cases:

  1. when startIndex < 0
  2. when endIndex < startIndex
  3. when endIndex > string length
  4. when startIndex > endIndex

We can use the substring() method in 2 different ways as mentioned below:

Ways of using Java Substring Method

1. Using only startIndex as a parameter

If we want to retrieve a substring from a particular index until the end of the string, then we pass only startIndex as a parameter.

Example

From the given input string, we need to retrieve the string “Java tutorial””. In this case, we pass the startIndex parameter as 11. Since we are not specifying any endIndex, the entire string from index 11 will be returned.

import java.lang.*;
public class substringDemo
{
  public static void main(String[] args)
  {
    String strValue = "Welcome to Java tutorial";
    String strnewValue = strValue.subString(11);
    System.out.println(strnewValue);
  }
}
Output:
Java tutorial

2. Using startIndex and endIndex as parameters

In case we need to fetch a string of specified length, then we pass both startIndex and endIndex as parameters. The below example shows how to fetch the string”Java””.

import java.lang.*;
public class substringDemo
{
  public static void main(String[] args)
  {
    String strValue = "Welcome to Java tutorial";
    String strnewValue = strValue.subString(11,15);
    System.out.println(strnewValue);
  }
}

Output:
Java

Here startIndex is 11 and endIndex is 15, which means it returns a 4 letter word starting from the character “J”. In other words, substring() when used with the endIndex parameter returns a string of length endIndex-startIndex.

READ  Variables in Java

Reference  String Interview Questions

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions