I've come across this code in one of the projects I'm working on
(This is in Java)
if (Boolean.TRUE.equals(foo.isBar()))
Foo#isBar() is defined as boolean isBar(), so it can't return null
Is there really any reason why it should be written that way?
I myself would just write
if (foo.isBar())
, but perhaps I'm missing something subtle.
Thanks
I hope foo.isBar() returns a boolean. In that case you can always write if (foo.isBar()). If you foo.isBar() returns Boolean then it can be either Boolean.TRUE, Boolean.FALSE or NULL. In that case if (Boolean.TRUE.equals(foo.isBar())) makes sure the if block is executed in one scenario(TRUE) and omitted in remaining 2.
Over and above if (foo.isBar()) will fail, when foo.isBar() returns Boolean NULL.
Since isBar returns a primitive boolean, there is no semantic difference. Additionally, the second way is more concise, more clear, and more efficient, since the result won't have to be autboxed for the call and then have the original boolean extracted again. Given all that, there is no reason to use the first method, and several to use the second, so use the second. I give a great deal of leeway to fellow coders, but I would sit down and have a chat with anyone who added something like that to professional code.
I would suspect "old legacy code with no good reason" - and in fact, I would contend it is worse. (I wonder how ints are compared ..)
The code that uses TRUE.equals requires a boxing conversion, an additional method call (and everything inside) and, in the end, it just looks sloppy.
The only reason I am aware of is if foo.isBar was typed as returning Boolean (not boolean) and where it may return null:
Boolean b = null;
// throws an exception when it tries to unbox b because it is null
boolean isTrue1 = (boolean)b;
// evaluates to false
boolean isTrue2 = Boolean.TRUE.equals(b);
// evaluates to false as well
boolean isTrue3 = b != null ? (boolean)b : false;
Did I find this practical example, can be useful to someone:
When boxed type java.lang.Boolean is used as an expression it will throw NullPointerException if the value is null as defined in Java Language Specification §5.1.8 Unboxing Conversion.
It is safer to avoid such conversion altogether and handle the null value explicitly.
Noncompliant Code Example
Boolean b = getBoolean();
if (b) { // Noncompliant, it will throw NPE when b == null
foo();
} else {
bar();
}
Compliant Solution
Boolean b = getBoolean();
if (Boolean.TRUE.equals(b)) {
foo();
} else {
bar(); // will be invoked for both b == false and b == null
}
in the first condition you are checking for the equality of Boolean object corresponding to true.
and you are using the first condition in your code because your java version doesn't support autounboxing hence you need to use the boolean object.
What is the difference between Boolean.TRUE and true in Java?
Related
I have 2 java statements:
if(myvar!=null)
if(null!=myvar)
Some people says that second form is better because it helps to avoid NPEs, is it true? What is generally beter to use in java?
if(myvar!=null)
if(null!=myvar)
Some people says that second form is better because it helps to avoid
NPEs, is it true?
No. These are exactly the same, and there is no risk of NPE here to avoid.
Maybe you confused the example with this situation:
if (myvar.equals("something"))
if ("something".equals(myvar))
Here, if myvar is null, the first form would throw an NPE, since .equals would be dereferencing a null value, but the second one works just fine, as the .equals implementation of String handles a null parameter gracefully, returning false in this example. For this reason, in this example, the 2nd form is generally recommended.
A related argument, which one of these is preferred?
if (myvar == null)
if (null == myvar)
Consider the possibility of a typo, writing a single = instead of ==:
if (myvar = null)
if (null = myvar)
If myvar is a Boolean, then the first form will compile, the second form will not. So it may seem that the second form is safer. However, for any other variable type, neither form will compile. And even in the case of a Boolean, the damage is very limited, because regardless of the value of myvar, the program will always crash with an NPE when the if statement is reached, due to unboxing a null value.
Since no test will ever get past this statement, and since you should not release untested code, making such mistake is unrealistic.
In short, the safety benefit is so marginally small that it's practically non-existent, so I don't see a reason to prefer this unusual writing style.
Update
As #Nitek pointed out in a comment, an advantage of adopting the second form could be if you make it a habit, so that when you program in other languages where myvar = null might compile, you'd be slightly safer, out of your "good habits".
I'd still point out that in many languages comparisons with null are special, with no possibility of such typo errors. For example in Python, myvar == None is incorrect, and should be written as myvar is None, so there's no more == to mistype.
Strictly speaking, although the null = myvar writing style will not protect you in all languages, it might protect you in some, so I'd have to admit it seems to be a good habit.
This is not true, they are the same.
I prefer the first one because i think it reads better.
if(myvar!=null)
if myvar is not equal to null
and
if(null!=myvar)
if null is not equal to myvar
There is no certain difference in both of them both refer to the same check
if(myvar!=null)
if(null!=myvar)
both are the exact same things.
But in depper context it is the Yoda Condition.
It is generally criticized because of its readability issues, so try to make every thing simple for yourself and for other people who might read your code as this is not a standard notation.
This is primary opinion based, but I always go with
if (variable == null)
if (variable != null)
because imo it´s a better programming style.
And a short answer to your post, no difference between them.
There is no practical difference in your case.
15.21. Equality Operators
The equality operators are commutative if the operand expressions have no side effects.
That is, you can have a situation where the LHS and RHS matter because evaluating them can cause a change in the other, but not if one of them is the keyword null.
Consider the following example:
public class Example {
static int x = 0;
public static void main(String[] args) {
System.out.println(doit() == x); // false
System.out.println(x == doit()); // true
}
static int doit() {
x++;
return 0;
}
}
Furthermore,
15.21.3. Reference Equality Operators == and !=
The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.
shows that there is no difference in the evaluation.
As Nitek wrote in the comment to my initial question:
The second one prevents typos like "myvar=null" because "null=myvar" won't compile. Might save you some trouble.
So, we have a BIG advantage of the second form - it helps to prevent serious logic error. Example:
Boolean i=false;
....
if(null=i){
}
won't compile
but
Boolean i=false;
....
if(i=null){
}
will
But the second form has a big disadvantage - it's reading difficulties.
So I would say that in 99% cases the first form is ok, but I prefer to use the second form. If you are sure you won't mix == and = up, use the first form. If not, use the second. I'm sure there are a couple of other cases when the second form is preferred, but can't remind it at the moment.
I was wondering if there is a straightforward way (one-line, without creating a function) to convert String to Boolean in Java, but in a way that Boolean is null if String is null.
If I see it correctly, all of the methods from the Boolean class are returning false if the input string is null. Why is that?
Why is it better that Boolean.valueOf(String s) returns false in the case of s being null, rather than returning null?
Why is it better that Boolean.valueOf(String s) returns false in the case of s being null, rather than returning null?
Because out the build-in feature in Java, called autoboxing.
Let's suppose that Boolean.valueOf(String s) was actually returning null, when s is null. Then, the following statement would be throwing NullPointerException, because null cannot be assigned to a primitive:
boolean b = Boolean.valueOf(null);
Why is it better that Boolean.valueOf(String s) returns false in the case of s being null, rather than returning null?
It is a matter of opinion, and (to be frank) pointless to ask ... unless you happen to be designing your own language and runtime libraries. The design decision was made more than 20 years ago, and there is zero chance that it will be changed while the language is called "Java".
The javadocs for Boolean.valueOf(String) don't offer any clues as to why the designers designed it this way.
However, it is clear that the behavior of Boolean.valueOf(String) is inconsistent with the behavior of valueOf(String) for the other primitive wrapper classes. For example Integer.valueOf(String) throws NumberFormatException if the string argument is null. So it is possible that the real explanation is that the Boolean.valueOf(String) semantics are just an unfortunate anomaly that is the result of an oversight that occurred in the rush to release Java 1.0.
However, that is speculation. For a real answer you would need to consult relevant internal Sun / Oracle documentary sources (if they still exist) and / or talk to someone on the original Java team (if they can still remember).
You can use the ternary operator :
String s = ...
Boolean b = s != null ? Boolean.valueOf(s) : null;
This question already has answers here:
Which is more effective: if (null == variable) or if (variable == null)? [duplicate]
(9 answers)
Closed 9 years ago.
This may just be a style question, but I'm reading a Java coding book ('Programming Android') and the writer all declares null first before a variable method, a practice I am not familiar with. For example:
if (null == foo) {
//code here
}
or
if (null != foo) {
//code here
}
instead of
if (foo == null) {
//code here
}
I can't see how the order would make a difference semantically/syntactically, or am I wrong here? Really just curious.
It's probably a habit left over from C/C++. In C, you would put constants on the left, because if you mistyped = instead of == there would be an error because you can't assign something to a constant. In Java, this is unnecessary because if (foo = null) also gives an error, which says that an object reference isn't a boolean.
This is a holdover from C/C++. It was advantages to put the value on the left of the == operator in case you accidently used the assignment = operator. The C compiler will catch the 14 = var as an error, but var = 14 will compile, when you meant to type var == 14. There is not much reason to do this in Java, but some still do it.
Sometimes order saves you from null pointer exception e.g. if a String variable is coming from somewhere and you compare it like this:
if(foo.equals("foo")){
}
then you might get Null pointer exception. On the other hand if you do it like this:
if("foo".equals(foo)){
}
then you not only achieve your purpose but you also avoid a null pointer exception in case String foo was null.
No difference.
Second one is merely because C/C++ where programmers always did assignment instead of comparing.
E.g.
// no compiler complaint at all for C/C++
// while in Java, this is illegal.
if(a = 2) {
}
// this is illegal in C/C++
// and thus become best practice, from C/C++ which is not applicable to Java at all.
if(2 = a) {
}
While java compiler will generate compilation error..
There is no really different between two form. There is no performance issue but there are following notes:
First form is readable for code reader, because people usually read
codes Left-To-Right.
Second form is better for code writer, because in java = operator is
for assignment and == operator is for test equivalent, but people
usually using in if statement = instead of ==, by second approch
developer getting Compile-Time-Error because null can't use in
Left-Side of a assignment statement.
ADDED
if (object = null) {
The convention of putting the constant on the left side of == isn't
really useful in Java since Java requires that the expression in an if
evaluate to a boolean value, so unless the constant is a boolean,
you'd get a compilation error either way you put the arguments. (and
if it is a boolean, you shouldn't be using == anyway...)
There is no difference, and
if (foo == null)
enter code here
is the prefered way; however in C, you would put constants to the left since there would be an error if you used = instead of ==
I have the following code:
Boolean bool = null;
try
{
if (bool)
{
//DoSomething
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
Why does my check up on the Boolean variable "bool" result in an exception?
Shouldn't it just jump right past the if statement when it "sees" that it isn't true?
When I remove the if statement or check up on if it's NOT null, the exception goes away.
If you don't like extra null checks:
if (Boolean.TRUE.equals(value)) {...}
When you have a boolean it can be either true or false. Yet when you have a Boolean it can be either Boolean.TRUE, Boolean.FALSE or null as any other object.
In your particular case, your Boolean is null and the if statement triggers an implicit conversion to boolean that produces the NullPointerException. You may need instead:
if(bool != null && bool) { ... }
Use the Apache BooleanUtils.
(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)
Don't reinvent the wheel. Leverage what's already been built and use isTrue():
BooleanUtils.isTrue( bool );
Checks if a Boolean value is true, handling null by returning false.
If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans and Strings. I suggest you peruse the various Apache libraries and see what they already offer.
Or with the power of Java 8 Optional, you also can do such trick:
Optional.ofNullable(boolValue).orElse(false)
:)
Boolean types can be null. You need to do a null check as you have set it to null.
if (bool != null && bool)
{
//DoSomething
}
if (bool) will be compiled to if (bool.booleanValue()) aka unboxing and that would throw a NullPointerException if bool is null.
Other solutions for nullable boxed Boolean evaluation:
JDK 9+ requireNonNullElse(obj, defaultObj)
import static java.util.Objects.requireNonNullElse;
if (requireNonNullElse(bool, false)) {
// DoSomething
Google Guava 18+ firstNonNull(first, second)
import static com.google.common.base.MoreObjects.firstNonNull;
if (firstNonNull(bool, false)) {
// DoSomething
false is used as the default for the null-case here.
as your variable bool is pointing to a null, you will always get a NullPointerException, you need to initialize the variable first somewhere with a not null value, and then modify it.
Objects.equals()
There is nothing wrong with the accepted answer by K-ballo. If you prefer a single simple condition and like me you don’t like Yoda conditions, since java 1.7 the answer is
if (Objects.equals(bool, true)) {
or if at the same time you prefer to be really explicit
if (Objects.equals(bool, Boolean.TRUE)) {
Or better: avoid the issue
It’s not recommended to use Boolean objects thereby allowing a Boolean reference to be null in the first place. The risk of a NullPointerException like the one you saw is too great. If you need a kind of tri-state logic, it’s better to define an enum with three values. For example
enum MyTristateBoolean { FALSE, DONT_KNOW, TRUE }
Now we don’t need null at all. The middle constant should probably be named UNKNOWN, UNDEFINED, NOT_EXISTING or something else depending on your exact situation. You may even name it NULL if appropriate. Now depending on taste your comparison becomes one of the following two.
if (myBool.equals(MyTristateBoolean.TRUE)) {
if (myBool == MyTristateBoolean.TRUE) {
The latter works since the compiler guarantees that you will only have one instance of each enum constant. As most of you know == doesn’t work for comparing objects of non-enum type for equality.
In a project I've been trying to familiarise myself with, I ran across a method that looks like this:
public boolean testString(String string){
return string != null && !"".equals(string);
}
What is the value of testing the string for emptiness this way instead of with the variable first? I understand why we see constant-first (Yoda syntax) in C, but is there any reason to do so with method calls in Java?
note: I do understand about NullPointerException, which is not possible in this instance. I'm looking for a value to doing it this way in this case particularly.
In this context it makes little difference, as it already tested for null. Usually you do it this way to make sure you don't call a member on a null-reference (resulting in a NullPointerException), i.e.
"test".equals(myString)
will never throw a null pointer exception whereas
myString.equals("test")
will if myString is null. So basically, the first test makes sure it's a string (not null) AND it's equal to "test".
For two strings it doesn't matter much, but when there is a non-final type involved it can be a micro-optimization.
If the left hand side is a non-overridden concrete type, then the dispatch becomes static.
Consider what the JIT has to do for
Object o;
String s;
o.equals(s)
vs
s.equals(o)
In the first, the JIT has to find the actual equals method used, whereas in the second, it knows that it can only by String.equals.
I adopted the habit of doing
"constant value" == variableName
in other languages, since it means that the code will fail to parse if I mis-type = instead of ==.
And when I learned Java, I kept that order preference.
The usual reason for using "constant string".equals(variable) is that this works properly even if variable is null (unlike variable.equals("constant string")). In your case, however, since you are testing that string != null in a short-circuit boolean test, it's entirely a matter of style (or habit).
If they just did this:
!"".equals(string);
then they're avoiding the possibility of a NullPointerException, which is pretty smart. However, they're checking for null right before this condition, which is technically not necessary.
Is it running any tools like checkstyle? if it is, putting the variable first will result in checkstyle failing. Another reason is that if you put the empty string first it will take away the possibility of getting a null exception if the variable is null because the expression will always evaluate to false. If you had the variable first and the variable was null it will throw an exception.
It is more than a coder preference. If the purpose of the method was only to check that string is not an empty String (without caring whether its a null) then it makes sense to have the constant first to avoid a NullPointerException.
e.g. This method will return the boolean outcome. false in case string is null.
public boolean testString(String string){
return !"".equals(string);
}
while this one may throw a runtime exception if string is null
public boolean testString(String string){
return !string.equals("");
}
No, it is unnatural, and harder to read. It triggers a pause for most readers, and may wastefully consume lots of resources on stackoverlow.com.
(Better use string.isEmtpy() anyway)
There are no fixed rules tho, sometime this is easier to read
if( null != foobar(blahblahblah, blahblahblah, blahblahblah) )
than
if( foobar(blahblahblah, blahblahblah, blahblahblah) != null )
This question can be answered on a number of levels:
What does the example mean?
As other answers have explained, !"".equals(str) tests if str is an non-empty string. In general, the <stringLiteral>.equals(str) idiom is a neat way of testing a string that deals with the null case without an explicit test. (If str is null then the expression evaluates to false.
Is this particular example best practice?
In general no. The !"".equals(str) part deals with the case where str is null, so the preceding null test is redundant.
However, if str was null in the vast majority of cases, this usage would possibly be faster.
What is a better way to do this from a code-style perspective?
return "".equals(str);
or
return str != null && !str.isEmpty();
However, the second approach doesn't work with Java versions prior to 1.6 ... because isEmpty() is a recent API extension.
What is the optimal way to do this?
My gut feeling is that return str != null && !str.isEmpty(); will be fastest. The String.isEmpty() method is implemented as a one-line test, and is small enough that the JIT compiler will inline it. The String.equals(Object) method is a lot more complicated, and too big to be inlined.
Miško Hevery (see his videos on youtube) calls this type of overkill "paranoid programming" :-)
Probably in this video:
http://www.youtube.com/watch?v=wEhu57pih5w
See also here: http://misko.hevery.com/2009/02/09/to-assert-or-not-to-assert/