There isn't a meaningful difference between the two as far as these code samples are concerned. The only difference is the initialization of x. In the first code sample x is initialized when declared, and in the second code sampe it is declared first and initialized later. Both are legal, and should compile.
Thimal Deemantha wrote:No the 2nd could not compile
Could you post the full code of the application please, because I think I might know why you're getting a compiler error, but it's not down to either of the isolated code samples.
Also, as you may have noticed I've taken the liberty of editing your opening post to make the Java code snippet a bit more readable to people trying to help. You can do this to, all you need to do is UseCodeTags (< click).
Jelle Klap wrote:Yeah, that's what I figured. The difference is that in the first case x is a compile time constant. i.e. the compiler knows that x will always have value 101, and by extension it knows that the if-condition will always be true and y will always be initialized to value -1. That's why it's legal to use y in the System.out.println() call: the compiler knows it was initialized to a value. In the other code sample x isn't a compile time constant and all the implications that held up in the first code sample don't. This leads the compiler to complain about the use of y, because it can't figure out whether or not it was initialized. At runtime, this is clearly the case, but the compiler just isn't smart enough to pick up on that.