• Post Reply Bookmark Topic Watch Topic
  • New Topic

A question on Compilation of Local Variables  RSS feed

 
Ianz Somald
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why



Gives Compile Time Error

but



does not. Please explain the reason.

Thanks
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I added code tags to your post (always use the tags) and doesn't it look better It would have been even better if you had indented the code a bit better.
The javac tool is not programmed to retain the value of variables unless they are marked final. That means it does not keep track of the value of a from line 1 to line 2, so it cannot determine that the value of a is 4 at that point. That means there is a possibility that b has not been definitely assigned to before being used in line 4.
In the other code block however, the if‑else does assign a value to b in every path through it, and the javac tool can see that those paths encompass all possibilities, so b is definitely assigned to before line 7.
For more information you would have to go through the Java® Language Specification and see what it says about definite assignment.
 
Fred Kleinschmidt
Bartender
Posts: 571
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Campbell says, The compiler does not execute the code, so it does not know that a will always be 4, so in your first version, it sees that there is a path that might reach the print statement when b is still not initialized.

Also, you should learn to indent your code for better reading.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!