String is a class in java. While declaring and assigning string, it is correct to say String name = "Paul" though to instantiate an object from a java class we do String name = new String(); Taking name as an object, I'm wondering why we can assign a series of characters "Paul" to the object. Under what concept does this one works and how does it?
-
It has "special" support from the language itself. Otherwise, you won't be able to do it.nhahtdh– nhahtdh2013-05-14 11:43:20 +00:00Commented May 14, 2013 at 11:43
-
8The Java Language Specifications, section 3.10.5 states: A string literal is always of type String. That's why this works.jlordo– jlordo2013-05-14 11:45:48 +00:00Commented May 14, 2013 at 11:45
-
@zellus: The duplicate does not really answer this question that well, IMO. It doesn't really ask for the difference between them, but why we can do it.nhahtdh– nhahtdh2013-05-14 11:47:05 +00:00Commented May 14, 2013 at 11:47
-
@jlordo: Do you minds expanding that into an answer? I'll remove my community answer if you do.nhahtdh– nhahtdh2013-05-14 11:51:30 +00:00Commented May 14, 2013 at 11:51
-
1@nhahtdh: Edited your answer :P Was too lazy too start over :Djlordo– jlordo2013-05-14 11:56:28 +00:00Commented May 14, 2013 at 11:56
2 Answers
In Java code
"Paul"
is a String literal and
String name
a variable of type String with the name name.
The Java Language Specifications, section 3.10.5 states:
A string literal is always of type
String
As 123 is an int literal and int number is a variable of type int with the name number, following both statements are legal, because the type on the left- and righthand side of the assignments match:
int number = 123;
String name = "Paul";
Comments
That's because implicitly Strings - "..." are treated as objects as well.
Under the cover JVM looks for similar "objects" in so called String pool and then if it finds it there it returns that object (instead of creating new one) otherwise creates new object and puts it to String pool.
This is for memory efficiency, and "Paul" so new String("Paul") is not the same.
This is possible because as we know, strings are immutable in Java.
You can read more about this behavior search for keyword "string pool".