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?
source share