This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the difference between these boolean expression

 
Avais Aziz
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please shed some light
when I write the following code I get compile time error, it
says that b is not initialized
and when I change the boolean expression to true it works.

Now if I change it like below it works fine

 
Martin Rennix
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Avais Aziz
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! Martin
I asked many people but this is the first proper
answer to this question. Thanks again
Avais
 
Terence Doyle
Ranch Hand
Posts: 328
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Bye,

------------------
Terry Doyle
Sun Certified Programmer for Java 2 Platform
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic