Why is a local variable launched in if-else constructs, but not in if-else-if constructs?

So, we know that a local variable must be initialized for use in the if-else-if construct. As an example, the following code will not compile.

public class Test { public static void main (String...args){ double price= 11; String model ; if (price>10) {model ="smartphone";} else if (price<=11) {model="not smart phone";} System.out.println(model); } } 

But if you change the else if (price<=11) to else or initialize the local variable String with a model to some random value, the code will be compiled successfully. My question in this case is "why?"

Now it was a question from the book, and the explanation was:

"the local variable of the model is declared, not initialized. The initialization of the model variable is placed inside the if and else-if constructs. If you initialize the variable in the if or else-if construct, the compiler cannot determine whether these conditions are evaluated to true, which will not result to initialize a local variable.

Even after the explanation, I still did not understand two things,

  • I'm not sure why the variable model will confuse the compiler, since the double price is 11 no matter what model.
  • How does this magically initialize a local variable when you add else to the end?
+5
source share
1 answer

model must be initialized before the statement System.out.println(model); so that the code passes the compilation.

  • The compiler does not analyze the conditions of the if-else-if statements to determine whether one of them will always be executed, so it cannot be sure that the if or else-if blocks are always executed, and therefore it cannot be sure that the model will be initialized before the println statement.

  • When you use the if-else construct, an if or else block will execute, so since both of them are initialized by model , it is guaranteed to be initialized before the println statement.

+11
source

All Articles