This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Need help with if/else issue.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Need help with if/else issue...." Watch "Need help with if/else issue...." New topic
Author

Need help with if/else issue....

mahesh zarkar
Greenhorn

Joined: Feb 14, 2002
Posts: 24
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


In search of Excellence.
Uday Kumar
Greenhorn

Joined: Jan 22, 2002
Posts: 24
I guess you need "==" double equal to in the if condition.
Rick Salsa
Ranch Hand

Joined: Jul 17, 2001
Posts: 173
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

Joined: Nov 18, 2001
Posts: 29
yes, rick is right.
the if statement execute only its body if it evaluated to true.


an student of Operation Badar ( a educational movement in Pakistan).
mahesh zarkar
Greenhorn

Joined: Feb 14, 2002
Posts: 24
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

Joined: Jul 17, 2001
Posts: 173

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

Joined: Feb 14, 2002
Posts: 24
Rick,
Got it..............
Mahesh
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Need help with if/else issue....
 
Similar Threads
Boolean Que
questions from Marcus Green tutorial
Byte
Byte and String
need help