Hello, What is the difference between String s ="Hello" & String s= new String("Hello")
I am asking this question because in some forum i read in 2nd case two objects are created. If that is true , than how ??
Have the determination of mirror which never fails to reflect in spite of being broken into pieces.<br /> <br />Kiss the hands you cannot bite.<br /> <br />An Optimist is one who starts taking a bath when he accidentally falls into the water.
No, the compiler will definitely not create a reference from A to B unless you assign B to A.
I think you mean something else. In this case the compiler creates multiple objects and variables. It creates a normal String object for "hello" which resides on the heap as any other object. Besides because "hello" is known as a String literal at compile time the compiler creates a reference to it in the string literal pool. This is an optimization of the compiler/JVM special to strings. And finally there will be two reference variables A and B which point to the same String "hello" which on the heap. I think it was this you were talking about. There's only one object on the heap because A and B use the same string literal.
Note that, although perfectly legal, it is very rarely necessary or appropriate to use new String("something") constructor. If you are indeed a beginner, you are very unlikely to be in one of those rare situations.
For beginners(*), the semantics of new String("something") are of academic interest only, not practical use.
(*) and most of the time for others, too
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Joined: Feb 28, 2008
Originally posted by Marco Ehrentreich: Hi,
because Java creates a special pool for String literals there are actually two objects created:
1) "Hello" as a string literal in the pool 2) The String object you created with new and assigned it to s
I think the above 2 points contradict in the manner that 2 objects are created on heap and for new operator the object of one is returned to s. So, reference for this should be there in String Pool and another object which is on the heap should be lost.
Now I am really confused. I tried searching for previous post but couldn't really resolves about this issue. Please throw some light on only the above statement.