4.1 Primitives vs. Object Reference Variables
Key Takeaways
A primitive variable holds a primitive value. A reference variable holds a reference to an object or
null.Assignment copies the value after any applicable assignment conversion. Assigning a reference to another compatible reference variable does not clone the object.
Aliasing lets two variables refer to the same object. A mutation through one
StringBuilderalias is visible through the other, while an immutableStringalways retains its original contents.Between compatible references,
==tests whether they refer to the same object or are bothnull. Numeric and boolean operands follow their own equality rules.Reference fields default to null and local primitives cannot hold null; marking a reference variable final prevents reassigning the reference itself, not mutating the referenced object's fields or array elements
Primitive Values and Reference Values
To trace Java SE 8 code, distinguish primitive types (boolean, byte, short, char, int, long, float, double) from reference types such as class, interface, and array types.
In the JVM’s abstract model, each method invocation has a frame with local-variable slots, and the heap is the storage area for objects and arrays. Real JVMs can optimize physical storage. You can trace the program without knowing the object’s address or the JVM’s representation of a reference.
- A local
intcan hold the value42. - A local
StringBuildervariable can hold a reference to a builder ornull. - Each instance of a class has its own instance fields. A primitive field such as
int ageholds a value, while a reference field can link to another object.
What Assignment (=) Actually Copies
Assignment first applies any allowed conversion. For example, long wide = intValue; widens an int, and Integer boxed = intValue; boxes it. When both variables have the same type, follow their values:
- Assigning one primitive variable to another copies the numeric or boolean value. Modifying the copy never alters the original variable.
- Assigning one reference variable to another copies the reference handle, not the heap object. Both variables now point to the exact same object in heap memory—a relationship called aliasing.
public class ReferenceVsPrimitive {
public static void main(String[] args) {
int x = 10;
int y = x; // copies literal value 10
y = 25; // x stays 10
StringBuilder sb1 = new StringBuilder("Java");
StringBuilder sb2 = sb1; // copies reference handle; sb1 and sb2 alias the same object
sb2.append(" 8");
System.out.println(x + " | " + sb1);
}
}
Running ReferenceVsPrimitive prints 10 | Java 8. Because sb1 and sb2 hold copies of the same reference handle, calling sb2.append(" 8") mutates the single StringBuilder instance on the heap, so reading sb1 observes "Java 8".
Aliasing: Mutable Objects vs. Immutable String
Aliasing confuses many candidates when String enters the picture. A String object is immutable: none of its methods alter the character sequence inside an existing String instance. Methods such as concat, toUpperCase, and replace return a result. Some return the original instance when no change is required, such as concat("").
public class StringAliasingDemo {
public static void main(String[] args) {
String s1 = new String("OCA");
String s2 = s1; // s1 and s2 alias the same String instance
s1.concat("8"); // returns a new String "OCA8", which is discarded
System.out.println(s2); // prints: OCA
s1 = s1.concat("8"); // s1 is reassigned to the new String "OCA8"
System.out.println(s1 + " vs " + s2); // prints: OCA8 vs OCA
}
}
Notice the contrast:
- Calling
sb2.append(" 8")on a mutableStringBuilderchanges the shared heap object in place, affecting every alias. - Calling
s1 = s1.concat("8")on an immutableStringmovess1to a differentStringobject whiles2continues pointing to"OCA".
Comparing Values vs. Identities with ==
Apply the equality rule for the operand types:
- Between two primitives:
==compares their values (applying binary numeric promotion when types differ, such asintcompared withcharordouble). - Between two references:
==tests reference identity—whether both variables refer to the same object or are bothnull. It does not compare field contents inside two distinct objects.
int a = 65;
char ch = 'A';
System.out.println(a == ch); // true: both represent numeric value 65
StringBuilder b1 = new StringBuilder("hi");
StringBuilder b2 = new StringBuilder("hi");
StringBuilder b3 = b1;
System.out.println(b1 == b2); // false: two separate heap objects
System.out.println(b1 == b3); // true: both point to the same heap object
String n1 = null;
String n2 = null;
System.out.println(n1 == n2); // true: both references are null
Comparing a primitive directly to an unrelated object reference (such as int x = 5; String s = "5"; boolean same = (x == s);) fails to compile with incomparable types: int and String. By contrast, comparing an Integer wrapper to an int triggers unboxing of the Integer to int and compares their numeric values.
Reference null vs. Primitive Non-Nullability
Only reference variables can hold null. Attempting to assign null to any primitive (int count = null; or boolean flag = null;) triggers a compile-time error (incompatible types: <null> cannot be converted to int).
Remember also how field defaults interact with local variable rules:
- Instance and
staticreference fields automatically default tonullif not explicitly initialized. - Local reference variables have no default value. Writing
String name;inside a method and passingnametoSystem.out.println(name)before assigning it (even assigningnullexplicitly) causes a definite-assignment compile error.
final Object Reference Variables
A common Java SE 8 exam trap equates a final reference variable with an immutable object. Marking a reference variable final locks the reference slot so it cannot be reassigned after initialization—it does not freeze the heap object's internal state.
public class FinalReferenceTrap {
public static void main(String[] args) {
final StringBuilder sb = new StringBuilder("SE");
sb.append(" 8"); // VALID: mutates the heap object
// sb = new StringBuilder("SE 11"); // COMPILE ERROR: cannot assign a value to final variable sb
final int[] scores = {10, 20};
scores[0] = 99; // VALID: mutates an element inside the heap array
// scores = new int[]{1, 2}; // COMPILE ERROR: cannot reassign final reference scores
System.out.println(sb + " -> " + scores[0]); // prints: SE 8 -> 99
}
}
Side-by-Side Comparison: Primitives vs. Object References
| Feature | Primitive Variable | Object Reference Variable |
|---|---|---|
| Value held by the variable | Primitive value such as 42 | Object reference or null |
What = copies | The primitive value itself | The reference handle (creates an alias) |
What == tests | Numeric or boolean equality | Object identity or two null references when both operands are references |
Can hold null? | No (compile-time error) | Yes |
| Default value as a field | 0, 0.0, '\u0000', or false | null |
Effect of final modifier | Variable value cannot change | Reference cannot be reassigned; mutable object fields/elements can still change |
What is the output of compiling and running the following Java SE 8 code snippet?
public class AliasCheck {
public static void main(String[] args) {
int num = 5;
int copy = num;
copy += 3;
StringBuilder sb1 = new StringBuilder("A");
final StringBuilder sb2 = sb1;
sb2.append("B");
System.out.println(num + "-" + sb1 + "-" + sb2);
}
}
8-AB-AB
5-AB-AB
5-A-AB
Compilation fails because final variable sb2 cannot be modified via append
Which statement about null and == in Java SE 8 is accurate?
Assigning null to an uninitialized local char variable sets it to '\u0000'
Comparing two distinct StringBuilder objects that hold identical text with == returns true
An uninitialized local String variable inside a method automatically defaults to null when printed
Comparing two String variables that both hold null with == evaluates to true
Consider the following code inside a main method:
String a = new String("Duke");
String b = a;
a.toLowerCase();
a = a + "!";
System.out.println(a + " " + b);
What does this code print?
Duke! Duke
duke! duke
duke! Duke
Duke! Duke!
Sections you finish are checked off in the contents.