testinganswers.com

09.2 Control Flow

09.2 Control Flow

9.2 | Looping Statements

Java supports four looping statements.

  • for…statement
  • for each…statement
  • while…statement
  • do-while…statement
 
for …statement
 
It executes a block of code a specified number of times.
 
   For example – the code below prints numbers from 1 to 9.
 
for ...statement
for…each statement
 
It executes a block of code for each item in a collection or each element in an array.
 
For example – the code below prints all numbers in an array.
for each ...statement
 
 
while…statement
 
It executes a block of code while or until the condition is true.
 
For example – The code below executes the loop until array value <4.
 
while...statement
 
 
do…while statement
 
It executes a block of code until the condition becomes false.
 
do...while statement
 
 
Note: while loop is executed only if the condition is true. So while loop can execute zero or more times. Whereas do…while loop is executed first time without validating the condition, i.e. it will always execute for the first time. At the end of the first loop, the execution condition is checked. So, do…while loop always executes 1 or more times.
 

Leave a Reply

%d bloggers like this: