How does Java's switch work under the hood?

前端 未结 7 1177
花落未央
花落未央 2020-12-10 23:54

How does Java\'s switch statement work under the hood? How does it compare the value of the variable being used, to those given in the case parts? Does it use ==

相关标签:
7条回答
  • 2020-12-11 00:43

    Neither. it uses the lookupswitch JVM instruction, which is essentially a table lookup. Take a look at the bytecode of the following example:

    public static void main(String... args) {
      switch (1) {
      case 1:
        break;
      case 2:
        break;
      }
    }
    
    public static void main(java.lang.String[]);
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   iconst_1
       1:   lookupswitch{ //2
                    1: 28;
                    2: 31;
                    default: 31 }
       28:  goto    31
       31:  return
    
    0 讨论(0)
提交回复
热议问题