+91 81900 98289

Java Switch

switch picks one path from a fixed set of values. A classic switch needs break, or execution falls into the next case. A switch expression, available in current JDKs, yields a value and does not fall through.

Use switch when you are matching one code, one command, or one menu number. Use if when the test is a range, such as marks >= 50.

Example

day is 1, so only the Monday case runs. default runs when no case matches.

public class Day { public static void main(String[] args) { int day = 1; switch (day) { case 1 -> System.out.println("Monday"); case 2 -> System.out.println("Tuesday"); default -> System.out.println("Other"); } } }
The arrow form does not fall through. If you use the older colon form, end each case with break unless you truly want the next case to run as well.