if (boolean-expr)
// do an action
if (boolean-expr) {
// do an action
// do another action
}
// remember: = is assignment, == is comparison
if (x = 5) { // ERROR: should be x == 5
// do something
}
Execution begins at the first case that matches the variable
And continues until it reaches a break
If no case matches, executes the default case (if present)
// NOTE: can only switch on int or smaller (byte, short, int, char) // as well as String and enums (more on enums later)
switch (variable) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
}
void determineRange(int i) {
switch (i) {
case 1: case 2: case 3:
System.out.println("i is between 1 and 3");
break;
case 4: case 5: case 6:
System.out.println("i is between 4 and 6");
break;
case 7: case 8: case 9:
System.out.println("i is between 7 and 9");
break;
default:
System.out.println("i is out of range");
}
}
// i declared outside for block, because we need it later
int i;
for (i = 0; i < 5; i++) {
System.out.println("i is now " + i);
}
...
System.out.println("i after for loop is " + i); // i still in scope
// i is declared in the scope of the for block (typical case)
for (int i = 0; i < 5; i++) {
System.out.println("i is now " + i);
}
// i is now out of scope (see notes)
class ContinueOn {
public static void main(String args[]) {
int limit = 3;
for (int j = 0; j < 5; j++) {
if (j == limit)
continue; // stop current iteration and continue with next
System.out.println("j is " + j);
}
}
}