Value Types and Reference Types

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

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

  1. Track value copies and reference copies in assignments.
  2. Distinguish between mutation of parameter reassignment.
  3. 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.

University approvals: 0
Tasks
Question 1

What does == compare with two variables of type String (object references)?

Question 2

What effect does reassigning an object parameter within a Java method have?

Question 3

Swap two elements of the same int array by their indices.

Hint

Array elements are read and written with values[i]. A local variable of type int is available for a swap.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy