Java String subSequence

Filed Under: Java

Java 1.4 introduced the CharSequence interface and String implements this interface. This is the only reason for the implementation of subSequence() method in String class. Internally it invokes the substring() method.

Java String subSequence

java string subsequence

Below code snippet is from String subSequence method implementation.


public CharSequence subSequence(int beginIndex, int endIndex) {
    return this.substring(beginIndex, endIndex);
}

String subSequence method returns a character sequence that is a subsequence of this sequence. An invocation of this method of the form str.subSequence(begin, end) behaves in exactly the same way as the invocation of str.substring(begin, end).

Below is a simple Java String subSequence method example.

StringSubsequence.java


package com.journaldev.examples;

public class StringSubsequence {

	/**
	 * This class shows usage of String subSequence method
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		String str = "www.journaldev.com";
		System.out.println("Last 4 char String: " + str.subSequence(str.length() - 4, str.length()));
		System.out.println("First 4 char String: " + str.subSequence(0, 4));
		System.out.println("website name: " + str.subSequence(4, 14));
		// substring vs subSequence
		System.out.println("substring == subSequence ? " + (str.substring(4, 14) == str.subSequence(4, 14)));
		System.out.println("substring equals subSequence ? " + (str.substring(4, 14).equals(str.subSequence(4, 14))));
	}

}

Output of the above String subSequence example program is:


Last 4 char String: .com
First 4 char String: www.
website name: journaldev
substring == subSequence ? false
substring equals subSequence ? true

There is no benefit in using subSequence method. Ideally, you should always use String substring method.

Comments

  1. Abhishek Kumar Gupta says:

    System.out.println(“subString == subSequence ?:”+str.substring(0, 4)==str.subSequence(0, 4));

    The output of this line will be only false.

  2. NanduShende says:

    This article is usefull

  3. Avi says:

    what is difference between subString and subSequence?

  4. swathi says:

    wat is the use of string subsequence

  5. Rahman says:

    This is because “==” compares the Hash code and “equals” compares the actual content of the objects.

    String class over writes the “equals” method to compare the actual contents of the strings.

  6. Jayasimha says:

    Could you please explain the output mainly the last two “sysout”

  7. HIMANSU NAYAK says:

    I think this is one of the Obsolete Interface in java. Just to add something

    // will always work
    CharSequence s1 = str.subSequence(0, 3);

    // this won’t work
    String s1 = str.subSequence(0, 3);

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages