Momen Travolta wrote:1)What are other "things" considered to be an object in java?
2) Why is a string literal considered an object?
Welcome to the Ranch
Vedha Vishali wrote: . . .There are two ways to create a String object in Java:
. . .
Vedha Vishali wrote:
1.Creates a new String object "Java" in the String literal pool.
2.Creates a another new String Object out of the String literal pool and the reference variable str points to it.
Yogesh Gnanapraksam wrote:In the above code, according to what Campbell has said there are two identical objects ?
According to Vedha, Only one object with two references ?
Jesper Young wrote: you create a new String object and the contents of the literal string in the pool is copied to that new object.
2.Creates a another new String Object out of the String literal pool and the reference variable str points to it (Points to the new String Object created outside the literal pool).
1.In this step no String object creates.
2.The reference varaible str1 is made to point to the already available String Object("Java") in the literal pool.
Whenever you make a new String,he JVM puts it into a special part of memory called 'String Pool'. If there is already a String
in the String Pool with the same value ,the JVM doesn't create a duplicate ,it simply refers your reference variable to the existing entry.
The JVM can get away with this because Strings are immutable;one reference variable can't change a String's value out from under another reference
variable referring to the same String.
The other issue with String pool is that Garbage Collector doesn't go there.
Yogesh Gnanapraksam wrote:
In my understanding of the above lines,the manner is which the String is initialized (using new or without new) does not make any difference.