Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question regarding "if"

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
what does this mean if(true)?
Thanks for your answers.
Thomas.
class A1 {
public static void main(String args[]) {
boolean b=true;
// if(b) // same as if(b=true)
if(true)
System.out.println("YES");
else
System.out.println("NO");
}
}
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
arun mahajan
Ranch Hand
Posts: 305
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
Arun
 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic