Value Types and Reference Types
Primitive types (int, boolean, ...) store values directly. Reference types store references to objects on the heap. Assigning a reference copies the reference, not the object.
Autoboxing converts int to Integer. Equality: == compares identity for references, while equals compares content (if overridden).
Example: Two new Integer(1000) are not necessarily ==, but equals may return true.
$$x\texttt{.equals}(y)\nRightarrow x\equiv y$$
Where used
Autoboxing in Collections, identity versus equality in caches, why int ends up in hot loops and Integer in Maps. In APIs, value/reference semantics clarify serialization and equality tests.
Depth
Primitive Java values are copied as values upon assignment. In contrast, for objects, the reference is copied, allowing two variables to refer to the same mutable object. A change via one reference is then visible through the other.
Parameter passing always occurs by value copy. In the case of an object parameter, the reference is copied as a value. The method can change the referred object, but reassigning the parameter does not replace the caller’s variable.
Immutable objects reduce the consequences of shared references. Aliasing remains, but is less risky since no observer can change the shared state.
Difficulty levels
- Track value copies and reference copies in assignments.
- Distinguish between mutation of parameter reassignment.
- Control aliasing through immutability or defensive copies.
Pitfalls
Java does not have a call-by-reference mechanism for local variables. == compares references for objects, not automatically their substantive content.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Beginner
- Completed: 0 users