Substring In Java

A substring refers to a segment of a String, essentially a smaller part of the original String. The Java String class includes a predefined method called substring that retrieves a substring from a specified string by utilizing provided index positions. When using the substring method, the starting index is inclusive, while the ending index is exclusive.

If we consider the string as " computer ", the substrings can be "com", "compu", "ter", and so on.

Note: Index starts from 0.

To extract a substring from a String object, you have two methods available:

  1. Utilize the method below to get a substring starting from a specific index:
  2. Example
    
    public String substring(int startIndex)
    

This method creates a new String object that includes the substring of the original string starting from the provided startIndex (inclusive). If the specified startIndex exceeds the length of the String or is less than zero, an IndexOutOfBoundsException will be thrown.

  1. Alternatively, you can use the following method to obtain a substring within a range of indexes:
  2. Example
    
    public String substring(int startIndex, int endIndex)
    

By using this method, a new String object is generated with the substring from the given string, starting from the specified startIndex up to the endIndex. An IndexOutOfBoundsException is thrown if the startIndex is negative, the startIndex is greater than the endIndex, or if the endIndex exceeds the length of the original String.

When dealing with a String:

  • The startIndex is considered inclusive.
  • The endIndex is considered exclusive.

Let's delve into the concepts of startIndex and endIndex through the following code snippet.

Example

String s="hello";  

System.out.println(s.substring(0,2)); //returns he  as a substring

Within the provided substring, index 0 references the initial letter, while index 2 references the second letter, which is 'e' because the end index is exclusive.

Example of Java substring method

TestSubstring.java

Example

public class TestSubstring{  

 public static void main(String args[]){  

 String s="SachinTendulkar";  

 System.out.println("Original String: " + s);

 System.out.println("Substring starting from index 6: " +s.substring(6));//Tendulkar  

 System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6)); //Sachin

 }

}

Output:

Output

Original String: SachinTendulkar

Substring starting from index 6: Tendulkar

Substring starting from index 0 to 6: Sachin

The Java code snippets above showcase different implementations of the substring function from the String class. It is important to note that the starting index is considered inclusive while the ending index is considered exclusive.

Using String.split method:

The split function within the String class is utilized for isolating a portion of text from a sentence, taking into account a regular expression as its parameter.

TestSubstring2.java

Example

import java.util.*;



public class TestSubstring2

{  

    /* Driver Code */

    public static void main(String args[])

    {  

        String text= new String("Hello, My name is Sachin");

        /* Splits the sentence by the delimeter passed as an argument */

        String[] sentences = text.split("\\.");

        System.out.println(Arrays.toString(sentences));

    }

}

Output:

Output

[Hello,  My name is Sachin]

The program above utilizes the split function with an argument of \\. This argument examines the occurrence of 'a' in the sentence and divides the string into separate strings, which are then stored in an array of String objects named sentences.

Java substring MCQ

  1. Given the code snippet provided, what will be the resulting output?
  2. Example
    
    String str = "Java Programming";
    
    System.out.println(str.substring(5));
    
  • Java
  • Programming
  • Java P
  • amming

The Java method substring(5) retrieves and returns a part of a string starting from the 5th index up to the end of the string. In this specific case, the resulting substring is "Programming".

What output can be expected from the provided code snippet?

Example

String str = "SubstringExample";

System.out.println(str.substring(0, str.length() - 1));
  • SubstringExample
  • SubstringExampl
  • Substring
  • SubstringExam

Explanation: Java substring(0, str.length - 1) returns the substring from index 0 to one less than the length of the string, excluding the last character.

  1. If str is "HelloWorld", what does str.substring(str.indexOf('W')) return?
  • Hello
  • World
  • HelloWorld

Explanation: str.indexOf('W') returns the index of 'W', and substring starting from this index gives "World".

  1. Which exception is thrown if the start index is greater than the end index in the substring method?
  • NullPointerException
  • IndexOutOfBoundsException
  • IllegalArgumentException
  • StringIndexOutOfBoundsException

Explanation: If the start index is greater than the end index, StringIndexOutOfBoundsException is thrown.

  1. What does str.substring(1, 1) return if str is "Testing"?
  • "" (empty string)
  • null

The Java substring(1, 1) function will result in an empty string as the start index and end index hold identical values.

Input Required

This code uses input(). Please provide values below: