Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I have 2 reference types, with the same value, does that mean only 1 object in memory

Tags:

java

pointers

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?

like image 284
Dave Avatar asked Nov 27 '22 05:11

Dave


2 Answers

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.

like image 169
ghdalum Avatar answered Dec 05 '22 18:12

ghdalum


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.

like image 43
Joachim Sauer Avatar answered Dec 05 '22 17:12

Joachim Sauer