Careeroza
Reference Types
Primitive vs Reference
| Primitive | Reference | |
|---|---|---|
| Examples | int, double, boolean | String, arrays, Scanner, your classes |
| Stores | the value itself | a reference to an object on the heap |
| Can be null? | no | yes |
| Has methods? | no | yes (name.length()) |
| Name style | lowercase | starts with a capital letter |
| Default value (fields) | 0 / false | null |
Copying Values vs Copying References
Example
Assigning a primitive copies the value. Assigning a reference copies the arrow, so both variables point to the same object.
public class Main {
public static void main(String[] args) {
int a = 10;
int b = a; // copy of the value
b = 20;
System.out.println("a = " + a + ", b = " + b);
int[] marks1 = {70, 80, 90};
int[] marks2 = marks1; // copy of the reference (same array!)
marks2[0] = 100;
System.out.println("marks1[0] = " + marks1[0]);
String s = null; // references can be null
System.out.println("s is " + s);
}
}Output
a = 10, b = 20 marks1[0] = 100 s is null
Memory Picture
Stack (method variables) Heap (objects) +-----------------+ | a = 10 | | b = 20 | | marks1 ------------+--------> [100, 80, 90] | marks2 ------------+ +-----------------+
Tip: Calling a method on a null reference throws NullPointerException, the most common runtime error in Java.