File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Very tricky one" Watch "Very tricky one" New topic

Very tricky one

Gaurav Chikara
Ranch Hand

Joined: Jun 09, 2000
Posts: 411
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);
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...
- satya

Take a Minute, Donate an Hour, Change a Life
Srivathsan Kris

Joined: Mar 26, 2000
Posts: 7
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.
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).]
I agree. Here's the link:
subject: Very tricky one
It's not a secret anymore!