Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Very tricky one

 
Gaurav Chikara
Ranch Hand
Posts: 412
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Paul Smiley
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5040
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

 
Srivathsan Kris
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic