Intermediate Java
Jim White
Java Developer
while (condition) {
// Run this code
}
if
statementif
statement, can run multiple times// Prints numbers smaller than 5
int counter = 1;
while (counter < 5){
System.out.println(counter);
counter = counter + 1;
}
1
2
3
4
int counter = 1;
while (counter < 5){
System.out.println(counter);
counter = counter + 0;
}
➡ Causes program to hang
true
int counter = 1;
while (counter < 5){
System.out.println(counter);
counter = counter - 1;
}
int counter = 0;
// Same as counter = counter + 3
counter += 3;
Similar to
-=
,
*=
,
/=
, ...
break
to exit while
loop early, but not best coding practiceint counter = 0;
while (counter < 5){
System.out.println("Counter: " + counter);
if (counter == 3) {
break; // Exit the loop when counter is 3
}
counter+=2;
}
Counter: 1
Counter: 3
// while loop that prints even numbers smaller than 20
int counter = 2;
while (counter < 20){
System.out.println(counter);
counter *= 2;
// Exit while loop if counter is odd
if (counter % 2 == 1){ // counter % 2 is counter modulo 2
System.out.println("Something went wrong, counter is odd.");
break;
}
}
Intermediate Java