Is it possible to make comparisons with variable values in the switch case
statement or the case
just check the value of a variable and do an action? Is it better to make this type of comparison with if
?
Is it possible to make comparisons with variable values in the switch case
statement or the case
just check the value of a variable and do an action? Is it better to make this type of comparison with if
?
No. In Java, switch
only works with constant values in case
s. Other dynamic languages like Javascript can use variables in case
s, but Java does not.
One of the reasons is how switch
is compiled - it becomes a fixed table in the bytecode containing a mapping (from-to) of integer values to instructions addresses within methods. Since this table is fixed and constant in bytecodes, there is no way to depend on variable values that are only available at runtime.
For switch
with enum
s, the compiler transforms it into a switch
into ordinal()
of enum
. In the case of switch
with String
s, the compiler transforms it into a switch
with hashCode()
s of String
s (and uses a sequence of if
s when hashes collide). However, switch
will always be done through a fixed table determined at compilation time by mapping a number to a method instruction address.
Therefore, the most obvious alternative would be to use if
. However, other alternatives are possible. For example:
Transform the call to switch
into a call to a polymorphic method of some object and transform each case
into an implementation of this polymorphic method.
If the goal of switch
is within every case
set a different value of the same variable, you can put all those values in an array, List
or Map
if switch
is given by an access to an element of that array, List
or Map
.
It is possible to use an array, List
or Map
of lambdas, implement in each lambda a functionality that would refer to case
. As a result, switch
would be replaced by access to an element of this array, List
or Map
and execution of the lambda obtained.
switch case
is recommended when you have defined states and just want to check if a given variable "home" with some values. If you need to do any manipulation, you can do this before entering switch case
or else opting for if else
to make more complex config operations.
The case
itself is already a comparison.
You can not compare an expression with switch case
. Ex:
The code below compiles:
switch(variavel) {
case 1:
System.out.println("Número 1");
break;
}
The code below does not compiles:
switch(variavel) {
case (variavel > 1):
System.out.println("Número 1");
break;
}
To make comparisons as the second case you should use if
.