w3resource

Java String: subSequence() Method

public CharSequence subSequence(int beginIndex, int endIndex)

The subSequence() method returns a character sequence that is a subsequence of this sequence.

Java Platform: Java SE 8

Syntax:

subSequence(int beginIndex, int endIndex)

Parameters:

Name Description
beginIndex the beginning index, inclusive.
endIndex the end index, exclusive.

Return Value: the specified subsequence.

Throws:
IndexOutOfBoundsException - if beginIndex or endIndex is negative, if endIndex is greater than length(), or if beginIndex is greater than endIndex

Pictorial presentation of Java String subSequence() Method

Java String: subSequence() Method

Example: Java String subSequence() Method

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

public class StringSubSequenceExample {

	public static void main(String[] args) {
		String strExample = "The quick brown fox jumps over the lazy dog.";
		CharSequence cstr = strExample.subSequence(4, 10);
		System.out.println();
		System.out.println(cstr);
        System.out.println();
	}

}

Output:

quick

Example of Throws: subSequence(int beginIndex, int endIndex) Method

IndexOutOfBoundsException - if beginIndex or endIndex is negative, if endIndex is greater than length(), or if beginIndex is greater than endIndex

Let

CharSequence cstr = strExample.subSequence(-4, 10);

in the above example.

Output:

Exception in thread "main" java.lang.StringIndexOutOfBo
undsException: String index out of range: -4           
        at java.lang.String.substring(String.java:1960)
        at java.lang.String.subSequence(String.java:200
3)                                                     
        at StringSubSequenceExample.main(StringSubSeque
nceExample.java:5)

Java Code Editor:

Previous:startsWith Method
Next:substring Method