File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Question regarding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question regarding "if"" Watch "Question regarding "if"" New topic

Question regarding "if"

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
what does this mean if(true)?
Thanks for your answers.
class A1 {
public static void main(String args[]) {
boolean b=true;
// if(b) // same as if(b=true)
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
You know ?
In if(true), the boolean expression is true. true is just a boolean literal. So the // do this code will be done.
This is a technique used for including/excluding
code for debugging or testing. The compiler will
also allow such "unreachable" statements not to be treated as compilation errors.
[ October 09, 2002: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
arun mahajan
Ranch Hand

Joined: Dec 07, 2001
Posts: 305
As Barry explained it will execute the block against the boolean value. Just to add you can't write
// same as if(b=true)
the above is an assignment, rather you should comapre it like
// same as if(b==true)
Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
Hello Arun,
if i compare a boolean variable it is also ok to write if (b = true) as it is ok to write if (b==true).
But when you compare non booleans it is only possible to say "==".
if (a == b) ...
public class BooleanTest1 {
public static void main (String[] argv) {
int i = 10;
int j = 10;
boolean b = false;
if(b = true) //Test Boolean with "=" is ok
System.out.println("b = is True");
if(b == true)//This is better
System.out.println("b == is True");

// if(i = j) compiler error: Compare NON-Booleans
// always with "=="
// System.out.println("i=j = is True");
if(i == j)
System.out.println("i==j is True");

Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Thomas Markl:
if i compare a boolean variable it is also ok to write if (b = true) as it is ok to write if (b==true).

b = true is not a comparison, but an assignment.
if (b = true)
is the same as
b = true;
if (b)

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Don't get me started about those stupid light bulbs.
subject: Question regarding "if"
It's not a secret anymore!