Non-Primitive Data Types
Common Non-Primitive Types
String — a sequence of characters (technically a class, not a primitive)
Arrays — e.g. int[], String[]
Classes — any type you define with the class keyword
Interfaces — contracts implemented by classes
References, Not Values
A primitive variable stores its value directly. A reference-type variable does not store the object itself — it stores a reference (an address) that points to where the actual object lives on the heap. This is the single most important behavioral difference between the two categories.
A reference points to an object
public class Student {
String name;
Student(String name) {
this.name = name;
}
}Assignment Copies the Reference, Not the Object
This is where reference types diverge sharply from primitives. When you assign one reference variable to another, Java copies the reference (the address) — not the object it points to. After the assignment, both variables point at the exact same object in memory.
Two variables, one object
public class ReferenceDemo {
public static void main(String[] args) {
Student s1 = new Student("Aman");
Student s2 = s1; // s2 now points to the SAME object as s1
s2.name = "Neha"; // modifies the shared object
System.out.println(s1.name); // also "Neha"!
System.out.println(s2.name);
}
}Neha Neha
Aspect | Primitive Types | Reference Types |
What the variable holds | The actual value | A reference (address) to an object |
Assignment | Copies the value (independent copies) | Copies the reference (shared object) |
Can be null? | No | Yes |
Default value | 0 / 0.0 / false / '\u0000' | null |
Default Value: null
Uninitialized reference field
public class Library {
String bookTitle; // reference field, defaults to null
public static void main(String[] args) {
Library lib = new Library();
System.out.println(lib.bookTitle); // prints "null"
}
}null
The Classic Consequence: NullPointerException
Triggering a NullPointerException
public class NpeDemo {
public static void main(String[] args) {
String message = null;
// Calling a method on a null reference blows up at runtime
System.out.println(message.length());
}
}Arrays Are Reference Types Too
Arrays share references just like objects
public class ArrayReferenceDemo {
public static void main(String[] args) {
int[] scores1 = {90, 85, 70};
int[] scores2 = scores1; // same array object
scores2[0] = 100;
System.out.println(scores1[0]); // 100, not 90!
}
}100