Is if(x) same as if(x==true)?
Solution 1
Yes,
if(x) {
}
is the succinct equivalent of
if(x == true) {
}
As @Sotirios points out, they are different at the bytecode level. Consider the following Java class:
class Test {
public void foo() {
boolean x = true;
if(x == true) {
}
}
}
emits:
public void foo();
Code:
0: iconst_1
1: istore_1
2: iload_1
3: iconst_1
4: if_icmpne 7
7: return
vs
class Test {
public void foo() {
boolean x = true;
if(x) {
}
}
}
which emits:
public void foo();
Code:
0: iconst_1
1: istore_1
2: iload_1
3: ifeq 6
6: return
I don't think this has any bearing on the performance or correctness of the program.
Solution 2
Yes, it is.
if
checks if the condition is true, and if it is, executes the body statement. So x
needs to be a boolean
expression.
In fact x
is equivalent to x == true
if x
is a boolean expression, so you should use x
as it is more concise. This becomes clearer if the variable has a proper name for a boolean, e.g.
if (this.isVisible()) {
this.hide();
}
vs.
if (this.isVisible() == true) {
this.hide();
}
The first one is better to read.
Solution 3
Yes, it is same as if(x == true)
. In fact if(x)
is recommended.
See the examples in The if-then and if-then-else Statements in The Java tutorial.
Solution 4
If x
can be resolved as a boolean, and the value is "true", the "other stuff" will be executed.
Solution 5
Yes, it means the same thing as if you had if(x == true).
Freedom
You can have the project: -Done On Time -Done On Budget -Done Properly Pick two.
Updated on June 05, 2022Comments
-
Freedom almost 2 years
Ok, so let's say I have an if statement and a boolean x:
if (x) { // some stuff }
What happens here? Does this mean the same thing as
if(x == true)
?-
Amir Afghani about 10 yearsyes, yes it does.
-
Freedom about 10 yearsOkay thanks, I've been seeing a lot of this used in code and I was always wondering.
-
Sotirios Delimanolis about 10 yearsSemantically, it is equivalent. At the bytecode level, it is not.
-
Kayaman about 10 years@SotiriosDelimanolis Really? Any good reason the compiler doesn't compile it to the same bytecode?
-
Sotirios Delimanolis about 10 years@Kayaman Yes. As for a good reason, I don't know. The
==
is an extra operation. -
yitzih about 10 yearsand at the other end if(!x) is the same as
if(x != true)
orif(x == false)
-
david.pfx about 10 yearsIt means exactly the same, but whether the same code is generated depends on the compiler. It should be, but don't count on it.
-
Raedwald about 10 years
-
-
Mattias Buelens about 10 years
x ? true : false
is just as redundant asx == true
, and they're both equivalent to simplyx
. -
Admin about 10 yearsWell i just wrote this example to make sure that he knows this version of an if statement too. It isn't a example for production.