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

java, pointers

Solution

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.

Problem

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?

Original source

Related problems