Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need help with if/else issue....

 
mahesh zarkar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a code here and would like to know why the code prints "Hello" rather than "false"
Code :-
public class MyIf{
public static void main(String argv[]){
MyIf mi = new MyIf();
}
MyIf(){
boolean b = false;
if(b=false)
System.out.println("False");
else
System.out.println("Hello");
}
}
Help appreciated
Mahesh
 
Uday Kumar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess you need "==" double equal to in the if condition.
 
Rick Salsa
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mahesh,
It prints out hello because your expression evaluates to be false. Change the code in the if test to b=true and your example will print out False.
Take a look at the JLS on if-else statements. That might help you.
If statements work by evaluating the expression first. Then checks to see if it results in true or false.

Hope that helps,
/rick
[ February 26, 2002: Message edited by: rick salsa ]
 
Muhammad Usman
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, rick is right.
the if statement execute only its body if it evaluated to true.
 
mahesh zarkar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Uday and Rick,
Thank you for the reply but i am still not clear why b=flase evaluates to false. Bcos as per my understanding if we say that false is assigned to b then the if statement is true bcos b is false already. Am i right...
 
Rick Salsa
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

gets evaluated to:

Then the if statement checks to see the result, "false" and then executes the appropriate statements.
I think you might be confusing it with:

In that case, it would print out "False" as per your code.
/rick
[ February 26, 2002: Message edited by: rick salsa ]
 
mahesh zarkar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rick,
Got it..............
Mahesh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic