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
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.
System.out.println(“subString == subSequence ?:”+str.substring(0, 4)==str.subSequence(0, 4));
The output of this line will be only false.
This article is usefull
what is difference between subString and subSequence?
wat is the use of string subsequence
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.
Could you please explain the output mainly the last two “sysout”
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);