Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between subSequence and subString methods in java String class

Tags:

java

I have a little confusion regarding the difference between subSequence method and subString method in Java String class. I read the article What is the difference between String.subString() and String.subSequence() which was been answered to this question but I have a little confusion, the article mentioned "Its read only in the sense that you can't change the chars within the CharSequence without instantiating a new instance of a CharSequence".

But when I tried with the following example it

String string = "Hello";
CharSequence subSequence = string.subSequence(0, 5);
System.out.println(subSequence.subSequence(1, 4));
subSequence = subSequence.subSequence(1, 4);
System.out.println(subSequence);

it prints
ell
ell

I do not know whether I have understood it correctly. Can you please help me to clarify this and please tell me the difference between subString and subSequence with an example

thanks a lot

like image 317
Dilan Avatar asked Oct 25 '14 08:10

Dilan


1 Answers

As explained in the article you linked to, the only difference between those two methods is the return type. One returns a String and the other returns a CharSequence.

The thing to understand is that CharSequence is an interface, and String is a class which implements CharSequence.

So every String is also a CharSequence, but not vice versa. You can assign the output of substring() to a variable of type CharSequence, but not the other way around:

String string = "Hello";

String subString1 = string.substring(1,4);             // ell
String subString2 = string.subSequence(1, 4);          // Type mismatch compiler error

CharSequence subSequence1 = string.subSequence(1, 4);  // ell
CharSequence subSequence2 = string.substring(1, 4);    // ell

In this particular case, since we're executing the subSequence() method on a String object, the String implementation will be invoked, which just returns a substring():

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

This is what people are talking about when they say the substring() and subSequence() methods are identical when you call them on a String.


Regarding the code you posted, since you started with a String, all your calls to subSequence() are really just substring() calls under the covers. So each time you try to "change" your CharSequence, the compiler is really just creating another String object and passing you a reference to the new one, rather than changing the existing object.

Even though your variable is of type CharSequence, the object it refers to is really a String.

like image 168
azurefrog Avatar answered Sep 28 '22 05:09

azurefrog