Java Wrapper in Switch Statements
Java provides four wrapper classes to use: Integer, Short, Byte, and Long in switch statements.
Example:
Java Wrapper in switch case.
public class WrapperSwitchExample {
public static void main(String[] args) {
Integer age = 25;
switch (age.intValue()) { // Extract primitive value for switch
case 25:
System.out.println("You are 25.");
break;
case 30:
System.out.println("You are 30.");
break;
default:
System.out.println("Age not matched.");
}
}
}
Output:
You are 25.
Note:
Regardless of its placement, the default case only gets executed if none of the other case conditions are met. So, putting it at the beginning, middle, or end doesn’t change the core logic (unless you’re using a less common technique called fall-through).
Example: In this code we will identify the weekday through (1-7) numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a day number (1-7): ");
int day = scanner.nextInt();
switch (day) {
default:
System.out.println("Not a valid weekday.");
break;
case 1:
System.out.println("It's Monday!");
break;
case 2:
System.out.println("It's Tuesday!");
break;
case 3:
System.out.println("It's Wednesday!");
break;
case 4:
System.out.println("It's Thursday!");
break;
case 5:
System.out.println("It's Friday!");
break;
case 6:
System.out.println("It's Saturday!");
break;
case 7:
System.out.println("It's Sunday!");
break;
}
}
}
Output
Enter a day number (1-7): 8
Not a valid weekday.
Switch Statements in Java
The switch statement in Java is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions.
It is like an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The expression can be a byte, short, char, or int primitive data type. It tests the equality of variables against multiple values.