In JAVA we can use wrapper class for the switch statement. But java allows only four types of Wrappers that are Byte, Short, Integer, Long. I this article we will read how works Switch case with wrapper classes.
The switch statement executes one block of the statement from multiple blocks of statements based on condition. In the switch statements, we have a number of choices and we can perform a different task for each choice.
As you already knew the execution of Switch statement is totally dependent on Switch expression. Here is an example of Wrapper class Integer:

You can see in the above syntax how to use the Switch case with wrapper classes. You can’t use the object of the Wrapper class in the case. Because the case always accepts a constant value.
public class ExampleOfSwitch { public static void main(String[] args) { //Declaring a wrapper variable for switch expression Integer year = 3; int marks = 80; switch(year) //Switch expression { //Case statements case 1: System.out.println("First year students are not eligible for scholarship "); break; case 2: System.out.println("Second year students are not eligible for scholarship"); break; case 3: System.out.println("Congrats!!!!! you are eligible for the scholarship"); break; //Default case statement default: System.out.println("Please enter valid year"); } } }
Output: Congrats!!!!! you are eligible for the scholarship
Why does float values are not allowed in the switch statement?
As you know the Switch statement makes a comparison of expression with the cases. If any match found, the matched case get executed. But the comparison of float vales doesn’t guarantee always the correct results. This is why float comparison is not recommended even with if-else conditions.
Let’s say we have two floating numbers x and y. Comparing two floating-point numbers can be inaccurate when the decimal equivalents of x and y look the same to a reasonable precision.
Java allows only four types of Wrappers that are Byte, Short, Integer, Long
It is not fully correct. Java also support Character wrapper.
Ex:
public class Main
{
public static void main(String[] args) {
Character b = ‘A’;
switch (b) {
case ‘B’:
System.out.print(“B”);
break;
case ‘A’:
System.out.print(“A”);
break;
}
}
}
Output: A
Good article