问题
If it can be initiated with just
String s = "Hello";
then why is it a class? Where's the parameters?
回答1:
Given that String
is such a useful and frequently used class, it has a special syntax (via a string literal representation: the text inside ""
) for creating its instances, but semantically these two are equivalent:
String s = "Hello"; // just syntactic sugar
String s = new String("Hello");
Behind the hood both forms are not 100% equivalent, as the syntax using ""
tries to reuse strings from Java's string pool, whereas the explicit instantiation with new String("")
will always create a new object.
But make no mistake, either syntax will produce a reference to an object instance, strings are not considered primitive types in Java and are instances of a class, like any other.
回答2:
String s = "Hello";
is just syntactical sugar. It's actually implemented as a reference type. (It's an immutable reference type, so you can't change it)
回答3:
From the §4.3.3 of the Java Specification:
String literals are references to instances of class
String
.
And from §3.10.5:
A string literal is a reference to an instance of class
String
回答4:
String s = "Hello";
JVM treats it as:
String s = new String("Hello");
and interns it to String
pool as String
literal.
回答5:
The line you have in the example is creating a String object. There aren't any parameters in the traditional sense that you are thinking of.
来源:https://stackoverflow.com/questions/12717451/why-is-string-a-class