What is the difference between two lines of java code?

Sorry for my ignorance. I could not understand the difference between the following seemingly similar lines of code.

  • final int num1 = 1;
  • final int num2; num2 = 2;

What makes num2 not suitable for the switch enclosure constant?

  switch (expression) { case num1: System.out.println("Case A"); case num2: System.out.println("Case B"); } 
+8
java switch-statement
source share
3 answers

We are going to the Java language specification. A switch case expression labels are defined as

 SwitchLabel: case ConstantExpression : case EnumConstantName : default : 

Your num variable does not apply to the enum constant name, so let it ignore it. What are ConstantExpressions ? JLS defines it again

The compile-time constant expression is an expression denoting a value of a primitive type or String , which does not end abruptly and using only the following:

  • Primitive type literals and String literals
  • [...]
  • Simple names (Β§6.5.6.1) that refer to constant variables (Β§4.12.4).

So, the primitive value of int 2 is a constant expression. You could do

 switch { case 2: } 

Now we want to find out the relation using final and a constant variable .

Empty final is the final variable, in the declaration of which there is no initializer. [...]

A variable of a primitive or String type, that is, final and initialized by the expression of a compile-time constant (Β§15.28), is called a constant variable.

Thus, the last quote refers to a non-empty variable final , i.e. one that has an initializer.

So

 final int num1 = 1; 

is a constant variable.

and

 final int num2; num2 = 2; 

not used and therefore cannot be used in the case label.

+7
source share

So, to answer your question: num1 is a compile-time constant, so the compiler can essentially replace it with 1 :

 switch(whatever) { case num1: // will produce same bytecode as case 1: // num1 was replaced by compiler } 

The compiler cannot take the same values ​​in num2 , as explained with a simple example here

Note that you would have the same problem with num1 , you initialized it with int num1 = new Random().nextInt(); , for example: int num1 = new Random().nextInt();

0
source share

in num1 you initialize it right away, in num2, which you don't immediately, you assign its value later

-2
source share

All Articles