Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

if - boolean

 
Arnb Sen
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code compiles and runs with NO output. Cannot understand why ?

 
Henry Wong
author
Marshal
Pie
Posts: 21194
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What were you expecting? The print statement is in a condition that is set to false.

Henry
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Normally an if statement would not compile if you replace == with =. However in this case it compiles, because b is boolean. An assignment (=) has the side effect of returning the value assigned, which means for example

Here the last statement assign y = 1, and then assigns x = 1. Because (y = 1) not only assigns y = 1; it also evaluates to 1. So

is the same as

Similarly,

is the same as

[ November 27, 2005: Message edited by: Jim Yingst ]
 
Campbell Ritchie
Sheriff
Pie
Posts: 49382
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't need to use = or == in the if () statement when dealing with a boolean primitive variable. You just write
 
Campbell Ritchie
Sheriff
Pie
Posts: 49382
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and I forgot you want it to work if myBoolean is false. Then all you have to write is,

CR
 
Arnb Sen
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you everyone.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49382
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pleasure
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic