Perhaps visualizing the objects involved will help. After the first statement in main, we have:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
After the second statement in main, we have:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
+-----------+ +-------+
| CardBoard | ---> | Short |
c2 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
(theoretically, it's also possible that the two CardBoard share the Short
object, the Javadoc of Short.valueOf
says:
This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
However, the JDK implementation only caches in the range -128 to 127, so we are going to assume that going forward)
Upon entering the go() method, we have:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
+-----------+ +-------+
| CardBoard | ---> | Short |
c2 ----> |-----------| / |-------|
--> | story | / | 200 |
/ +-----------+ +-------+
/
/
cb
and before leaving go(), we have:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
+-----------+ +-------+
| CardBoard | ---> | Short |
c2 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
cb --x
and after the 3rd statement in main, we have:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
+-----------+ +-------+
| CardBoard | ---> | Short |
c2 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
c3 --x
And before leaving main(), we have:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 -x |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
+-----------+ +-------+
| CardBoard | ---> | Short |
c2 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
c3 -x
As we can see, of the 4 objects allocated, 2 remain reachable, and 2 are eligible for collection.