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,
model
must be initialized before the System.out.println(model);
statement in order for the code to pass compilation.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With