SERich SERich - 3 months ago 3x
Java Question

Why does a local variable get initiated in if-else constructs but not in if-else-if constructs?

So We know that a local variable has to be initialized in order to be used in 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";}

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

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

"the local variable model is only declared, not initialized. The initialization
of the variable model is placed within the if and else-if constructs. If you initialize a variable within an if or else-if construct, the compiler can’t be sure whether these conditions will evaluate to true, resulting in no initialization of the local variable."

Even after the explanation, I still didn't understand two things,

  1. I am not sure why variable model will confuse the compiler, since double price is 11 regardless of what model is.

  2. How does it magically initialize the local variable when you put else at the end?


model must be initialized before the System.out.println(model); statement in order for the code to pass compilation.

  1. The compiler doesn't analyze the conditions of the if-else-if statements to determine whether one of them will always be met, so it can't be sure that either the if or else-if blocks are always executed, and therefore it can't be sure that model will be initialized prior to the println statement.

  2. When you use an if-else construct, either the if or else block would be executed, so since both of them initialize model, it is guaranteed to be initialized prior to the println statement.