How can a string be initialized using " "?
If String is a class just like any other, how can it be initialized using double quotes?
Solution 1:
Java String is Special
The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the call stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces.
For performance reason, Java's String is designed to be in between a primitive and a class.
For example
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object
Note: String literals are stored in a common pool. This facilitates the sharing of storage for strings with the same contents to conserve storage. String
objects allocated via the new
operator are stored in the heap
, and there is no sharing of storage for the same contents.
Solution 2:
Java treats String as a special class, you can initialize in both ways
-
Directly assigning literal
String a = "adsasdf";
-
As other Objects using new keyword
String a = new String("adsasdf");
You need to take special care when you wants to compare with ==
sign:
String a = "asdf";
String b = "asdf";
System.out.println(a == b); // True
System.out.println(a.equals(b)); // True
String a = new String("asdf");
String b = new String("asdf");
System.out.println(a == b); // False
System.out.println(a.equals(b)); // True
That is because in first case the objects a and b are kept in something called literal pool
and they both are referencing same object so they are equal in both ways.
But in second case a and b references different objects like when we initialize any other objects. so they are unequal when compared with ==
operator whereas they are equal in values.
Solution 3:
String gets special treatment in the JLS: it's one of the two non-primitive types for which literals exist (the other is Class
) *.
From the JLS:
A string literal is a reference to an instance of class `String [...].
* well, there's also the "null type" with it's "null literal" null
, but most people don't think of the "null type" as a proper type.
Solution 4:
It's a feature of the Java language. String literals in the source code is given special treatment.
The language spec, here, simply says that a string literal is of String
type