• Post Reply Bookmark Topic Watch Topic
  • New Topic

confusing IF block  RSS feed

 
Nirmit Dalal
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Output
b is true

if my variable b stores false as a value then why does the output show "b is true"
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you try to compile and run this program? It will not print "b is true". If you get "b is true", then you're not compiling and running exactly the program you posted above. Probably your real program has a line

instead of

*edit* Ah, I see you've edited your code...

It prints "b is true" because b = true assigns the value 'true' to b, and the result of the expression is also true.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
= is not the same as ==. In fact, this error is one reason why you should just use if(b).
 
Nirmit Dalal
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper i made a change in the IF condition please make a note of it ...and it compiles and runs perfectly
 
Nirmit Dalal
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay ...Thanks guys
 
Nirmit Dalal
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does it only happen if assignment operation of boolean variable is done in the condition expression of IF statement and not with other data type?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nirmit Dalal wrote:Why does it only happen if assignment operation of boolean variable is done in the condition expression of IF statement and not with other data type?


Assignments have a value of the right-hand-side of the expression. So, if you assign any other data type, then the value is of the any other data type. And since IF conditions only take a boolean, this would be a compile time error.

Henry
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The assignment statement works like that for all types. So if i is an int, for example, then i = 2 evaluates to 2.

But the difference is that in Java the condition in an if statement has to be a boolean value. if(i = 2) doesn't type check, so the compiler will reject it. boolean variables are the only ones where = and == return the same type.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!