Operation of the switch case

Asked

Viewed 972 times

2

It is possible to make comparisons with variable values in the instruction switch case or the case just checks the value of a variable and makes an action? It is better to make this kind of comparison with if?

3 answers

5

No. In Java, the switch only works with constant values in cases. Other dynamic languages such as Javascript can use variables in cases, but Java does not.

One of the reasons is the way the switch is compiled - it becomes a fixed table in the bytecode containing a map (-to) of integer values to instruction addresses within the methods. Since this table is fixed and constant in bytecodes, there is no way it depends on values of variables that are only available at runtime.

In the case of switch with enums, the compiler turns it into a switch in the ordinal() of enum. In the case of switch with Strings, the compiler turns it into a switch with the hashCode()s of Strings (and uses a sequence of ifs when the hashes collide). Anyway, the switch always be done by means of a fixed table determined at compilation time by mapping a number to an instruction address of the method.

Therefore, the most obvious alternative would be to use the if. However, other alternatives are possible. For example:

  • Turn the call to switch in a call to a polymorphic method of some object and transform each case in an implementation of this polymorphic method.

  • If the purpose of switch is within each case define a value different from the same variable, you can put all these values in an array, List or Map and replace the switch by an access to an element of that array, List or Map.

  • It is possible using an array, List or Map to implement in each lambda a functionality that would refer to a case. With that, the switch would be replaced by access to an element of that array, List or Mapand execution of the lambda obtained.

2

The switch case is recommended when you have set states and just want to check if a given "house" variable has some values. If you need to do some manipulation, you can do it before entering the switch case or opt for the if else to perform more complex operations.

2

The very one case That is a comparison. It is not possible for you to 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 nay compilation:

switch(variavel) {
    case (variavel > 1):
        System.out.println("Número 1");
        break;
}

To make comparisons as the second case should be used if.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.