I read this previous post. Can any one say what the exact difference between CharSequence and String is, other than the fact that String implements CharSequence and that String is a sequence of character? For example:
CharSequence obj = "hello";
String str = "hello";
System.out.println("output is : " + obj + " " + str);
What happens when “hello” is assigned to obj and again to str ?
General differences
There are several classes which implement the
CharSequenceinterface besidesString. Among these areStringBuilderfor variable-length character sequences which can be modifiedCharBufferfor fixed-length low-level character sequences which can be modifiedAny method which accepts a
CharSequencecan operate on all of these equally well. Any method which only accepts aStringwill require conversion. So usingCharSequenceas an argument type in all the places where you don’t care about the internals is prudent. However you should useStringas a return type if you actually return aString, because that avoids possible conversions of returned values if the calling method actually does require aString.Also note that maps should use
Stringas key type, notCharSequence, as map keys must not change. In other words, sometimes the immutable nature ofStringis essential.Specific code snippet
As for the code you pasted: simply compile that, and have a look at the JVM bytecode using
javap -v. There you will notice that bothobjandstrare references to the same constant object. As aStringis immutable, this kind of sharing is all right.The
+operator ofStringis compiled as invocations of variousStringBuilder.appendcalls. So it is equivalent toI must confess I’m a bit surprised that my compiler
javac 1.6.0_33compiles the+ objusingStringBuilder.append(Object)instead ofStringBuilder.append(CharSequence). The former probably involves a call to thetoString()method of the object, whereas the latter should be possible in a more efficient way. On the other hand,String.toString()simply returns theStringitself, so there is little penalty there. SoStringBuilder.append(String)might be more efficient by about one method invocation.