dimanche 10 juillet 2016

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";}
      System.out.println(model);
    }
}

But, if you change else if (price<=11) to else 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?

Aucun commentaire:

Enregistrer un commentaire