The basic structure of a loop is as follows:
while(true) {
//evaluate the code
}
A loop that actually does something might look like this.
int x = 0;
while(x < 5){
System.out.println(x);
x++;
}
Java also as a do…while loop. The main difference between the while loop and the do…while loop is that the do…while loop always runs at least once. For example take a look at the code below
int x = 0;
do {
System.out.println(x);
x++;
} while (x >= 5);
The variable x is never greater than or equal to five, but it still prints the initial value of x, 0. However, although looking at the while loops, each line should make perfect sence, there are two lines of unnecessary code, and while we strive to be “good†programmers, we frown upon that; which is why there is a for loop. The for loop looks like this
for(int x = 0; x < 5, x++){
System.out.println(x);
}


Sign In
Create Account

Back to top









