When a decision compares one variable against a list of specific fixed values, an else if chain repeats that variable on every line. The switch statement says it once and then lists the cases underneath. It is not more powerful than an if chain — anything a switch does can be written with else if — but for the right shape of problem it is far easier to read and far harder to get wrong.
int month = 4;
int days;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31;
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
case 2:
days = 28;
break;
default:
days = 0; // not a real month
}
System.out.println(days); // prints 30The value in the brackets is the selector, and Java jumps to the case label whose constant matches it. Execution then continues from that point until it meets a break, which exits the whole switch. default catches every value that matched no case, and it plays the same role as the final else in a chain. Case labels must be compile-time constants, not variables or ranges, which is the main limit on where a switch can be used.
| Selector type | Allowed in a switch? | Note |
|---|---|---|
int, short, byte, char | Yes | The everyday cases — menu choices, month numbers, letter grades |
String | Yes | Compares by content, like .equals(), so no == trap here |
| enum | Yes | The neatest fit of all, since the cases are named constants already |
double, float | No | Exact equality on decimals is unreliable, so Java forbids it |
long, boolean | No | A boolean has only two values, which is what if / else is for |
int code = 2;
switch (code) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
default:
System.out.println("Other");
}
// prints: Two, then Three, then Other — every break is missingChoosing between switch and else if
- One variable is compared against several fixed, known values
- The values are whole numbers, characters or Strings
- A menu, a month number, a letter grade or a command word
- You want every option visible in one flat, readable list
- The tests are ranges, such as mark >= 80
- The selector is a double, or the tests involve more than one variable
- Conditions combine with && or ||
- Each branch asks a genuinely different question
Validating input
Every value that comes from outside your program is a guess until you check it. A user types a letter where a number was expected, enters a negative age, or leaves a count at zero and then your program divides by it. Validation means testing an input against what your calculation actually requires, before the calculation runs, and having a plan for the case where it fails.
import java.util.Scanner;
public class Marks {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a mark out of 100: ");
if (!sc.hasNextInt()) { // is the next token even a number?
System.out.println("That is not a whole number.");
} else {
int mark = sc.nextInt();
if (mark < 0 || mark > 100) { // range check
System.out.println("A mark must be from 0 to 100.");
} else {
System.out.println("Accepted: " + mark);
}
}
}
}int total = 0;
int count = 0;
if (count == 0) {
System.out.println("No marks entered, so there is no average.");
} else {
double average = (double) total / count;
System.out.println("Average: " + average);
}
System.out.println(5.0 / 0); // Infinity — no exception, no warning
System.out.println(0.0 / 0.0); // NaN- Validate as early as possible, at the moment the value is read, so bad data never travels.
- Test the type first (
hasNextInt), then the range, then any rule specific to your problem. - Say what is wrong and what would be acceptable: a mark must be from 0 to 100 beats invalid input.
- Guard every divisor, every index and every value that could be zero, negative or missing.
- Check boundaries deliberately: for a 0 to 100 range, test −1, 0, 100 and 101, not just 50.