w3resource logo


Introduction to Java Programming

Java String: substring() Method

Secondary Nav

public String substring(int beginIndex)

The substring() method returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

Examples:

"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)

Java Platform: Java SE 8

Syntax :

substring(int beginIndex)

Parameters:

Name Description Type
beginIndex the beginning index, inclusive. String

Return Value : the specified substring.

Return Value Type: int

Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

Example : Java String substring() Method

The following example shows the usage of java String() method.

public class Example {

public static void main(String[] args)
    {
        String str = "The quick brown fox jumps over the lazy dog.";

        // Get a substring of the above string starting from
        // index 10 and ending at index 26.
        String new_str = str.substring(10, 26);
        System.out.println();
        // Display the two strings for comparison.
System.out.println("old = " + str);
System.out.println("new = " + new_str);
System.out.println();
    }
}

Output:

old = The quick brown fox jumps over the lazy dog.     
new = brown fox jumps

Example of Throws: substring(int beginIndex) Method

IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

Let

 String new_str = str.substring(-10, 26);

in the above example.

Output:

Exception in thread "main" java.lang.StringIndexOutOfBo
undsException: String index out of range: -10          
        at java.lang.String.substring(String.java:1960)
        at Exercise.main(Exercise.java:9)

Java Code Editor:







Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program