Java Loops (for, while, do-while) Quiz

Java
0 Passed
0% acceptance

35 deep, practical, and often misunderstood questions about Java loops — from subtle break/continue label behavior and enhanced for-loop limitations to infinite loop detection, do-while quirks, loop unrolling myths, and the performance & safety best practices used in real production systems.

35 Questions
~70 minutes
1

Question 1

What is the only fundamental difference between while and do-while that can never be replicated with the other?

A
do-while always executes the body at least once — even if condition is false initially
B
do-while is faster
C
while allows break in condition
D
Only while supports continue
2

Question 2

Why does this nested loop exit completely with a single statement?

java
outer: for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        if (j == 3) break outer;
        System.out.print(j + " ");
    }
    System.out.println();
}
A
Labeled break jumps out of the named loop — skips both levels
B
Only breaks inner loop
C
Compilation error
D
Continues outer loop
3

Question 3

What actually happens when continue is used with a label in nested loops?

java
outer: for (int i = 0; i < 3; i++) {
    inner: for (int j = 0; j < 3; j++) {
        if (j == 1) continue outer;
        System.out.print("(" + i + "," + j + ") ");
    }
}
A
Skips to the next iteration of the outer loop — skips remaining inner iterations
B
Only skips current inner iteration
C
Compilation error
D
Continues to next j value
4

Question 4

Why does this enhanced for-loop fail at runtime?

java
List<String> list = Arrays.asList("a", "b", "c");
for (String s : list) {
    list.remove(0);
}
A
Enhanced for-loop uses Iterator — structural modification throws ConcurrentModificationException
B
Cannot modify loop variable
C
List is immutable
D
Compilation error
5

Question 5

What is the safest way to remove elements while iterating over a collection?

A
Use the Iterator.remove() method directly
B
Use enhanced for-loop with list.remove()
C
Use traditional for loop with index
D
Use stream filter
6

Question 6

Why is this infinite loop pattern preferred in high-performance servers?

java
while (true) {
    Task task = queue.take(); // blocking
    task.execute();
}
A
No condition check overhead — JVM can optimize better
B
Uses less memory
C
Only way to block
D
Faster than for(;;)
7

Question 7

What is actually generated by the compiler for this enhanced for-loop?

java
for (String s : strings) {
    System.out.println(s);
}
A
Equivalent to using strings.iterator() and calling hasNext()/next()
B
Traditional index-based for loop
C
Direct array access
D
Stream pipeline
8

Question 8

Why does this loop never terminate even though i is incremented?

java
for (int i = 0; i < 10; i += 1) {
    if (i == 5) i = 0;
}
A
Resetting loop variable has no effect — update expression runs every iteration
B
Loop variable is final
C
Compilation error
D
Terminates at i = 10
9

Question 9

What is the only loop construct that can be safely used with try-with-resources in a way that guarantees resource closure even on continue?

A
Traditional for loop with resource declared outside
B
No difference — all are safe
C
Enhanced for-loop
D
while loop
10

Question 10

Why is this loop pattern considered extremely dangerous in production?

java
while (true) {
    processNextMessage();
    Thread.sleep(100);
}
A
Busy-waiting with sleep creates high CPU and delayed response
B
Sleep can throw exception
C
Infinite loop forbidden
D
Should use for(;;)
11

Question 11

What is the output of this tricky labeled continue?

java
outer: for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i == 2) continue outer;
        System.out.print(i + "" + j + " ");
    }
}
A
11 12 13 31 32 33
B
11 12 13 21 22 23 31 32 33
C
11 12 13 22 23 31 32 33
D
All combinations
12

Question 12

Why does this enhanced for-loop work perfectly on primitive arrays?

java
int[] numbers = {1, 2, 3};
for (int n : numbers) {
    System.out.println(n);
}
A
Arrays implement Iterable<int> internally via synthetic adapter
B
No autoboxing occurs — direct access
C
Only works on object arrays
D
Compilation error
13

Question 13

What is the most common mistake when using break in nested loops?

A
Forgetting to use a labeled break and only exiting the inner loop
B
Using return instead
C
Break not allowed in for loops
D
Break requires condition
14

Question 14

Why is for(;;) considered idiomatic for infinite loops in Java?

A
Clearly expresses intent — no accidental condition that could terminate
B
Faster than while(true)
C
Only valid syntax
D
Less memory
15

Question 15

Why does this loop cause a performance myth to be busted?

java
for (int i = 0; i < list.size(); i++) {
    // body
}
A
list.size() is O(1) for ArrayList — no performance penalty vs cached length
B
Should cache size in variable
C
Use enhanced for-loop
D
Use iterator
16

Question 16

What is the output when break is used in this do-while?

java
int i = 0;
do {
    if (i == 2) break;
    System.out.print(i + " ");
    i++;
} while (i < 5);
A
0 1
B
0 1 2 3 4
C
0 1 2
D
Nothing
17

Question 17

Why is the loop variable in enhanced for-loop effectively final?

A
Reassigning it would not affect the iteration — compiler prevents confusion
B
Declared final automatically
C
Only in Java 8+
D
Can be reassigned
18

Question 18

What is the most overlooked feature of labeled loops?

A
They enable precise control flow in complex nested algorithms
B
Only for documentation
C
Deprecated
D
Only work with break
19

Question 19

Why is this loop considered the cleanest way to process input until EOF?

java
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    process(line);
}
A
Condition and read are combined — no duplicate code or sentinel values
B
Fastest possible
C
Only way
D
Uses do-while
20

Question 20

After mastering Java loops, what is the single most important principle you now follow?

A
Prefer enhanced for-loop when possible, never modify during iteration, use labels only when necessary, and favor clear intent over micro-optimizations
B
Always cache array length
C
Never use do-while
D
All loops are the same
21

Question 21

Why does this loop print nothing despite the condition being true initially?

java
int x = 5;
while (x < 5) {
    System.out.println(x);
    x++;
}
A
while checks condition before first execution — body never runs
B
Should use do-while
C
Infinite loop
D
Compilation error
22

Question 22

What is the output of this continue behavior?

java
for (int i = 0; i < 5; i++) {
    if (i % 2 == 0) continue;
    System.out.print(i + " ");
    if (i == 3) break;
}
A
1 3
B
1 2 3
C
0 1 2 3 4
D
1 3 4
23

Question 23

Why is the enhanced for-loop not suitable for this use case?

java
for (String s : list) {
    if (shouldRemove(s)) list.remove(s);
}
A
Throws ConcurrentModificationException — cannot modify during iteration
B
Cannot access index
C
Slower than indexed loop
D
Compilation error
24

Question 24

What is the actual performance difference between these two loops in modern JVMs?

java
// Loop A
for (int i = 0; i < arr.length; i++) { sum += arr[i]; }
// Loop B
int len = arr.length;
for (int i = 0; i < len; i++) { sum += arr[i]; }
A
No measurable difference — JVM optimizes both identically
B
Loop B is significantly faster
C
Loop A causes bounds check elimination
D
Loop B uses more memory
25

Question 25

Why does this loop run exactly once?

java
int count = 0;
do {
    System.out.println("Running");
    count++;
} while (count < 0);
A
do-while executes body first — condition checked after
B
Infinite loop
C
Compilation error
D
Never runs
26

Question 26

What is the most elegant way to iterate with index when you need both element and position?

A
Use IntStream.range(0, list.size()).forEach(i -> ...)
B
Traditional for loop
C
Enhanced for-loop with counter variable
D
list.iterator() with hasNext
27

Question 27

Why is this infinite loop safe and commonly used?

java
for (;;) {
    String input = scanner.nextLine();
    if ("quit".equals(input)) break;
    process(input);
}
A
Clear intent, no condition overhead, easy to exit with break
B
Faster than while(true)
C
Only way to read from scanner
D
Prevents StackOverflow
28

Question 28

What is the output when continue skips the increment?

java
int i = 0;
while (i < 5) {
    if (i == 3) {
        continue;
    }
    System.out.print(i + " ");
    i++;
}
A
Infinite loop — i never reaches 4 or 5
B
0 1 2 3 4
C
0 1 2 4
D
0 1 2 3
29

Question 29

Why is the enhanced for-loop the preferred choice in 99% of cases?

A
Cleaner syntax, fewer bugs, works on any Iterable, and no off-by-one errors
B
Always fastest
C
Less memory
D
Only way to iterate
30

Question 30

What is the only valid use case for modifying the loop variable in a traditional for loop?

A
There is no valid use case — it’s always confusing and bug-prone
B
To skip multiple elements
C
To restart loop
D
To optimize bounds
31

Question 31

Why does this loop execute exactly 10 times despite the condition?

java
int i = 0;
while (i++ < 10) {
    System.out.print(i + " ");
}
A
Post-increment: condition uses old value — i becomes 10 on last check
B
Should be i++ > 10
C
Infinite loop
D
Prints 0 to 9
32

Question 32

What is the modern replacement for manual iteration in most cases?

A
Streams and functional operations (filter, map, collect)
B
Enhanced for-loop
C
while loop
D
Recursion
33

Question 33

Why is for(;;) preferred over while(true) in performance-critical code?

A
JVM can apply stronger optimizations knowing the condition is always true
B
Less bytecode
C
No difference
D
for(;;) is slower
34

Question 34

When should you actually use do-while in real code?

A
When you must execute the body at least once (e.g., game loop, menu display)
B
Never — always use while
C
Only for infinite loops
D
When performance matters
35

Question 35

You now fully understand that great Java loop code means:

A
Prefer enhanced for-loop, never modify during iteration, use labeled control only when necessary, and write for clarity over micro-optimization
B
Always cache length
C
Never use do-while
D
All loops are interchangeable

QUIZZES IN Java