Reputation: 8451
I'm new to Java and have read a conflicting statement to what I believe. Please consider the following code.
String str1 = "dave";
String str2 = "dave";
Both str1 and str2, although unique variables, reference the exact same value. So, how many unique objects are created in memory? 1 or 2 and can some one explain why?
Upvotes: 4
Views: 3195
Reputation: 159754
You have one unique Object
& 2 references pointing to the same object. This is as a result of String
pooling (or interning). Given that both String
literals have identical content, the only way to ensure that 2 separate Objects
could be created would be to to explicitly invoke one of the String
constructors.
Upvotes: 9
Reputation: 308001
It's not so complicated. Except if you're talking about Strings ;-)
First, let's ignore Strings and assume this simple type:
public class ValueHolder {
private final int value;
public ValueHolder(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
If you have two lines like this:
ValueHolder vh1 = new ValueHolder(1);
ValueHolder vh2 = new ValueHolder(1);
then you'll have created exactly 2 objects on the heap. Even though they behave exactly the same and have the exact same values stored in them (and can't be modified), you will have two objects.
So vh1 == vh2
will return false
!
The same is true for String
objects: two String
objects with the same value can exist.
However, there is one specific thing about String
: if you use a String
literal(*) in your code, Java will try to re-use any earlier occurance of this (via a process called interning).
So in your example code str1
and str2
will point to the same object.
(*) or more precisely: a compile-time constant expression of type String
.
Upvotes: 10
Reputation: 1873
You are writing a short-hand version of this
String str1 = new String("dave");
String str2 = new String("dave");
So str1 and str2 are different objects and may be modified separately as such
"dave", the original string, exists once only in memory, with another reference.
Upvotes: 0
Reputation: 568
it depends. if you write a little test program, then there's a very good chance that they will contain the same reference, because java is trying to do you a favor by saving memory and reusing references. if str2 came from user input, then it would likely be two different references. a good way to test is to use == in a comparison. if the two are ==, then they are referencing the same memory location. if they are not, then they are two different references. this throws off a lot of beginning programmers because when they first start writing code, they use ==, see that it works, then down the road can't figure out why their comparisons aren't working.
i can't explain specifically when java does reuse references "behind the scenes" but it's related to how and when the values are created
Upvotes: 0