☰ Contents How Java Runs

How Java Runs in Summary

Java hands out references in the order objects are created, starting at @1001. Fill in the memory picture for when main finishes.
Names
top level: start = @1001, x = @1002, y = @1003, more =
y.doubled() on , returns @1004
main()
x.addOne() on

Heap
@1001:
@1002: Bag[counts=@1001]
@1003: Bag[counts=]
@1004:
Still at the end of main, what does each expression produce?
x == y
x.equals(y)
start == y.counts
Arrays.equals(start, more)

This test fails. Why?

record Bag(int[] counts) { }
void main() {
  assertEquals(new Bag(new int[]{ 1, 2 }), new Bag(new int[]{ 1, 2 }));
}
  1. The two counts fields hold different arrays, and a record’s equals compares an array field with the array’s own equals, which checks the reference.
  2. assertEquals compares the two Bags with ==.
    assertEquals uses .equals(), not ==. That is why two Cars with only String and int fields passed.
  3. The two arrays have different contents.
    Both arrays are { 1, 2 }. Their contents are the same; they are just two separate arrays.
  4. Records always compare by reference.
    A record with only String and int fields passes this kind of test, like the first Car. It’s the array field that compares by reference.