Home >>Java Tutorial >Java Loops

Loops in Java

Loops in Java

Loops in java are basically used to execute a set of instructions or functions for multiple times or we can say repeatedly, whenever some of the conditions become true and these loops whether they are in any other programming languages they usually have the exact same business. There are basically three types of loops in the java language that are depicted below:

  • for loop: for loop in java is basically used when there is a need to iterate a part of the program several times. The use of for loop in java is recommended when the number of iteration is generally certain.
  • while loop: while loop in java is basically used when there is a need to iterate a part of the program several times. The use of while loop in java is recommended when the number of iteration is generally not certain.
  • do-while loop: do-while loop in java is basically used when there is a need to iterate a part of the program several times. The use of while loop in java is recommended when the number of iteration is generally not certain and the loop is needed to be executed at least once.

Java For Loop vs While Loop vs Do While Loop

Here is the difference between all the loops in java along with a description and all the major differences:

for loop while loop do while loop
The for loop in Java is basically a control flow statement that iterates a part of the programs for a multiple number of times. The while loop in Java is basically a control flow statement that generally executes a part of the programs multiple times based on the condition of the given boolean. The do while loop in Java is basically a control flow statement that generally executes a part of the programs at least one time and the further execution depend upon the condition of the given boolean.
The use of for loop in java is recommended when the number of iteration is generally certain. The use of while loop in java is recommended when the number of iteration is generally not certain. The use of do while loop in java is recommended when the number of iteration is generally not certain and the loop is needed to be executed at least once.
for(init;condition;incr/decr){ // code that is to be executed } while(condition){ //code that is to be executed } do{ //code that is to be executed }while(condition);
//for loop for(int i=1;i<=10;i++){ System.out.println(i); } //while loop int i=1; while(i<=10){ System.out.println(i); i++; } //do-while loop int i=1; do{ System.out.println(i); i++; }while(i<=10);
for(;;){ //code that is to be executed } while(true){ //code that is to be executed } do{ //code that is to be executed }while(true);