w3resource logo


Introduction to Java Programming

Java String: subSequence() Method

Secondary Nav

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.

Return Value Type:

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

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:







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

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables