The code in the first example fails to compile because the b=2 line is dependant on a conditional that could be false. In other words (a>3) might not always be true, in which case b would never get initialised. It's because you have a variable (a) in the conditional expression. The second example compiles ok because the conditional is always true and hence b will always be initialised. Bottom line is always initialise your variables when you declare them! Martin
Joined: Oct 07, 2001
Thanks! Martin I asked many people but this is the first proper answer to this question. Thanks again Avais
HI, Two solutions: If you declare a as final the code compiles because the condition will always be true. OR if you declare b ouside main() like this: static int b; it will then be a class member variable and automatically be assigned a default value at class construction time. Method variables are not assigned any value because they are considered local variables and must be manually initialised.
------------------ Terry Doyle Sun Certified Programmer for Java 2 Platform