Why does the java compiler complain that local variables are not initialized here?
•
Java
int a = 1,b;
int a = 1,b; if(a > 0) b = 1; if(a <= 0) b = 2; System.out.println(b);
If I run this, I receive:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The local variable b may not have been initialized at Broom.main(Broom.java:9)
I know that the local variable is not initialized, and you have the responsibility to do so, but in this case, the first if does not initialize the variable?
Solution
If you change the second if to else, the compiler will be happy
int a = 1,b; if(a > 0) b = 1; else b = 2; System.out.println(b);
If you really want to delve into this problem, a whole chapter of the Java language specification is devoted to the problem of definition assignment This case is related to your specific example:
This particular example (and many other illustrative examples) may seem against your expectations, but that's the way language designers want it. All compilers must follow the rules
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码