I'm working on a java source code that has the style:
if (0 == var) {}
and
if (null == someObj) {}
or
if (0 != var) {}
and
if (null != someObj) {}
Should I rewrite it to:
if (var == 0) {}
and
if (someObj == null) {}
?
Thanks in advance!.
No, if the first condition returns false then the whole expression automatically returns false. Java will not bother examining the other condition.
The break statement is used inside the switch to terminate a statement sequence. The break statement is optional. If omitted, execution will continue on into the next case.
The Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Java has three logical operators: && , || , and ! , which respectively stand for and, or, and not.
It's perfectly valid to have:
if (0 == var) {}
and
if (null == someObj) {}
It's famously called yoda condition to prevent accidental use single =
in place of ==
.
I personally never used it. But some people like it. It's really a matter of taste.
However, it's of no use in Java. Because, such an accidental typo is caught at compile time.
The following would give a compile time error in Java.
if( var = 0 )
{
//Some code
}
Because assignment operation doesn't yield Boolean value in Java.
However, in languages like C/C++, the above is valid and compiler would give no errors if warnings are not enabled. The above if
condition will always evaluate to false (0) in C/C++. So it may go unnoticed and give unexpected results at run time.
In GCC, with all warnings enabled, it would give the warning for the above in C or C++:
warning: suggest parentheses around assignment used as truth value
So this may not of much use in C/C++ too as one is expected to compile with all warnings and fix all warnings. As I said before it's a personal choice and makes no difference.
So if ( 0 == var){}
is a valid syntax and is same as if (var == 0) {}
and if you prefer Yoda conditions it, go for it!
In general to write 0 == n
is called a yoda condition
. Because if you say it loud you say if zero equals my var
.
It is better to write n == 0
. But it is exactly the same. But it is read better.
Some of the pros of the condition does not apply to java.
if (value = 42)
yields a compile error. value = 42
yields an int
which is not a valid input in an if
in java. But perfectly legal in C
.
To compare using the constant
on the left side is a common best practice. But only if using Object equals method.
if ("CONSTANT".equals(myString))
if myString
is null or you are comparing primitives
since there is no .equals()
access to the variable theres no point in checking null.
if ( "CONSTANT" == null )
Although is only my opinion, the benefit is legibility only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With