Loops in Java WHILE FOR DO WHILE Interview MCQ
Table of Contents
Study and learn Interview MCQ Questions and Answers on Loops in Java WHILE FOR DO WHILE and Break & Continue Label Statements. Attend job interviews easily with these Multiple Choice Questions of Java Loops WHILE FOR DO WHILE
Loops in Java Do While with Break & Continue Tutorial
Java language provides a Do While loop with slightly modified features of the WHILE loop.
Normal WHILE loop does not execute loop statements if the condition is not satisfied or true. But a DO WHILE loop executes the loop statements for the first time without even checking the loop condition. Programmers usually prefer a WHILE loop to DO WHILE loop.
A Do While loop condition should evaluate to either true or false values.
Loops in Java Do While with Break and Continue
Syntax of a Do While loop is as follows.
do{ //statements //loop counter }while( condition ); //Semicolon is present
Example:
int a=1; do { System.out.print(a +","); a++; }while(a<=5); //OUTPUT //1,2,3,4,5
Loops in Java Do While with Break Statement
“Break” statement inside a Do While loop causes the program control to exit the loop. The statements below the Do While loop if any will be executed. We use an IF statement to break out of the loop based on a condition.
Example:
int a=1; do { if(a>5) break; System.out.print(a +","); a++; }while(true);
//OUTPUT //1,2,3,4,5,
Java Loops Do While with Continue Statement
“Continue” statement inside a Do While loop causes the program control to skip the statements below it and go to the beginning of the loop. Loop condition is checked again before executing the statements from the beginning. We have used an IF statement to use CONTINUE statement.
Example:
int a=0; do{ a++; if(a%2==0) continue; System.out.print(a +","); }while(a <= 9); // //OUTPUT //1,3,5,7,9,
Nesting of Do While Loops in Java
A Do While loop can be nested inside another Do While loop, For Loop and While loop without any problem.
Example:
int a=5, b=5; do { b=a; do { System.out.print(b+","); b--; }while(b>0); a--; System.out.println(""); }while(a > 0); // //OUTPUT //5,4,3,2,1, //4,3,2,1, //3,2,1, //2,1, //1,
This is how a Java DO WHILE loop works.
Java Loops FOR with Break and Continue Tutorial
Java language provides another good looping control statement called FOR loop. A FOR loop is superior to WHILE loop and DO WHILE loop in terms of flexibility in maintaining loop variables.
Loops in Java FOR Explained
There are two types of FOR loops.
- FOR loop
- FOR EACH or Advanced FOR or Enhanced FOR loop
In this chapter, we shall see usage examples of the Traditional FOR loop.
Syntax:
for(initialization; condition ; iteration) { //STATEMENTS //BODY }
Example:
for(int i=1; i<=5; i++) System.out.print(i + ","); // //OUTPUT //1,2,3,4,5,
There are three parts in a FOR loop.
- Initialization
- Condition
- Iteration (Increment or Decrement)
1. Initialization Part – FOR Loop
You can declare and initialize any type of variables and any number of variables under INITIALIZATION part of a FOR loop. If you declare a variable, you must initialize it with some value. There is no default value assigned.
Rules for declaring and Initializing Variables
- Multiple variables are separated with Commas(,).
- All variables should be of the same data type.
- Any type of variable can be declared and initialized.
- After this initialization part, a Semicolon (;) is mandatory which separates CONDITION part of FOR loop.
Example:
for(int i=1, j=0, k=4; (i<=5)&&(j<=5); i++) System.out.print(i + ","); // //OUTPUT //1,2,3,4,5, //j and k are not used.
2. Condition Part – FOR Loop
The CONDITION can be an expression that evaluates to a boolean constant. Usually, this consists of Relational or Conditional Operators along with Logical Operators to create a complex CONDITION.
3. Iteration Part – FOR Loop
Iteration Part consists of Increment and Decrement Operations on the Loop and other Variables.
FOR Loop with Break Statement
You can use a BREAK statement inside a FOR loop to break out of the loop. Program control exits the loop after encountering a BREAK statement. Usually, an IF Statement or Block surrounds the Break statement. Without the IF condition, the loop becomes Infinite or never-ending.
Example:
for(int i=1; ; i++) { if(i>5) break; System.out.print(i + ","); } //OUTPUT //1,2,3,4,5
FOR loop with Continue Statement
You can use a CONTINUE statement inside a FOR loop to force the program execution control go to the beginning of the loop. Loop condition is checked once again before executing the loop body from the beginning to the end. A CONTINUE statement usually follows an IF statement.
Example:
for(int i=1; i<=10; i++) { if(i%2!=0) continue; System.out.print(i + ","); } //OUTPUT //2,4,6,8,10,
Nested FOR Loops in Java
You can nest a FOR loop inside another FOR loop, WHILE loop and DO WHILE loops. Nested loops are useful to access Multidimensional Arrays.
Example:
for(int i=1; i<=5; i++) { for(int j=i; j>0; j--) { System.out.print(j+" "); } System.out.println(""); } //OUTPUT //1 //2 1 //3 2 1 //4 3 2 1 //5 4 3 2 1
This is how a Java FOR loop works.
Java Loops While with Break and Continue Tutorial
As part of Loop control statements, Java provides three loops namely WHILE loop, FOR loop and DO WHILE loop. Loops repeatedly execute a set of statements as long as the Loop condition is satisfied. A while loop executes the statements under it only if the condition is satisfied.
Java Loops While with Break and Continue Statements
Java continued the same syntax of while loop from the C Language. A while loop accepts a condition as an input. The condition should evaluate to either true or false. A while loop in Java does not work with integers. In Java, a number is not converted to a boolean constant.
Syntax:
while( condition ) { //statements //loop counters }
Example 1: A simple while loop
Note that this while loop will become an Infinite Loop if we do not increment the loop counter variable.
int num=1; while(num <= 5) { System.out.print(num + ", "); num++; //Loop counter //Comment this to make it infinite loop } //1, 2, 3, 4, 5,
While Loop with a break statement
Java provides break statement to make the program control abruptly leave the block or loop inside which a break statement is encountered. Here, we will use the break statement without a label.
int num=1; while(true) { System.out.print(num + ", "); num++; //Loop counter if(num > 5) break; //break the loop } //1, 2, 3, 4, 5,
While loop with a Continue statement
Java provides a continue statement to make the program control abruptly go to the beginning of the loop. So, the loop is not exited in this case. Only that current iteration is skipped. In the below program we try to print only EVEN numbers in a given range. Break or Continue statements are generally used along with an IF condition.
int num=1; while( num <=10 ) { num++; //Loop counter if(num%2 !=0 ) continue; System.out.print(num + ", "); } //2, 4, 6, 8, 10
Nested While Loops in Java
You can nest one while loop inside another while loop. It is fun to use break and continue with nested while loop. In the below program, you will how to break inner and outer loops with break and continue statements. You can also nest different loops like for loop and do-while inside a while loop.
class NestedWhile { public static void main(String args[]) { int i=1, j=1; while(i <= 5) { j=1; while(true) { System.out.print(j + " "); if(i==j) break; j++; } System.out.println(""); i++; } } } //OUTPUT //1 //1 2 //1 2 3 //1 2 3 4 //1 2 3 4 5
This is how a Java While Loop works
Java Break with Label Statement Tutorial
A BREAK statement in Java causes the program control to exit the block or loop immediately.
Label in Java
A Java Label is any valid Identifier or name with a COLON after it.
Rules to define a Label
- A Label name must start with either Alphabet, Underscore(_) or a Dollar ($) symbol. It may contain numbers.
- A Label must be followed by a Loop or a Block.
- Defining a Label like a Goto statement produces a compiler error
There are two types of Break statements.
- Break without label
- Break with label
1. Java Break without Label Statement
Using a Break statement without specifying any Label causes the loop to close and exit immediately. It works only with Loops.
You can use the Break statement without a Label with any loop like FOR, Enhanced FOR, WHILE and DO WHILE loop. You can not break more than one loop using just a BREAK without Label.
2. Java Break with Label Statement or GOTO Statement
C language supported goto statements for the convenience of developers or programmers. Java supports GOTO statement in the form of BREAK with Label or CONTINUE with LABEL statements. That means you can not use the keyword “goto” as of now. It is just a reserved word.
Break with a Label works with both Code BLOCKS and Loops.
Break with a Label Block
You can define a Block in Java program using an Opening Brace ( { )and a Closed Brace ( } ). Just add a name to that block with a COLON symbol. SWITCH block is the best example of using a BREAK with a BLOCK statement. After the BREAK statement is encountered, program control goes out of that named block or labelled block.
Example:
class LabelBlock { public static void main(String[] args) { int a=10; MYLABEL: { System.out.println("Entered Label"); if(a>5) break MYLABEL; System.out.println("NOT REACHABLE"); } System.out.println("AFTER LABEL BLOCK"); } } //OUTPUT //Entered Label //AFTER LABEL BLOCK
Break with a Label using Loops
You can define a LABEL with a Loop BLOCK like WHILE loop block, FOR loop block, Do WHILE loop block or an Enhanced FOR loop Block. You can escape any number of loops with a Break inside a Labelled Block. Nesting is not just 2 levels in the real programming world.
Rules to use Break with a Labelled Loop
- Break statement should be part of the labelled loop.
- You can not break out of a labelled loop which does not enclose the break statement.
Example: Break a Nested Loop or Inner Loop
class BreakNesetedLoop { public static void main(String[] args) { outer: for(int i=0; i<5; i++) { for(int j=0; j<5; j++) { System.out.print(j + ","); if(j==3) break outer; } } System.out.println("\nOUTSIDE of LABEL"); } } //OUTPUT //0,1,2,3, //OUTSIDE of LABEL
This is how a BREAK with LABEL works in Java.
Java Continue with Label Statement Tutorial
A CONTINUE statement inside a loop or iteration in Java causes the program control to go to the beginning of the loop. Next iteration of the loop continues as usual. A CONTINUE statement can be used only with Loops. If you use, you get the error “continue cannot be used outside of a loop“.
There are two types of CONTINUE statements.
- CONTINUE without LABEL
- CONTINUE with LABEL
Java Continue Statement without LABEL
A CONTINUE statement without a LABEL statement can Skip remaining statements of the loop for the current iteration. It can affect only the Inner Loop or a Single Loop or the Loop where the CONTINUE statement is present.
You can use CONTINUE without label statement with the loops, FOR, WHILE, DO WHILE and FOR-EACH. You can nest any number of loops and use CONTINUE statement with a Label at any Level. The number of loops may be more than two for example.
Java Continue with LABEL Statement and Rules to Use
Usually, a CONTINUE statement is used inside an IF statement which is surrounded by a Loop with a Label.
Rules:
1. A Label name or an identifier can start with an Alphabet, Underscore ( _ ) or a Dollar ($) sign. It may contain numbers.
2. A Label should be declared before the loop which contains the CONTINUE statement.
3. You can not use CONTINUE on a Label that is outside the Loop Block. It means that LABEL loop block is different.
4. You can exit an Inner loop with CONTINUE on Label for Outer loop. Without using a Break statement, you are exiting a loop.
5. You can restart an Inner loop without affecting Loop Counter value.
Example: Continue Outer Loop with Label
class ContinueOuterLabel { public static void main(String args[]){ outer: for(int i=1; i<=5; i++) { inner: for(int j=i; j>0 ;j--) { if(i>3) continue outer; System.out.print(j +","); } System.out.println(""); } System.out.println("OUTSIDE LABEL"); } } //OUTPUT //1, //2,1, //3,2,1, //OUTSIDE LABEL
This is how a Java Loops CONTINUE statement works with or without a LABEL.
[WpProQuiz 154]
Loops in Java Interview MCQ
1) What is a Loop in Java programming language?
A) A Loop is a block of code that is executed repeatedly as long as a condition is satisfied.
B) A Loop is a block of code that is executed only once if the condition is satisfied.
C) A Loop is a block of code that is executed more than 2 times if the condition is satisfied.
D) None
Answer [=] A
Explanation:
A Java loop is similar to a C style loop.
2) Choose a valid loop name in Java below.
A) for
B) while
C) do while
D) All
Answer [=] D
3) Every loop in Java has a condition that should be ___ in order to proceed for execution. (TRUE / FALSE)
A) FALSE
B) TRUE
Answer [=] B
4) Choose the correct syntax of the WHILE loop in Java below.
A)
while(condition) { //statements }
B)
while(condition); { //statements }
C)
while { //statements }(condition)
D) None
Answer [=] A
Explanation:
Answer B has a WHILE loop immediately terminated by a Semicolon. So it is a wrong representation.
5) Choose the correct Syntax of FOR loop in Java below.
A)
for(initialization; condition; increment-or-decrement) { //statements }
B)
for(condition; increment-or-decrement; initialization) { //statements }
C)
for(increment-or-decrement; condition; initialization) { //statements }
D) None
Answer [=] A
Explanation:
Notice that there is no semicolon at the end of the INCREMENT/DECREMENT part.
6) Choose the correct syntax of the DO WHILE loop in Java below.
A)
do { //statements }while(condition);
B)
do { //statements }while(condition)
C)
do while(condition) { //statements }
D) None
Answer [=] A
Explanation:
There must be a Semicolon at the end of the while(condition) part when writing a DO-WHILE loop.
7) Choose the correct syntax of an Enhanced FOR loop in Java below.
A)
for(Type variable: Collection) { //statements }
B)
for(Type variable; Collection) { //statements }
C)
for(Collection: Type variable) { //statements }
D) None
Answer [=] A
Explanation:
There should be a COLON before the collection variable name in the Enhanced FOR loop.
8) State TRUE or FALSE. A WHILE loop in Java executes the statements at least once even the condition is not satisfied.
A) FALSE
B) TRUE
Answer [=] A
Explanation:
Only the DO WHILE loop executes the statements at least once.
9) A BREAK statement inside a Loop like WHILE, FOR, DO WHILE and Enhanced-FOR causes the program execution ___ Loop.
A) Exit
B) Continuation with next iteration
C) Never exit
D) None
Answer [=] A
10) A CONTINUE statement inside a Loop like WHILE, FOR, DO-WHILE and Enhanced-FOR causes the program execution ___ the loop.
A) Skip
B) Skip present iteration and continue with next iteration of the loop
C) Exit
D) None
Answer [=] B
11) Choose the Java-Code below with a never-ending loop.
A)
while(true);
B)
for(;true;);
C)
do { ; }while(true);
D) All
Answer [=] D
12) A loop in Java generally contains a Loop-Counter variable. State TRUE or FALSE.
A) FALSE
B) TRUE
Answer [=] B
13) An Increment operator “++” and/or a Decrement operator “–” are used along with a Loop-Counter variable in Java. (TRUE / FALSE).
A) FALSE
B) TRUE
Answer [=] B
14) What is the output of the below Java program?
int a=1; while(a<4) { System.out.print(a + " "); a++; }
A) 1 2 3 4
B) 1 2 3
C) 6
D) Compiler error
Answer [=] B
Explanation:
a++; yields to a=a+1;
15) What is the output of the below Java program with a decrement operator and WHILE-loop?
int a=4; while(a>0) { System.out.print(a + " "); a--; }
A) 4 3 2 1
B) 3 2 1
C) Compiler error
D) None
Answer [=] A
16) What is the output of the below Java program?
String str="FOX"; int i=0; while(i<str.length()) { System.out.print(str.charAt(i)); i++; }
A) FFF
B) FOX
C) Compiler error
D) None
Answer [=] B
17) What is the output of the below Java program with WHILE, BREAK and CONTINUE?
int cnt=0; while(true) { if(cnt > 4) break; if(cnt==0) { cnt++; continue; } System.out.print(cnt + ","); cnt++; }
A) 0,1,2,3,4,
B) 1,2,3,4,
C) 1,2,3,4
D) Compiler error
Answer [=] B
Explanation:
CONTINUE takes the program execution to the beginning of the loop by skipping the present iteration.
18) What is the main difference between a WHILE and a DO-WHILE loop in Java?
A) WHILE loop executes the statements inside of it at least once even if the condition is false.
B) DO-WHILE loop executes the statements inside of it at least once even if the condition is false.
C) WHILE loop is fast.
D) DO-WHILE loop is fast.
Answer [=] B
Explanation:
Both the WHILE loop and DO-WHILE loop work at the same speed. A DO-WHILE loop executes the statements inside of it even the condition is false. It is the reason why a DO-WHILE loop is used in MENU driven console java programs.
19) What is the value of “age” in the below Java program with a DO-WHILE loop?
int age=20; do { age++; }while(age<20); System.out.println(age);
A) 20
B) 21
C) Compiler error
D) None
Answer [=] B
Explanation:
WHILE condition fails. By that time, the increment statement was executed for one time. So its new value is 21.
20) What is the output of the below java program that implements nesting of loops?
int i=1, j=1; while(i<3) { do { System.out.print(j + ","); j++; }while(j<4); i++; }
A) 1,2,3,4,1,2,3,4,
B) 1,2,3,4,
C) 1,2,3,1,2,3,
D) 1,2,3,
Answer [=] B
Explanation:
Do-WHILE works for the first time printing (1,2,3). In the next iteration of i=2, the value of j is already 4. So it is printed and checked for condition (j<4). The inner loop exits. In the third iteration with i=3, nothing is printed.
21) What is the output of the below Java program?
int time=50; do { System.out.print(time + ","); time++; }while(time < 53)
A) 50,50,50,
B) 50,51,52,
C) 51,52,53,
D) Compiler error
Answer [=] D
Explanation:
The semicolon after the WHILE (Condition) is missing.
22) What is the output of the below Java program?
char ch[] = {'A', 'B', 'C'}; int i=0; do { System.out.print(ch[i] + ","); i++; }while(i < ch.length);
A) A,B,C,
B) A,B,C
C) A,A,A
D) Compiler error
Answer [=] A
23) What is the output of the below Java program?
String str[] = {"A","B","C"}; int i=0; do { if(i>= str.length) break; System.out.print(str[i] + ","); i++; }while(true);
A) A,B,C,
B) A,B,C
C) Runtime Exception with Index Of Bounds Exception
D) Compiler error
Answer [=] A
24) What is the output of the below Java code with a FOR loop?
for(int i=1; i<5; i++) { System.out.print(i +","); }
A) 1,2,3,4,
B) 1,2,3,4
C) 1,2,3,4,5,
D) 1,2,3,4,5
Answer [=] A
25) What is the output of the below Java code?
boolean[] ary = {true, false, true, true}; for(int i=0; i<ary.length; i++) { System.out.print(ary[i] +","); }
A) true,true,true,true,
B) true,false,false,true
C) true,false,true,true
D) Compiler error
Answer [=] C
26) What is the output of the below Java code?
int score=1; for(; true; score++) { System.out.print(score +","); if(score > 3) break; }
A) 1,2,3,
B) 1,2,3
C) 1,2,3,4,
D) 1,2,3,4
Answer [=] C
Explanation:
BREAK condition is checked after printing the variable “score”. So, it prints 4 also.
27) What is the output of the below Java program with FOR loop?
for(int j=0; j<5;j++;) System.out.print(j + ",");
A) 1,2,3,4,
B) 0,1,2,3,4
C) Compiler error
D) None
Answer [=] C
Explanation:
The semicolon after the INCREMENT/DECREMENT part is not allowed.
28) State TRUE or FALSE. In a FOR loop, the Initialization-part, Condition-part and Increment/Decrement part can be empty.
A) FALSE
B) TRUE
Answer [=] B
Explanation:
for(;;) is valid.
29) Any loop can be nested inside any loop in Java. (TRUE/FALSE).
A) FALSE
B) TRUE
Answer [=] B
30) A Loop in Java language may contain ___.
A) Any loop
B) IF-ELSE statements
C) SWITCH statements
D) All
Answer [=] D
31) In Java language, BREAK or CONTINUE statements can be implemented inside a Loop only with the help of ___ statements to avoid never-ending loops.
A) IF ELSE
B) SWITCH
C) ENUM
D) None
Answer [=] A
32) The Enhanced FOR loop in Java was introduced by ___.
A) JDK 4
B) JDK 5
C) JDK 6
D) JDK 7
Answer [=] B
33) An enhanced FOR loop work with only Collection type data. Examples of Collection are ___.
A) Array Class type or any regular array variable
B) ArrayList
C) HashMap, HashSet
D) All
Answer [=] D
34) What is the output of Java Enhanced FOR loop below?
String names[] = {"MOGLI", "SHAREKHAN", "BALU"}; for(String str: names) { System.out.print(str + ","); }
A) MOGLI,
B) MOGLI,SHAREKHAN,
C) MOGLI,SHAREKHAN,BALU,
D) Compiler error
Answer [=] C
35) An Enhanced FOR loop in Java misses ___ and __ compared to the old-style FOR loop.
A) Speed and Easiness
B) Initialization, Increment/Decrement
C) Semicolons, Variables
D) None
Answer [=] B
Explanation:
The condition part is not required as the Enhanced FOR loop iterates through all elements of the Collection from staring to end.
36) What is the output of the Java program with Enhanced FOR loop below?
String countries[] = {"BRAZIL", "CHILE", "SYDNEY"}; int i=0; for(String str: countries) { if(i<2) ; else break; System.out.print(str + ","); i++; }
A) BRAZIL,CHILE,SYDNEY,
B) BRAZIL,CHILE,
C) BRAZIL,
D) Compiler error
Answer [=] B
37) What is the output of the Java code snippet?
int i=0; for(i=1; i<=6;i++) { if(i%3==0) continue; System.out.print(i+","); }
A) 1,2,
B) 1,2,4,5,
C) 3,6,
D) Compiler error
Answer [=] B
Explanation:
CONTINUE statement skips the execution of the remaining statements below it.
38) A BREAK or CONTINUE statement applies only to the ___ loop.
A) Inner loop or the loop containing break or continue
B) always Outer loop
C) Sometimes inner loop, sometimes outer loop
D) None
Answer [=] A
39) A BREAK-WITH-LABEL or CONTINUE-WITH-LABEL are used in particular in Java to select __ loop either to Break or Continue.
A) Inner loop
B) Outer loop
Answer [=] B
Explanation:
Use the Labels only to choose outer loops. Otherwise, simply use BREAK or CONTINUE without any label.
40) Choose rules for naming a Label in Java below.
A) The name of a label or identifier may start only with Alphabet, Underscore ( _ ) or Dollar ($) symbol
B) A label is kept before the loop in general
C) Duplicate label names are not allowed
D) All
Answer [=] D
41) State TRUE or FALSE. You can exit an inner loop without using a BREAK statement but with a CONTINUE and Label on the outer loop.
A) FALSE
B) TRUE
Answer [=] B
42) The keyword “goto” can be used in Java programs with labels. (TRUE/FALSE)
A) FALSE
B) TRUE
Answer [=] A
Explanation:
The keyword “goto” is still a reserved keyword. It can not be used.
43) Is it possible to break all loops with a single BREAK with a Label statement? (YES/NO)
A) YES
B) NO
Answer [=] A
44) What is the output of the Java code snippet below?
outer: for(int i=1; i<=4;i++) { inner: for(int j=1; j<=4;j++) { if(j==1) break outer; } System.out.print("A"); }
A) A
B) AAAA
C) No Output
D) Compiler error
Answer [=] C
Explanation:
Even before reaching the PRINT statement, the outer loop will stop because of BREAK outer.
45) What is the output of the below Java program?
outer: for(int i=1; i<=2;i++) { inner: for(int j=1; j<=2;j++) { if(j>i) break inner; System.out.print(j +","); } }
A) 1,1,1
B) 1,2,2,
C) 1,1,2,
D) Compiler error
Answer [=] C