Single character String
My opinion was, until today, that a literal like "c"
creates a String
object. Today I heard that Java is no开发者_如何学Ct creating an object for single character strings. Is this right? Does it store that literal as a char
?
No it's wrong. Even ""
, creates a String
object.
However if you type 'c'
, you got a char and not a String
object.
"c"
will create a string. 'c'
will create a char
Java does create an instance of a string even for a single character string. The following prints java.lang.String
:
public class Test{
public static void main(final String[] args){
System.out.println("c".getClass().getName());
}
}
"c"
is a String
literal. It represents a String
just as "foo"
represents a String
.
There is no special handling of single-character String
literals (not even of the 0-letter String
literal ""
).
Whoever told you that it's treated differently was either a.) wrong or b.) talking about something different (a library that has special treatment, for example).
"c"
does create an object. However, if you assign the literal again in somewhere in the source code, it will not create a new object, but reference the first string object created.
For example:
String s1 = "abc"; //creates the String object
String s2 = "abc"; //references the same object as s1
Both s1 and s2 are assigned the same object, and == would work.
You can read more here: http://javatechniques.com/blog/string-equality-and-interning/
Maybe what was meant was that the beneath the hood flyweights are created (dunno how this works with Java, but I presume that this concept is employeed at some level for strings)
String
stores characters as a char[]
, so most likely "c"
will be represented as new char[] { 'c' }
within the String
object.
Since the String
class is final
, it means there is no subclass storing single-character strings in a char c
field.
Also, there is no concept of auto-boxing/unboxing for a single-character String
to char
-- as far as it is documented, so it is safe to assume single-character Strings are stored similar to any other type of String.
As with most things in programming look at the source -> java.lang.String.
All Strings are instances of java.lang.String there is no special case. Each and every java.lang.String includes a char[] and some integers to hold the start and end indexes. Note the char[] is shared between Strign instances such as when one does a String.substring() the original char[] is not cloned or copied it is shared but the start/end indexes are updated.
精彩评论