true and sometimes returns false:6 + 7 == 13 that’s clearly true. So why isn’t trash + " panda" == "trash panda"? And I don’t think it’s fascinating I think it’s annoying! The same thing happens with arrays, look:nums1 = @1001nums2 = @1002nums3 = @1002same1and2 = falsesame1and3 = falsesame2and3 = true@1001: [6, 7]@1002: [6, 7]Hover over an address like @1001 to draw an arrow to its object on the heap; click or tap it to keep the arrow showing.
Prof: OK, so stepping way back – our computers store data in memory. You can think of memory in Java as being split into two parts:
- The stack which holds all the definitions at the top level, all method arguments, and all definitions of variables inside methods
- The heap which holds all created objects. The objects we’ve seen so far are record instances like
Point[...]orStudent[...], arrays, and as it turns out,Strings. When an object is created, like withnewor with{"array", "initialization"}, Java makes space for it on the heap and returns a reference to it. Only the reference actually gets stored in variables, fields, or array elements.
This picture makes that explicit. See the things that look like @1001 and @1002? Those are the references. So we can see that the value stored in nums2 and the value stored in nums3 are the same reference. In contrast, nums1 holds a separate reference to a different array with the same contents.
The last piece we need to understand this is that == compares references, not contents, of objects. So same1and2 is calculating @1001 == @1002, which is false, while same2and3 is calculating @1002 == @1002, which is true.
Whew, that was a lot. What do you think?
tp1 = @1001trash = @1002tp2 = @1003tp3 = @1003same1and2 = falsesame1and3 = falsesame2and3 = true@1001: "trash panda"@1002: "trash"@1003: "trash panda"== on strings compares the references, not the contents, which explains the output.Practice
Java hands out references in the order objects are created, starting at @1001. Fill in the memory picture for this code:
int[] a = { 3, 4 };
int[] b = { 3, 4 };
int[] c = b;
int[] d = a;
boolean ab = a == b;
boolean bc = b == c;
boolean ad = a == d;a =
b =
c =
d =
ab =
bc =
ad =
Heap
@1001: [3, 4]
@1002: [3, 4]
Same rules, starting again at @1001. This time one of the objects holds references of its own:
String word = "hi";
String loud = word + word;
String same = loud;
String[] pair = { word, loud };
boolean match = pair[1] == same;word =
loud =
same =
pair =
match =
Heap
@1001: "hi"
@1002: "hihi"
@1003: [, ]