Hi, Any local variable should be assigned before they are used, otherwise it is a compiler error. And there are some rules in JLS about the same. i could not fully digest the rules, but can somebody try this out in your JVM? In my JVM it DOES COMPILE fine.
However, notice the first for loop is just infinite loop. However if I change the code like as follows, the code complains of missing definite assignment.
If I change the code sample-3 break to continue, it again compiles fine. Is this related to reachability?
[ April 12, 2006: Message edited by: Binu K Idicula ] [ April 12, 2006: Message edited by: Binu K Idicula ]
The part x=readint() will never get called, so the code does not compile. When you dont have the break statement (code sample 2) , the code will never reach the block, where x is accessed, so you dont get any compilation error.
BTW, i am not getting any compilcation error for code sample 2
I am confused with this code. The difference between sample 1 and sample 2 is that in sample 1 k and x are declared on 1 line but in sample 2 they are declared on separate lines.
Sample 1 compiles fine for me but sample 2 I get a compilation error that x might not have been initialised.
Can anyone please explain why these 2 ways of declaring variables would make any difference.
I would have expected a compiliation error in both samples.
Binu K Idicula
posted 14 years ago
I think I should agree with Vishal in doubting unreachability which is not certain a compile time. if I say,
1. int x; 2. if(true||(x=1)==1) return; 3. boolean y = false;
Compiler will not complain that statement 3 is unreachable. However I trust compiler should complain about chance of a local variable uninitialised and accessed. BUT IT DOESNOT COMPLAIN ABOUT LINE 3 in the following code sample, trying to access x, which is unitialized. I agree it is not reachable, but is it beyond rule?
1. int x; 2. if(true||(x=1)==1) return; 3. System.out.println(x); 4. boolean y = false;
regards Binu K Idicula [ April 13, 2006: Message edited by: Binu K Idicula ]