Cosmic Module
J
Qubits of DPK
March 15, 2026
Core Java
Enhanced For Loop (for-each)
java
QUBITS OF DPK
Limitations
java
QUBITS OF DPK
Array of Objects
java
QUBITS OF DPK
Memory Model for Array of Objects
javascript
QUBITS OF DPK
️ Traps
java
QUBITS OF DPK
Interview Answer
"Enhanced for loop provides clean syntax for read-only array/collection iteration without managing index. It cannot modify primitive array elements (changes local copy) but CAN modify object fields (since reference points to heap object). Array of objects stores references — each element is null until explicitly initialized with new. Always null-check before accessing elements in an object array."
Interview Questions & MAANG-Level Answers
Q1. Can for-each modify array elements? What about object fields?
For PRIMITIVES: No. for (int x : arr) { x = 0; } modifies only the local copy x — original array unchanged. For OBJECTS: Yes for fields, No for reference reassignment. for (Student s : students) { s.marks = 100; } DOES modify the actual Student objects in heap (s is a reference to heap object). But s = new Student() does NOT change the array — it only reassigns the local variable s to a new object, the array still holds the old reference.
Q2. What is the default value of an array of objects?
null. Student[] arr = new Student[3] creates an array of 3 null references — the Student objects don't exist yet. Accessing arr[0].name throws NullPointerException. You must explicitly create each object: arr[0] = new Student(). This is the most common array-of-objects trap. Always null-check when iterating: if (s != null) { ... }.
Q3. What is the difference between s.marks = 100 and s = new Student() inside for-each?
s.marks = 100 modifies the FIELD of the existing object that s references in heap — the array still holds this reference, so the change is visible through the array. s = new Student() creates a new Student object and points the LOCAL variable s to it — the array slot still holds the original reference, completely unaffected. s is just a local copy of the reference, not the array slot itself.
Q4. When would you prefer regular for loop over for-each?
Use regular for loop when: (1) You need the index: arr[i] for positional operations. (2) You need to modify primitive array elements: arr[i] = newValue. (3) You need to iterate in reverse: for (int i = n-1; i >= 0; i--). (4) You need to skip elements: for (int i = 0; i < n; i += 2). (5) You need to compare adjacent elements: arr[i] vs arr[i+1]. Use for-each for: clean read-only iteration, collections, when index doesn't matter.