Version without JavaScript, read-only: workshops, quizzes and running code are not available here. Full version · Catalogue · Sign in
if, the ternary operator, switch, while, do…while and for.
5.1.1 The if condition
- The
if instruction executes the instruction or block that follows it if the boolean condition is true. - The optional
else specifies what to execute if the condition is false.
if (condition1) {
instruction1;
} else if (condition2) {
instruction2;
} else {
instructionSinon;
}
5.1.2 Ternary operator
If an if instruction contains only a value assignment, you may prefer the ternary operator ? :.
if (niveauJoueur > 3) {
bonusXP = 5;
} else {
bonusXP = 10;
}
// is equivalent to
bonusXP = (niveauJoueur > 3) ? 5 : 10;
5.2 Conditional branching (switch)
The switch instruction executes code depending on the value of an expression.
switch (expression) {
case constante1 :
instr11;
instr12;
break;
case constante2 :
break;
default :
// ...
}
Fall-through: here, a is 2
public class Demo {
public static void main(String[] args) {
int a = 0;
int expression = 0;
switch (expression) {
case 0 :
a++;
case 1 :
a++;
break;
default :
a = -1;
}
System.out.println("a is " + a);
}
}
5.4 The while loop
A while loop executes the block that follows it as long as the condition is true. The condition is evaluated at the start of each iteration.
while (condition) {
instruction;
}
If the condition is false before the while, the body of the loop will never be executed.
5.5 The do…while loop
The condition is evaluated at the end of each iteration.
do {
instructions;
} while (condition);
5.6 The for loop
for (initialisation; condition; modification) {
// instructions
}
The body of the loop is executed as long as condition is true, and modification is applied at each iteration.
The three loops, side by side
public class Demo {
public static void main(String[] args) {
System.out.print("for :");
for (int i = 1; i <= 5; i++) {
System.out.print(" " + i);
}
System.out.println();
System.out.print("while :");
int j = 1;
while (j <= 5) {
System.out.print(" " + j);
j++;
}
System.out.println();
System.out.print("do while :");
int k = 10;
do {
System.out.print(" " + k); // runs even if the condition is false
k++;
} while (k <= 5);
System.out.println();
}
}