New Operator
1. What new Does (beginner)
new creates an object/array on the Heap and returns its address. Without new, reference variables point to null (nothing). Think: new = "build me a house, give me its address".
2. Code — Without vs With new
String s; // declares address box, holds null (no object yet!)
// s.length(); // NullPointerException! (no house built)
s = new String("hi"); // NOW built on Heap, s holds address
System.out.println(s.length()); // 2 — works!
int[] arr = new int[3]; // array of 3 zeros on Heap: [0,0,0]
arr[0] = 10;
Student st = new Student(); // calls constructor (see Module 2)
Steps of new Student(): allocate Heap memory → run constructor → return address into st.
3. Primitives Don't Need new
int x = 5; lives on Stack directly. Objects/arrays need new (Heap). String is special: "hi" auto-creates (no new needed, but new String("hi") also works).
4. Traps
NullPointerException= forgotnew(most common beginner crash!).new int[3]elements auto-zero;new String[3]elements auto-null.- Memory freed by GC (no
deletelike C++).
5. Exam Points
- What
newdoes (Heap + constructor + address) — 5 marks, very frequent. - NullPointerException cause + fix — 3 marks, frequent.