Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>So it can be evaluated during the compilation phase ( statically check ) </p> <p>See: <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11" rel="noreferrer">http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11</a> for a formal definition of the <code>switch</code>.</p> <p>Additionally it may help you to understand better how that <code>switch</code> is transformed into bytecode:</p> <pre><code>class Switch { void x(int n ) { switch( n ) { case 1: System.out.println("one"); break; case 9: System.out.println("nine"); break; default: System.out.println("nothing"); break; } } } </code></pre> <p>And after compiling: </p> <pre><code>C:\&gt;javap -c Switch Compiled from "Switch.java" class Switch extends java.lang.Object{ Switch(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."&lt;init&gt;":()V 4: return void x(int); Code: 0: iload_1 1: lookupswitch{ //2 1: 28; 9: 39; default: 50 } 28: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 31: ldc #3; //String one 33: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 36: goto 58 39: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 42: ldc #5; //String nine 44: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 47: goto 58 50: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 53: ldc #6; //String nothing 55: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 58: return } </code></pre> <p>See that line marked as <code>1:</code> </p> <pre><code> 1: lookupswitch{ //2 1: 28; 9: 39; default: 50 } </code></pre> <p>It evaluates the value and goes to some other line. For instance if value is <code>9</code> it will jump to instruction 39: </p> <pre><code> 39: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 42: ldc #5; //String nine 44: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 47: goto 58 </code></pre> <p>Which in turn jumps to instruction 58 :</p> <pre><code> 58: return </code></pre> <p>All this wouldn't be possible if it was evaluated dynamically. That's why.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload