Provide Best Programming Tutorials

Java Loop Control

Java Loop Control

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

Why need loop

Suppose you have to display “Hello World!” 100 times. Of course, the straightforward solution is that you type System.out.println("Hello World!") 100 times but obviously this is not the elegant solution and kind of tedious and error-prone.Java provides a powerful construct called loop to help solve this kind of issue. Using a loop statement, you simply tell the computer to display a string a hundred times without having to code the print statement a hundred times, as follows:

 int count=100;
 for(int i=0;i<100;i++){
     System.out.println("Hello World!")
 }

line 1 defines a variable called count and initiate it to 100.

line 2 defines a variable called i and initiate it to 0 and continues to display “Hello World” on the console until i is equal or greater than 100 the loop ended.

See, with just a couple lines of code you solve this problem.

Three types of loop

Java provides three types of loop statements:

  • for loop
  • while loop
  • do…while loop

Leave a Reply

Close Menu