This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
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

Simple boolean question?

 
Dave Johnson
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the code:

Now I know that if the if statement read: if(a==true), the code would then compile & run & display Goodbye. What I cannot understand is why as the code stands does it take a boolean value as false and then interprete it as true?
I have seen this a few times and although I know to answer it correctly I still don't understand why the code does what it does!
Thanks, Dave.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The value of the assignment expression "a = true" is true -- it assigns "true" to "a" and returns the value "true". So it's as if you had written "if (true)". The fact that assignment expressions have a value is what makes it possible to write statements like "i = j = k = 0;" which is interpreted as
"i = (j = (k = 0));"
There's a really easy way to avoid this error, by the way: you should never compare to a boolean literal. Instead of writing "if (a == true)", always write "if (a)" . Similarly, you can and should replace "if (a != true)" with "if (!a)".
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What I cannot understand is why as the code stands does it take a boolean value as false and then interprete it as true?
Within your "if", you have an expression that assigns true to the variable. Since the variable is of boolean type, the whole expression then evaluates to true.
 
Dave Johnson
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many thanks for your time taken to reply, very much appreciated Dave.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic