A variable is assigned in all switching cases, but does Java say that it may not be so?

Why is this Java code not compiling?

class A { public static void main(String[] args) { boolean b; switch(1) { case 1: b = true; } System.out.println("b: " + b); } } 

He complains that b may not have been initialized, although he is in all cases, as far as I can tell. How b cannot be initialized?

 $ javac A.java A.java:8: variable b might not have been initialized System.out.println("b: " + b); ^ 1 error 
+4
source share
2 answers

You need to initialize it in advance or add a default clause:

 switch (1) { case 1: b = true; default: b = false; } 

It is simply not possible for the JVM to analyze all possible cases, not even for a literal. At least, as @assylias points out, the language specification does not require it to be.

Therefore, from the point of view of code analysis, it must process the literal as well as process the variable, and cannot know that the selected path is always selected, even here, where we can easily see that the first case will always correspond.

So, he should see that the variable b initialized no matter what the value is, and therefore requires a default clause.

+4
source

You can refer to JLS # 16.2.9 . In particular, without the default statement, the compiler cannot decide that b definitely assigned after the switch statement, even if this is obvious in your example.

+1
source

Source: https://habr.com/ru/post/1479270/


All Articles