Java MCQ
Java Tricky Loops Questions
What is the output?
for(int i = 0; i < 5; i++); {
System.out.println("Hello");
}
System.out.println("Hello");
}
The semicolon after the for loop ends the loop statement. The code block that follows is just a regular block that executes once, printing "Hello" only one time.
What will be printed?
int i = 0;
while(i < 3) {
System.out.print(i + " ");
i++;
}
System.out.print(i);
while(i < 3) {
System.out.print(i + " ");
i++;
}
System.out.print(i);
The loop prints 0, 1, 2 (while i < 3). After the loop ends, i becomes 3 and the final print statement prints 3.
What is the output?
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 2; j++) {
if(i == j) break;
System.out.println(i + " " + j);
}
}
for(int j = 0; j < 2; j++) {
if(i == j) break;
System.out.println(i + " " + j);
}
}
2 0
2 1
When i=0, j=0: break (no print). When i=0, j=1: i≠j, print 0 1. When i=1, j=0: i≠j, print 1 0. When i=1, j=1: break. When i=2, j=0: i≠j, print 2 0. When i=2, j=1: i≠j, print 2 1.
What will be printed?
int i = 5;
do {
System.out.print(i + " ");
i--;
} while(i > 0);
System.out.print(i);
do {
System.out.print(i + " ");
i--;
} while(i > 0);
System.out.print(i);
do-while executes at least once. It prints 5,4,3,2,1 (while i>0). When i becomes 0, loop stops and final print shows 0.
What is the output?
for(int i = 0; i < 5; i++) {
if(i == 2) continue;
System.out.print(i + " ");
}
if(i == 2) continue;
System.out.print(i + " ");
}
When i=2, continue skips the print statement and moves to next iteration. So 2 is not printed.
What will be printed?
int i = 0;
while(i++ < 3) {
System.out.print(i + " ");
}
while(i++ < 3) {
System.out.print(i + " ");
}
Post-increment (i++) returns the original value then increments. So: i=0: 0<3 (true), i becomes 1, print 1. i=1: 1<3 (true), i becomes 2, print 2. i=2: 2<3 (true), i becomes 3, print 3. i=3: 3<3 (false), loop ends.
What is the output?
for(int i = 0; i < 3; i++) {
System.out.print(i + " ");
break;
}
System.out.print(i + " ");
break;
}
The break statement exits the loop immediately after the first iteration, so only 0 is printed.
What will be printed?
int i = 0;
while(true) {
if(i == 3) break;
System.out.print(i + " ");
i++;
}
while(true) {
if(i == 3) break;
System.out.print(i + " ");
i++;
}
The loop breaks when i becomes 3, so it prints 0, 1, 2 and stops before printing 3.
What is the output?
for(int i = 0; ; i++) {
if(i > 2) break;
System.out.print(i + " ");
}
if(i > 2) break;
System.out.print(i + " ");
}
Even though the for loop has no condition, the break statement stops the loop when i>2, so it prints 0, 1, 2.
What will be printed?
outer: for(int i = 1; i <= 2; i++) {
inner: for(int j = 1; j <= 2; j++) {
if(i == j) continue outer;
System.out.println(i + " " + j);
}
}
inner: for(int j = 1; j <= 2; j++) {
if(i == j) continue outer;
System.out.println(i + " " + j);
}
}
When i=1, j=1: continue outer skips to next i. When i=1, j=2: i≠j, print 1 2. When i=2, j=1: i≠j, print 2 1. When i=2, j=2: continue outer.