AP Computer Science Exam Review Guide

@McTeach I drew arrows on my exam - didn’t seem to hurt my score.

@MITer94 I don’t know if I explicitly discussed it, because it’s more of an issue in functional programming languages, or in hybrid languages like Scala, that really make serious use of immutability. It does have some important applications in Java (for example, you should not use mutable fields when overriding the Object class’ equals method - see http://www.artima.com/lejava/articles/equality.html), but discussions of this nature are beyond the scope of the AP exam / an introduction to CS. Still, as I extend the guide I may venture into topics that are more advanced, and I’ll add discussions about them.

With particular regard to your example, this is less to do with mutability and more to do with an understanding of Java pointers. The basic structure of an object definition is:

ObjectType objectName = new ObjectType(arg1, arg2, …);

The right-hand side of the assignment is the “value,” i.e. the newly constructed object. The left-hand side of the assignment is the reference, or “pointer,” to which the object is assigned.

The statement “ObjectType objectName2 = objectName” simply creates a new pointer and assigns it to the object to which objectName points. Now there are two pointers, objectName and objectName2, that point to the same object. Thus, when you make changes to objectName, changes are reflected in objectName2. It’s not that there are 2 objects that somehow have their fates intertwined - they are actually the SAME object.

Analogy:

Say Mom gives Tim and Tom a toy to share. Tim identifies the toy as “Tim’s toy.” Tom identifies the toy as “Tom’s toy.” Now say Tom’s toy breaks. What happens to Tim’s toy? It breaks also! Why? It’s the same toy; it just had two different labels.