wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Very tricky one Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Very tricky one" Watch "Very tricky one" New topic
Author

Very tricky one

Gaurav Chikara
Ranch Hand

Joined: Jun 09, 2000
Posts: 410
Hi java wizards look at this code
1 public void aa()
2 {
3 boolean flag = false;
4 int k;
5 if(flag)
6 k = 3;
7 else if (!flag)
8 k = 4;
9 System.out.println(k);
10}
It gives compile time error stating k is not initialised
but when i remove the portion if (!flag) from line 6
it compiles
another case when i write simply if(!flag) on line 6 instead of else then again it gives same compiler eror
Can anyone explain it?


SCJP,SCWCD,SCBCD<br />If Opportunity doesn't knock then build the door
Paul Smiley
Ranch Hand

Joined: Jun 02, 2000
Posts: 244
Remember the compiler is not THAT smart. It looks for a possible path where a variable does not get initialized. If you do an if - else that covers 100% of the cases, you won't get the error.
Since you did an if - else if , even though they do logically cover 100% of the cases as you noted, the compiler cannot interpret your logic. What it sees is a potential path where the first if is false and the else if is also false. Even though we know it will never happen, the compiler doesn't. Thus the error.
[This message has been edited by Paul Smiley (edited July 12, 2000).]
Madhav Lakkapragada
Ranch Hand

Joined: Jun 03, 2000
Posts: 5040

To add to what Paul said.....
logic is evaluated only at runtime.
Hence, the error during compile.
I guess its probably safe to assume
that we don't know the expression inside
the boolean test...
Regds.
- satya


Take a Minute, Donate an Hour, Change a Life
http://www.ashanet.org/workanhour/2006/?r=Javaranch_ML&a=81
Srivathsan Kris
Greenhorn

Joined: Mar 26, 2000
Posts: 7
Hi
Here in the code snippet the variable is local. So the compiler expects u 2 initialize a variable. It looks till the last of the code. as it doesnt find one it throws as an error.
Regds
Srivathsan
rajsim
Ranch Hand

Joined: May 31, 2000
Posts: 116
Actually, the compiler can be smart enough to compile
this code successfully, but I think JLS requires
the compiler to reject such cases.
However, if you change the flag to be "final" as in
final boolean flag = false;
The code compiles and works as expected.
In this case, the compiler is able to prove that
"k" will definitely have some value before it
reaches the "println" statement.

[This message has been edited by rajsim (edited July 12, 2000).]
 
 
subject: Very tricky one