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?
In your example they reference to the same object, because the strings are interned.
In general, usage of new creates new objects, thus using:
String str1 = new String("dave");
String str2 = new String("dave");
would create two different objects in the heap.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With