Title here
Summary here
Switch statements express conditionals across many branches.
Here’s a basic switch
.
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
int i = 2;
System.out.print("Write " + i + " as ");
switch (i) {
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
}
// You can use commas to separate multiple expressions in the same case statement.
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
switch (day) {
case Calendar.SATURDAY:
case Calendar.SUNDAY:
System.out.println("It's the weekend");
break;
default:
System.out.println("It's a weekday");
break;
}
// switch without an expression is an alternate way to express if/else logic.
int hour = calendar.get(Calendar.HOUR_OF_DAY);
switch (true) {
case (hour < 12):
System.out.println("It's before noon");
break;
default:
System.out.println("It's after noon");
break;
}
// A type switch compares types instead of values.
whatAmI(true);
whatAmI(1);
whatAmI("hey");
}
// In Java, we achieve a type switch using instanceof
static void whatAmI(Object obj) {
if (obj instanceof Boolean) {
System.out.println("I'm a bool");
} else if (obj instanceof Integer) {
System.out.println("I'm an int");
} else {
System.out.printf("Don't know type %s\n", obj.getClass().getSimpleName());
}
}
}
To run the program, compile the code in a file named Main.java
and use the java
command to execute it.
$ javac Main.java
$ java Main
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type String