posted 22 years ago
Preeti,
The local variable declaration statement may or may not have initialization statement. If a local variable decalration does not have an initialzation, then compiler must prove that, according to the rules of definite assignment, every reference to this variable is preceded by an assignment to it.
In the example given by you, when "else part" was commented out, the compiler knew that assignment to local variable takes place only when condition was true, (i.e for n> 0). in all other cases, assignment was not taking place. This is not sufficient in case of local variables.
On the other hand, when else part was not commented out, compiler knows that whether or not condition is true or false, assignment takes place always.
If you want to go further and experiment, I would ask you to see what happens when following code is executed.
... //rest of your code
String tm;
if (true)
tm = "positive";
System.out.println(msg+tm);
... //restof your code
Do you think that this will compile? Sure it will! Because we used "true" (which is a literal constant that has a value = true always) as the conditional expression and compiler knows that assignment will take place always in this case.
I hope I cleared your doubts. If you have any further questions, please feel free to post them here.
Thanks,
Rajesh
[This message has been edited by Rajesh Radh (edited March 28, 2001).]
[This message has been edited by Rajesh Radh (edited April 04, 2001).]