Java Reference Types
Understand Java reference types: objects, arrays, and strings, and how reference values shape assignment, aliasing, and method calls.
Understand Java reference types: objects, arrays, and strings, and how reference values shape assignment, aliasing, and method calls.
Java Reference Types
In Java, a reference value refers to an object; it is not the object itself. Understanding references versus values helps explain assignment, method calls, and shared mutable state.
Introduction
Java variables hold either primitive values or reference values. A reference value refers to an object or array, or it may be null; Java does not promise a particular machine-level representation for it. If you assign String a = new String("hello"); String b = a;, both variables refer to the same object. Any change to a mutable object through b is visible through a too.
Arrays are objects with a .length field and a .clone() method. Cloning an array copies its element values; for an array of references, that means the copied array still refers to the same elements. String literals are interned, while String values remain immutable. A NullPointerException can occur when code dereferences a null reference; use null checks or reject null at an API boundary when it is not a valid input.
This post covers reference values, field and local-variable defaults, equality semantics (== for reference identity vs .equals() for value equality), and Java’s pass-by-value method calls. It also explains string interning, strong and special references, and the difference between shallow and deep copies. Stack and heap pictures are common JVM implementation models; the Java language does not promise a machine-address representation or a storage location for each variable.
When to Use / When Not to Use
Use reference types when:
- You need to model complex data with multiple fields
- You need to share mutable state between parts of your program
- You need to use objects with identity and behavior
- Working with collections that require object elements
Prefer primitives when:
- You need simple, immutable scalar values
- Performance is critical and object allocation overhead is unacceptable
- You’re working with numerical computations where predictability matters
Reference Type Architecture
This diagram shows a common JVM implementation model for stack frames and heap objects. It is a useful mental picture, not a guarantee about physical storage: a runtime may optimize object allocation when doing so does not change program behavior.
graph TD
A["Stack Frame"] --> B["Reference Variable<br/>'obj'"]
B -.-> C["Heap Memory<br/>Object Instance"]
D["Stack Frame"] --> E["Reference Variable<br/>'arr'"]
E -.-> F["Heap Memory<br/>int[3] Array"]
G["String Pool"] --> H["String Literal<br/>'hello'"]
style A stroke:#00fff9,color:#00fff9
style C stroke:#ff00ff,color:#ff00ff
style F stroke:#ff00ff,color:#ff00ff
style G stroke:#00ff00,color:#00ff00
Production Failure Scenarios
| Scenario | Cause | Mitigation |
|---|---|---|
| NullPointerException | Dereferencing null reference | Null checks, Optional, defensive initialization |
| Memory leak via collections | Holding references to unused objects | Clear collections, weak references, profiling |
| Shallow copy issues | Sharing mutable internal objects | Deep copy with clone or copy constructors |
| ArrayStoreException | Assigning wrong type to Object[] | Type checking at compile time with generics |
// NPE prevention patterns
public String safeGetName(User user) {
// Pattern 1: null check
if (user != null) {
return user.getName();
}
return "Anonymous";
// Pattern 2: Optional (Java 8+)
// return Optional.ofNullable(user)
// .map(User::getName)
// .orElse("Anonymous");
}
// Defensive copying for mutable inputs
public class Account {
private final Date createdDate;
public Account(Date creationDate) {
// Defensive copy - don't store the reference
this.createdDate = new Date(creationDate.getTime());
}
public Date getCreatedDate() {
// Return copy to prevent external modification
return new Date(createdDate.getTime());
}
}
Trade-off Table
| Aspect | Reference types | Primitive types |
|---|---|---|
| Null support | A reference value can be null |
No null value |
| Default value | null for fields and array elements; locals need definite assignment |
Type-specific default for fields/arrays |
| Runtime storage | Depends on the JVM and optimization | Depends on the JVM and optimization |
| Copy behavior | The reference value is copied; the object is not | The primitive value is copied |
| Methods | Values refer to objects with methods | Primitive values have no instance methods |
Implementation Snippets
Object Reference Behavior
When you assign a reference variable to another, both variables refer to the same object; the object itself is not copied. A method receives a copy of the reference value, so it can mutate that shared object but cannot change which object the caller’s variable refers to. The examples below show this with assignment, arrays, and wrapper objects.
public class ReferenceDemo {
public static void main(String[] args) {
// Creating objects - reference assignment
String original = new String("hello");
String alias = original; // Both refer to the same object
alias = "world"; // Reassign alias to new object
// original still refers to "hello"
// Using wrapper classes
Integer a = 127; // Auto-boxed
Integer b = 127; // This value is in the required cache range
Integer c = 128; // Identity outside the required range is not guaranteed
System.out.println(a.equals(b)); // true: compare wrapper values
System.out.println(a == 127); // true (unboxing)
// Arrays are objects
int[] numbers = {1, 2, 3};
int[] copy = numbers; // Copy reference, not array
copy[0] = 100; // Modifies original array!
System.out.println(numbers[0]); // 100
// True copy
int[] actualCopy = numbers.clone();
System.out.println(original); // hello
System.out.println(alias); // world
}
}
This example uses Java 5+ autoboxing. Its output is:
true
true
100
hello
world
Aliasing and immutability
An alias to a mutable object can change what every reference sees. Calling a method on an immutable String instead returns a value; the original string stays the same.
public class AliasingDemo {
public static void main(String[] args) {
StringBuilder shared = new StringBuilder("hello");
StringBuilder alias = shared;
alias.append(" world");
String original = "hello";
String changed = original.concat(" world");
System.out.println(shared);
System.out.println(original);
System.out.println(changed);
}
}
This example uses StringBuilder, available since Java 5. Expected output:
hello world
hello
hello world
Reference vs Value Comparison
Java passes every argument value to a method. For a reference type, that value is a reference to an object. The method can mutate the shared object, but reassigning its local parameter does not change which object the caller’s variable refers to. Primitive arguments are copied too, so changing a parameter never changes the caller’s variable.
// Primitive pass-by-value
void increment(int x) {
x = x + 1; // Only local variable affected
}
int num = 5;
increment(num);
System.out.println(num); // 5 (unchanged)
// Reference pass-by-value (reference copy)
void changeString(String s) {
s = "changed"; // Reassigns local reference only
}
String str = "original";
changeString(str);
System.out.println(str); // "original" (unchanged!)
// BUT mutable objects can be modified through reference
void addElement(ArrayList<String> list) {
list.add("new"); // Modifies the actual list
}
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
addElement(names);
System.out.println(names); // [Alice, new]
Aliasing and Immutable Strings
Assigning a mutable reference gives another variable access to the same object. StringBuilder can change that shared object; String cannot. Its concat() method returns a new string, so reassigning one variable leaves the original string alone.
public class AliasingAndImmutability {
public static void main(String[] args) {
StringBuilder original = new StringBuilder("hello");
StringBuilder alias = original;
alias.append("!");
System.out.println(original == alias); // true
System.out.println(original); // hello!
String text = "hello";
String textAlias = text;
textAlias = textAlias.concat("!");
System.out.println(text); // hello
System.out.println(textAlias); // hello!
}
}
Observability Checklist
- Monitor for unexpected null values in reference fields
- Track object creation rate in hot paths
- Profile for memory leaks in collections holding references
- Measure reference equality vs value equality performance
- Log when defensive copies are created in critical paths
// Observability for references
public class ReferenceMonitor {
private final Meter cacheHitRate;
private final Counter nullReferences;
public Object getOrCreate(String key) {
Object ref = cache.get(key);
if (ref == null) {
nullReferences.increment();
ref = createNew(key);
cache.put(key, ref);
}
return ref;
}
}
Common Pitfalls / Anti-Patterns
- Immutability for security: Use immutable objects for sensitive data to prevent modification
- Defensive copies for external data: Never store external references to mutable internal state
- Serialization risks: Reference types in serialization can leak internal state
- Injection attacks: Malicious input via reference-modified objects
// Security pattern: immutable data holder
public final class Credentials {
private final char[] password; // char[] instead of String (can be cleared)
public Credentials(char[] password) {
this.password = Arrays.copyOf(password, password.length);
}
public char[] getPassword() {
return Arrays.copyOf(password, password.length);
}
public void clear() {
Arrays.fill(password, '0');
}
}
-
Confusing == with .equals()
// BAD - comparing references, not values String a = new String("hello"); String b = new String("hello"); if (a == b) { } // false - different objects // GOOD - comparing values if (a.equals(b)) { } // true -
Modifying shared mutable state
// BAD void process(List<String> list) { list.add("unwanted"); // Caller's list modified! } // GOOD - defensive copy void process(List<String> list) { List<String> copy = new ArrayList<>(list); // work with copy } -
Null check missing after assignment
// BAD User user = findUser(id); int age = user.getAge(); // NPE if user is null // GOOD - null-safe int age = (user != null) ? user.getAge() : 0; // or using Optional -
Using raw types in generics
// BAD - raw type, no type safety List list = new ArrayList(); list.add("string"); Integer num = (Integer) list.get(0); // ClassCastException // GOOD - parameterized type List<String> safeList = new ArrayList<>(); safeList.add("string"); // No casting needed
Quick Recap Checklist
- Reference variables hold reference values that refer to objects or are
null - Treat heap/stack diagrams as common JVM implementation models, not Java language guarantees
- Arrays are objects with .length field and clone() method
- String literals are interned; use
.equals()for text comparison - == compares references; .equals() compares values
- Java passes every argument by value; for an object argument, the copied value is a reference
- null means “no object reference” — dereferencing throws NPE
- Reference types have default value null; primitives have type-specific defaults
Interview Questions
.equals() compares character sequences. Use .equals() for value comparisons and == for identity checks or null checks.SoftReference lets the garbage collector clear its referent in response to memory demand; the timing is not a cache policy. A WeakReference does not keep an otherwise unreachable referent alive, but collection timing is not tied to a specific next cycle. A PhantomReference does not let code retrieve its referent; it can be paired with a ReferenceQueue for cleanup coordination after reachability changes. Use a purpose-built cache when you need a predictable eviction policy.ReferenceQueue to coordinate cleanup. Reference processing and collection timing are runtime behavior, so do not use them as a precise lifecycle callback.Object.clone() performs a shallow copy — fields are copied by value for primitives and by reference for objects. For reference types, this means the clone shares the same child objects as the original. To deep copy, you must either implement Cloneable and override clone to recursively clone mutable children, or use copy constructors/factories. Arrays implement clone() and return a new array with copied references (shallow). Arrays.copyOf() and Arrays.copyOfRange() also create shallow copies. For immutable objects like Strings, shallow copy is effectively safe since Strings are immutable.String a = new String("hello"); String b = a;), both variables refer to the same object; no new object is made. Copying an array with clone() or Arrays.copyOf() creates a new array but copies its element references (a shallow copy). Replacing clone[0] affects only the copy. If both arrays contain a reference to the same mutable element, a mutation through either array is visible through the other.void reassign(String s) { s = new String("changed"); } leaves the caller's string variable unchanged. By contrast, void mutate(StringBuilder sb) { sb.append(" added"); } changes the shared StringBuilder object.equals() contract (from Object): reflexive (a.equals(a) is true), symmetric (a.equals(b) implies b.equals(a)), transitive (a.equals(b) and b.equals(c) implies a.equals(c)), consistent (multiple calls return same result if neither object changes), and null handling (a.equals(null) is false). Most reference types (String, Integer, etc.) override equals to compare values. For custom classes, you must override equals to define meaningful equality — by default (inherited from Object) it uses == which is reference identity. When overriding equals, also override hashCode to maintain the contract: equal objects must have equal hash codes.String.hashCode() and equals() for matching. You cannot switch on arbitrary objects using their equals() method — you would need an if-else chain or a Map-based dispatch. For enums, the compiler generates optimized table-based switch bytecode. For objects that override equals, there's no language-level switch support — consider Map<Object, Runnable> dispatch or if-else chains.instanceof operator checks whether a non-null reference refers to an instance of a given type or subtype. For example, null instanceof String is false. Use the check before casting, or use pattern matching (Java 16+) with if (obj instanceof String s) to check and bind the value in one expression.List<String>, Map<String, Integer>, etc. The generic type parameter is erased at runtime (type erasure) to Object or the bound type. At runtime, List<String> and List<Integer> are the same type List. This means you cannot use primitives as type arguments — List<int> is illegal; you must use List<Integer>. Generic arrays cannot be created directly (new List<String>[5] is illegal) due to type erasure and array covariance issues. Use wildcards (?, ? extends T, ? super T) for flexible generic references.null. This is different from primitives which get type-specific defaults (0, false, etc.). Static fields of reference types also default to null. Local variables (method scope) of reference types have no default — the compiler requires initialization before use. This is why uninitialized local reference variables cause compilation errors, but uninitialized instance fields silently become null. Be aware: a null reference only causes an NPE when you attempt to dereference it — just having a null reference stored in a field is not an error itself.int → Integer) via valueOf(), and unboxing converts wrappers to primitives (Integer → int) via xxxValue(). This happens automatically when you pass a primitive where a wrapper is expected, or vice versa. The compiler inserts the conversion calls at the bytecode level. Autoboxing can create new objects (outside the cache range), and unboxing a null throws NPE. Collections, generics, and reflection APIs require wrapper types — autoboxing bridges the gap between primitives and the object system. See the Java Autoboxing and Unboxing article for detailed coverage.String.intern() returns the canonical string for equal content. That can make == true for interned values, but use equals() for text comparison. new String(...) has distinct-object semantics when that distinction is observable; the runtime may optimize away an unobservable allocation. Interning can help when many equal strings are retained, but its memory and performance effects depend on the workload.SoftReference<T> lets the collector clear its referent in response to memory demand. The API requires that all soft references be cleared before the VM throws OutOfMemoryError, but it does not provide a predictable eviction policy. Check ref.get() for null if you use one. For application caches with a defined size or expiration rule, use a cache implementation with an explicit policy.ThreadLocal<T> provides thread-scoped storage — each thread gets its own independent value of type T (a reference type). The ThreadLocal holds a map from thread to value, and thread identity determines which value is retrieved. Reference types stored in ThreadLocal are subject to the same GC behavior as any reference — when no other references exist, the GC can collect the object. ThreadLocal values are not automatically cleared when a thread dies — they persist until the ThreadLocal itself is cleared or the thread is collected. This can cause memory leaks if you store large objects in ThreadLocal and the thread pool reuses threads. Always call threadLocal.remove() in cleanup code.Further Reading
- Java Autoboxing and Unboxing - Automatic primitive-wrapper conversion
- Java Wrapper Classes - Immutable object wrappers and caching
- Java String Class - String immutability and the String Pool
- Java Variables and Constants - Variable declaration and the
finalmodifier - Understanding Java Memory Model - Deep dive into heap, stack, and memory architecture
- Java Object Initialization - Constructor chains, instance initializers, and cleanup
Conclusion
Java reference types — objects, arrays, and strings — use reference values to refer to objects. This distinction shapes assignment, equality, and mutability. Reference variables can hold null; fields and array elements of reference types default to null when they are created.
Key takeaways: == compares reference identity, while .equals() compares logical value (for Strings, this means character content). Arrays are objects with .length and .clone(). Equal string literals are interned, but use .equals() for text. When passing references to methods, Java passes a copy of the reference value; the method can modify a shared mutable object but cannot reassign the caller’s variable.
Understanding references versus values is essential for writing correct code, especially around collection manipulation and defensive copying. For understanding how primitives and references interact through autoboxing, see Java Autoboxing and Unboxing.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.