Java String substring() Method Example

1. Introduction

The String.substring() method in Java is used to extract a portion of a string. This method returns a new string that is a substring of the original string, specified by a range of indices. It is invaluable for text processing, parsing, and formatting tasks. This tutorial will show how to use both overloaded versions of the substring() method.

Key Points

- substring(int beginIndex) returns a substring from the specified index to the end of the string.

- substring(int beginIndex, int endIndex) returns a substring from the specified beginning index up to, but not including, the end index.

- The method throws IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

2. Program Steps

1. Declare a string.

2. Extract a substring starting from a specified index.

3. Extract a substring between two specified indices.

4. Print both substrings.

3. Code Program

public class StringSubstringExample {
    public static void main(String[] args) {
        // Original string
        String str = "Hello, world!";
        // Extract substring from index 7 to the end
        String sub1 = str.substring(7);
        // Extract substring from index 0 to 5
        String sub2 = str.substring(0, 5);
        // Print the substrings
        System.out.println("Substring from index 7: " + sub1);
        System.out.println("Substring from index 0 to 5: " + sub2);
    }
}

Output:

Substring from index 7: world!
Substring from index 0 to 5: Hello

Explanation:

1. String str = "Hello, world!": Declares and initializes a String variable str.

2. String sub1 = str.substring(7): Calls the substring() method with the starting index 7, extracting all characters from this position to the end of the string.

3. String sub2 = str.substring(0, 5): Calls the substring() method with the starting index 0 and the ending index 5, extracting characters from the start to just before the fifth index (not including).

4. The print statements output the results of these operations, showing the extracted substrings world! and Hello.


Comments