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
?
This question is related to
java
string
charsequence
CharSequence
is a contract (interface), and String
is an implementation of this contract.
public final class String extends Object
implements Serializable, Comparable<String>, CharSequence
The documentation for CharSequence
is:
A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details.
I know it a kind of obvious, but CharSequence is an interface whereas String is a concrete class :)
java.lang.String is an implementation of this interface...
One is an interface (CharSequence
) while other is a concrete implementation of that interface (String
).
CharSequence animal = "cat" // `String` object presented as the interface `CharSequence`.
Just like ArrayList
is a List
, and HashMap
is a Map
, so too String
is a CharSequence
.
As an interface, normally the CharSequence
would be more commonly seen than String
, but some twisted history resulted in the interface being defined years after the implementation. So in older APIs we often see String
while in newer APIs we tend to see CharSequence
used to define arguments and return types.
Nowadays we know that generally an API/framework should focus on exporting interfaces primarily and concrete classes secondarily. But we did not always know this lesson so well.
The String
class came first in Java. Only later did they place a front-facing interface, CharSequence
.
A little history might help with understanding.
In its early days, Java was rushed to market a bit ahead of its time, due to the Internet/Web mania animating the industry. Some libraries were not as well thought-through as they should have been. String handling was one of those areas.
Also, Java was one of the earliest production-oriented non-academic Object-Oriented Programming (OOP) environments. The only successful real-world rubber-meets-the-road implementations of OOP before that was some limited versions of SmallTalk, then Objective-C with NeXTSTEP/OpenStep. So, many practical lessons were yet to be learned.
Java started with the String
class and StringBuffer
class. But those two classes were unrelated, not tied to each other by inheritance nor interface. Later, the Java team recognized that there should have been a unifying tie between string-related implementations to make them interchangeable. In Java 4 the team added the CharSequence
interface and retroactively implemented that interface on String and String Buffer, as well as adding another implementation CharBuffer
. Later in Java 5 they added StringBuilder
, basically a unsynchronized and therefore somewhat faster version of StringBuffer
.
So these string-oriented classes are a bit of a mess, and a little confusing to learn about. Many libraries and interfaces were built to take and return String
objects. Nowadays such libraries should generally be built to expect CharSequence
. But (a) String
seems to still dominate the mindspace, and (b) there may be some subtle technical issues when mixing the various CharSequence
implementations. With the 20/20 vision of hindsight we can see that all this string stuff could have been better handled, but here we are.
Ideally Java would have started with an interface and/or superclass that would be used in many places where we now use String
, just as we use the Collection
or List
interfaces in place of the ArrayList
or LinkedList
implementations.
The key difference about CharSequence
is that it is an interface, not an implementation. That means you cannot directly instantiate a CharSequence
. Rather you instantiate one of the classes that implements that interface.
For example, here we have x
that looks like a CharSequence
but underneath is actually a StringBuilder
object.
CharSequence x = new StringBuilder( "dog" ); // Looks like a `CharSequence` but is actually a `StringBuilder` instance.
This becomes less obvious when using a String literal. Keep in mind that when you see source code with just quote marks around characters, the compiler is translating that into a String object.
CharSequence y = "cat"; // Looks like a `CharSequence` but is actually a `String` instance.
There are some subtle differences between "cat"
and new String("cat")
as discussed in this other Question, but are irrelevant here.
This class diagram may help to guide you. I noted the version of Java in which they appeared to demonstrate how much change has churned through these classes and interfaces.
Other than adding more Unicode characters including a multitude of emoji, in recent years not much has changed in Java for working with text. Until text blocks.
Text blocks are a new way of better handling the tedium of string literals with multiple lines or character-escaping. This would make writing embedded code strings such as HTML, XML, SQL, or JSON much more convenient.
To quote JEP 378:
A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.
The text blocks feature does not introduce a new data type. Text blocks are merely a new syntax for writing a String
literal. A text block produces a String
object, just like the conventional literal syntax. A text block produces a String
object, which is also a CharSequence
object, as discussed above.
To quote JSR 378 again…
Using "one-dimensional" string literals.
String query = "SELECT \"EMP_ID\", \"LAST_NAME\" FROM \"EMPLOYEE_TB\"\n" +
"WHERE \"CITY\" = 'INDIANAPOLIS'\n" +
"ORDER BY \"EMP_ID\", \"LAST_NAME\";\n";
Using a "two-dimensional" block of text
String query = """
SELECT "EMP_ID", "LAST_NAME" FROM "EMPLOYEE_TB"
WHERE "CITY" = 'INDIANAPOLIS'
ORDER BY "EMP_ID", "LAST_NAME";
""";
Text blocks are found in Java 15 and later, per JEP 378: Text Blocks.
First previewed in Java 13, under JEP 355: Text Blocks (Preview). Then previewed again in Java 14 under JEP 368: Text Blocks (Second Preview).
This effort was preceded by JEP 326: Raw String Literals (Preview). The concepts were reworked to produce the Text Blocks feature instead.
In charSequence you don't have very useful methods which are available for String. If you don't want to look in the documentation, type: obj. and str.
and see what methods your compilator offers you. That's the basic difference for me.
From the Java API of CharSequence:
A CharSequence is a readable sequence of characters. This interface provides uniform, read-only access to many different kinds of character sequences.
This interface is then used by String, CharBuffer and StringBuffer to keep consistency for all method names.
other than the fact that String implements CharSequence and that String is a sequence of character.
Several things happen in your code:
CharSequence obj = "hello";
That creates a String
literal, "hello"
, which is a String
object. Being a String
, which implements CharSequence
, it is also a CharSequence
. (you can read this post about coding to interface for example).
The next line:
String str = "hello";
is a little more complex. String
literals in Java are held in a pool (interned) so the "hello"
on this line is the same object (identity) as the "hello"
on the first line. Therefore, this line only assigns the same String
literal to str
.
At this point, both obj
and str
are references to the String
literal "hello"
and are therefore equals
, ==
and they are both a String
and a CharSequence
.
I suggest you test this code, showing in action what I just wrote:
public static void main(String[] args) {
CharSequence obj = "hello";
String str = "hello";
System.out.println("Type of obj: " + obj.getClass().getSimpleName());
System.out.println("Type of str: " + str.getClass().getSimpleName());
System.out.println("Value of obj: " + obj);
System.out.println("Value of str: " + str);
System.out.println("Is obj a String? " + (obj instanceof String));
System.out.println("Is obj a CharSequence? " + (obj instanceof CharSequence));
System.out.println("Is str a String? " + (str instanceof String));
System.out.println("Is str a CharSequence? " + (str instanceof CharSequence));
System.out.println("Is \"hello\" a String? " + ("hello" instanceof String));
System.out.println("Is \"hello\" a CharSequence? " + ("hello" instanceof CharSequence));
System.out.println("str.equals(obj)? " + str.equals(obj));
System.out.println("(str == obj)? " + (str == obj));
}
Consider UTF-8. In UTF-8 Unicode code points are built from one or more bytes. A class encapsulating a UTF-8 byte array can implement the CharSequence interface but is most decidedly not a String. Certainly you can't pass a UTF-8 byte array where a String is expected but you certainly can pass a UTF-8 wrapper class that implements CharSequence when the contract is relaxed to allow a CharSequence. On my project, I am developing a class called CBTF8Field (Compressed Binary Transfer Format - Eight Bit) to provide data compression for xml and am looking to use the CharSequence interface to implement conversions from CBTF8 byte arrays to/from character arrays (UTF-16) and byte arrays (UTF-8).
The reason I came here was to get a complete understanding of the subsequence contract.
Source: Stackoverflow.com