How can a string be initialized using " "?
JavaStringJava Problem Overview
If String is a class just like any other, how can it be initialized using double quotes?
Java Solutions
Solution 1 - Java
>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
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 - Java
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 - Java
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
Solution 5 - Java
Text inside double quotes creates a literal String
object.
String myString = "Some text";
The code above creates a String
object, using double quotes.
Solution 6 - Java
Strings are very often used in a programming language. Since java is object oriented a string is an object. To avoid the cumbersome new String("someString"); statement everytime you need a string object java allows you to just create a string object by using the string literal.
But you should keep in mind the string equality. Here a short JUnit test to demonstrate what I mean.
@Test
public void stringTest() {
// a string literal and a string object created
// with the same literal are equal
assertEquals("string", new String("string"));
// two string literals are the same string object
assertSame("string", "string");
// a string literal is not the same object instance
// as a string object created with the same string literal
assertFalse("string" == new String("string"));
// java's String.intern() method gives you the same
// string object reference for all strings that are equal.
assertSame("string", new String("string").intern());
}
Solution 7 - Java
- String is a class in Java. You are right about it, so we can always initialize with the new
keyword.
- But when we do something like:
String s = "";
The above statement is marked by the compiler to be a special String object and then JVM during loading of the class (loading is done before initialization), sees this what is known as a string literal, which is stored in a string literal pool.
- So a String can be created using new()
and by the ""
method, but the latter provides a string literal which stays in the heap even when there is no reference to that string object, because it has a reference from the string literal pool.
Solution 8 - Java
Just to mention. A a string literal is a reference to an instance of class String you can write code like this:
"abc".getBytes();"a:b:c".split(":");
"愛".codePointAt(0);
Solution 9 - Java
Java does a two step process for us.
String str = "hello";
is equivalent to
char data[] = {'h', 'e', 'l' , 'l', 'o'};
String str = new String(data);
Like [.NET][1] got a similar thing.
String(Char[]) constructor
does
String(char[] value)
Adding references:-
Solution 10 - Java
Java.lang.String
is not just a class. It's an integral part of the core language. The compiler has syntactic sugar for it. For example, ""
is like an abbreviation for new String("")
. When written ""
the compiler optimizes identical strings to the same instance to save space. "a" + 5 == "a5" ==> true
The compiler has syntactic sugar for a lot of stuff, including not having to box/unbox between object versions and their native types, no parent means Object, default constructor, ...