Skip to content

Substring

In Java, a substring is a portion of a string extracted from the original string. The String class provides methods like substring() to extract substrings efficiently. Substrings are immutable, just like strings in Java.


substring() Method

The substring() method is used to extract a part of the string, starting at a specific index and optionally ending at another index.

Method Signatures

  1. substring(int beginIndex)
    1. Extracts the substring starting from beginIndex to the end of the string.
  2. substring(int beginIndex, int endIndex)
    1. Extracts the substring from beginIndex (inclusive) to endIndex (exclusive).

Examples of substring()

1. Extracting with Start Index

String str = “Hello World”;

String result = str.substring(6); // “World”

System.out.println(result);

  • Starts extraction at index 6.
  • Includes all characters until the end of the string.

2. Extracting with Start and End Index

String str = “Hello World”;

String result = str.substring(0, 5); // “Hello”

System.out.println(result);

  • Extracts characters from index 0 to 4 (5 is exclusive).

3. Edge Cases

  • Empty Substring: If beginIndex == endIndex, the substring is empty:

String str = “Hello”;

String result = str.substring(2, 2); // “”

System.out.println(result.isEmpty()); // true

  • Entire String: If beginIndex == 0 and endIndex == str.length(), the result is the original string:

String str = “Hello”;

String result = str.substring(0, str.length()); // “Hello”

System.out.println(result);

  • Error Cases:
    • beginIndex < 0
    • endIndex > str.length()
    • beginIndex > endIndex These cases throw a StringIndexOutOfBoundsException:

String str = “Hello”;

System.out.println(str.substring(-1, 3)); // Exception


Applications of substring()

1. Extracting a Portion of a String

String email = “user@example.com”;

String domain = email.substring(email.indexOf(‘@’) + 1);

System.out.println(domain); // “example.com”

2. Parsing Strings

String data = “ID:12345;Name:John”;

String id = data.substring(3, 8); // “12345”

System.out.println(id);

3. Reversing a Substring

String str = “abcdef”;

String reversed = new StringBuilder(str.substring(1, 4)).reverse().toString();

System.out.println(reversed); // “cba”


Performance Considerations

  1. Memory Efficiency (Before Java 7u6):
    1. Substrings shared the original string’s char[] array, which saved memory but could retain unused parts of the string.
    1. Example:

String str = “Hello World”;

String sub = str.substring(6);

Here, sub references the same character array as str.

  • Independent Substring (Java 7u6+):
    • Substrings now have their own char[] array, preventing memory leaks but using more memory for the substring.

Using Substring with Loops

To extract multiple substrings, you can use a loop:

Example:

String str = “abcdefgh”;

int length = 3;

for (int i = 0; i < str.length(); i += length) {

    String part = str.substring(i, Math.min(i + length, str.length()));

    System.out.println(part);

}

Output:

abc

def

gh


Difference Between substring() and split()

Featuresubstring()split()
PurposeExtracts a part of the string based on indices.Divides the string into parts based on a delimiter.
InputIndexes (beginIndex, endIndex).Regular expression or delimiter.
OutputA single string.An array of strings.

Example:

String str = “apple,banana,cherry”;

String sub = str.substring(6, 12); // “banana”

String[] parts = str.split(“,”); // [“apple”, “banana”, “cherry”]


Common Mistakes

  1. Index Out of Bounds: Ensure beginIndex and endIndex are valid:

String str = “Hello”;

String result = str.substring(10); // Throws exception

  • Overlapping Indexes: If beginIndex > endIndex, an exception occurs:

String str = “Hello”;

String result = str.substring(3, 2); // Exception


Example Code

public class SubstringExample {

    public static void main(String[] args) {

        String str = “Java Programming”;

        // Extract “Java”

        System.out.println(str.substring(0, 4)); // “Java”

        // Extract “Programming”

        System.out.println(str.substring(5)); // “Programming”

        // Extract “Program”

        System.out.println(str.substring(5, 12)); // “Program”

        // Error: Out of bounds

        try {

            System.out.println(str.substring(20)); // Exception

        } catch (StringIndexOutOfBoundsException e) {

            System.out.println(“Invalid index: ” + e.getMessage());

        }

    }

}

Output:

Java

Programming

Program

Invalid index: begin 20, end 16, length 16


Conclusion

  • The substring() method is a powerful tool for extracting parts of a string in Java.
  • It supports a variety of use cases, from simple text manipulation to complex parsing tasks.
  • Use it carefully to avoid common pitfalls like invalid indexes or overlapping bounds.