Loops in Java

If you want to repeat certain set of statements over and over again, you can make use of loops in Java. Let’s start with the while loop:

 
int x = 0;
while (x < 10) {
	System.out.println(x);
	x++;
}

This will print 0 to 9 on screen, each on a new line because we have println. If you use print instead, it’ll be printed on the same line.

In the above code, we basically initiated variable x to zero. And said keep printing x till it’s value is less than 10. Also each time we print x, we increment x by 1.

Let’s do the same thing using a do-while loop now:

int x = 0;
do {
	System.out.println(x);
	x++;
} 
while(x<10);

This again does the same thing but the difference is (as you might have noticed), it will execute the loop at least once even if the condition returns as false.

Let’s do this with a for loop now:

for (int x=0; x<10; x++) {
	System.out.println(x);
}

This prints the same thing. In this code, x is initialized to zero and the condition is checked (x is less than 10). So everything inside the for loop gets executed. After execution x is incremented and again the condition is checked. This goes on till the condition returns false.

There’s another kind of loop called the for-each loop. We’ll look into that after we understand Arrays. So the next post is of course about Arrays!