This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
It is not a case of scope of the variable, but whether it has a value. In the case of fields, they have a default value, but local variables do not have default values. If you have that print statement inside the if block, then you can be sure that the variable will have a definite value when the print statement is reached.
If the print statement is outside the if, what happens when the if is not called? You would try to print something without a definite value, and the compiler won’t permit that.
Joined: Oct 13, 2005
You appear to have missed the code button; I have edited your post and you can see how mcuh better it looks don’t sue tabs for indenting; use spaces.
The difference between the two cases is that this makes x a compile-time constant:
while this does not:
When x is a constant, the compiler knows that if (x > 100) is if (1000 > 100) which is of course if (true), so it just gets rid of the if altogether and unconditionally executes the y = -1; line. This means that when it gets to the println() call, it knows that y has been given a value.
When x is not a constant, it doesn't know whether the if block will execute, so it doesn't know whether y will have a value when we try to print it.