Cosmic Module
J
Qubits of DPK
March 14, 2026
Core Java
Layman Explanation
You're asked to write "I will study" 500 times. Instead of doing it manually, you say "repeat this 500 times." That's a loop.
4 Types of Loops
Every Loop Has 4 Parts
javascript
QUBITS OF DPK
1️⃣ for Loop — Known iterations
java
QUBITS OF DPK
2️⃣ while Loop — Unknown iterations
java
QUBITS OF DPK
3️⃣ do-while Loop — At least once
java
QUBITS OF DPK
4️⃣ for-each Loop — Arrays/Collections
java
QUBITS OF DPK
️ Which Loop to Use When
break and continue
java
QUBITS OF DPK
️ All Traps
java
QUBITS OF DPK
Interview Answer (SDE-2)
"Java has 4 loops. for is for known iteration counts. while checks condition first — body may never execute. do-while executes body first — guaranteed at least once, used for menus and input validation. for-each is cleanest for collection iteration but can't modify elements or access index. break exits the entire loop, continue skips current iteration. Nested loops give O(n²) complexity — the typical brute force indicator."
Interview Questions & MAANG-Level Answers
Q1. What is the difference between while and do-while?
while checks the condition BEFORE executing the body — body may never execute if condition is false initially. do-while executes the body FIRST, then checks condition — body executes at least once regardless. Example: while(false) {} — body never runs. do {} while(false) — body runs once.
Q2. When would you use do-while over while?
When the action must happen at least once before checking whether to continue. Classic examples: menu systems (show menu at least once before asking user to continue), input validation (take input at least once before checking if valid), retry logic (attempt operation once before checking result). Example:
java
QUBITS OF DPK
Q3. Why can't for-each modify array elements?
for-each gives you a copy of each element, not a reference to the actual array slot. When you do for (int x : arr) { x = 0; }, you're modifying the local copy x, not arr[i]. For objects, you CAN modify fields (since you have a reference to the heap object), but you CANNOT reassign the reference. To modify primitive array elements, use a regular indexed for loop: for (int i = 0; i < arr.length; i++) { arr[i] = 0; }.
Q4. What does break do in a nested loop?
break exits ONLY the innermost loop it is placed in. The outer loop continues normally. Example: for(outer) { for(inner) { break; } } — break exits inner loop, outer continues. To break outer loop, use a labeled break: outer: for(...) { for(...) { break outer; } }. In production, prefer restructuring code over labeled breaks for readability.
Q5. What is the output of a for loop with semicolon after it?
java
QUBITS OF DPK
Output: Hello printed exactly once. The semicolon makes the for loop body empty — loop runs 5 times doing nothing. The {} block is just a regular code block unrelated to the for loop, running once. This is one of the sneakiest Java traps in interviews.