The effect of position in comparing an object with a null reference - java

I would like to know the difference(w.r.t code size and/or performance) of the following snippets:
if(null == someObject.getSomeProperty()){
...
}
vs
if(someObject.getSomeProperty() == null ){
...
}

In my opinion performance and generated bytecode size should be the same. The first pointed style ( null == value) comes from C/C++ where anything different from 0 was considered true while something equal to 0 was false. To avoid an issue it is approached in this way: null == value, then you made sure that this is a condition.
As java has a boolean type, it is useless to approach a condition this way, more it is considered a bad practice. It is referred to as Yoda Condition.
A sole reason where this approach should be used when verified against a literal value:
if("someValue".equals(input)) {
// do something
}
if (BigDecimal.ONE.equals(input)) {
// do something
}
writing the code in the natural way would throw a NullPointerException exception if the input is null hence the condition should be written more defensive like:
if (input != null && input.equals("someValue")) {
// do something
}

There's no difference in the performance. Furthermore in modern languages that shouldn't be any of your concern since the compiler would do the optimization for you.
The only reason for writing these so-called "yoda conditions" (having the compare statement in the 'wrong' order) is comparing specific values to values that might be null when using equals, example:
if("blue".equals(sky.getColor())){
//...
}
because if you wanted to write it the intuitive way, you'd have to perfom a manual null check:
if(sky.getColor() != null && sky.getColor().equals("blue")){
//...
}

Related

Best way to check if a reference is null in Java

I was wondring what the best way to check if we have a valid reference in java. I know that this syntax works, but its a mouth full.
if (myObj == null) {
// Do something knowing we have an object
}
I'm coming from some other languages that allow you to just check a pointer like in c++.
char* prt = null;
if (ptr) {
// We know we have a valid c-string
}
Is there any equivocate or similar syntax in java? I would be okay using compiler extensions or a preprocessor.
Follow up before. Before some one jumps in a starts talking about why I should just use the java syntax because you can forget an = sign please don't.
if (myObj = null)
Will be caught by the compiler/linter.
Alas Java does not have an implicit conversion of the analogue of a nullptr_t or a pointer type to bool, so you have to use the somewhat more long-winded notation
if (myObj == null)
whereas in C++ we can write
if (myObj)
In this respect, Java is less terse, and arguably clearer.
There is no shortcut syntax for dealing with null checks in Java, not even a null coalesce or null propagation operators available in other languages. There are no user-defined conversion operators either, so you wouldn't be able to use the C++ idiom that lets you write loops on expressions returning objects, e.g. while (cin >> x) { ... }.
However, a powerful alternative exists in Java 8 to avoid null checks altogether: wrap your nullable objects in Optional<T>, and use its methods to hide null checks.
Here is a short example:
String s = "Hello";
Optional<String> os = Optional.ofNullable(s);
os.ifPresent(x -> { System.out.println(x); });
The above prints "Hello". If you set s to null, the code would print nothing.
Oracle's article on using Optional<T>.
if(x == null) {
doSomething();
}
... is the general idiom in Java. Java's designers made the decision not to allow treating non-boolean variables as implicit "truthy" values.
Another common idiom is to use x == null in a ternary statement:
return x == null ? "not found" : x;
Or to use a standard method to throw an exception early on nulls:
Objects.requireNonNull(x);
More generally, try to adopt a programming style in which you never expect null to be passed, and therefore don't have to code for the possibility.
On non-public APIs, since you never pass a null, you never need to test for null (if a NullPointerException occurs, whoever passed the null can take responsibility for the mess themselves).
In public APIs, it may be a courtesy to the caller to validate non-nulls at the point they are passed, but it's by no means essential in every case.
A reasonable goal is to always expect inputs to be non-null, and to never return a null (since Java 8, use Optional instead if necessary, or adopt the Null Object Pattern).

Which is better way of having a null check?

I came across these two ways of having a null check for a string object.
Given a string object String str = "example";
If(str.someMethod() != null ) or
If (null != str.someMethod())
Why do we prefer the 2nd one ?
What is the exact reason behind this, is it related to performance ?
In your example, it makes absolutely no difference which you do (other than style), because the reason for Yoda checks is to avoid accidentally doing an assignment (but keep reading for why this doesn't matter in Java), and you can't assign to the result of calling a method.
One of the nice things about Java is that even if you were testing str, e.g.:
if (str == null)
vs.
if (null == str)
there would still be no difference, whereas in some of the languages with syntax derived from B (such as C, C++, D, JavaScript, etc.), people do the second (a "Yoda test") to minimize the odds of this bug:
if (str = null) // Not an issue in Java
In C or JavaScript, for instance, that would assign null to str, then evaluate the result, coerce it to boolean, and not branch. But in Java, that's a syntax error the compiler tells you about.
Java doesn't do that kind of boolean conversion, so the only reason for using Yoda checks in Java is if you're testing booleans, e.c.
boolean flag;
// ...
if (flag == false)
There, you might conceivably do this by accident:
if (flag = false)
But since using == and != with booleans is completely unnecessary (you'd just use if (flag) or if (!flag)), in the real world you don't need Yoda checks with Java at all.
That doesn't mean people don't still use them, as a matter of their own personal style. There's just no objective reason to, in Java.
It makes no difference performance-wise, however the Yoda programming pattern have some advantages when it comes to the world of programming skills.
In your example it would not matter as both cases would throw a NullPointerException (since you're invoking someMethod` of a null instance reference).
However, say that you wanted to check if str is null. In the first case, you'd write if (str == null) and in the second if (null == str). Both are the same. Now say that you have accidently used = instead of ==. In Java, it would not matter as the compiler wouldn't let you as the expression doesn't evalute to a boolean value. But other languages let you do that, more specifically languages that are compiler-free and only use an interperter. In that case, if you write if (str = null) you'll be assigning null to string and overriding its' current value, which would result in buggy behavior and you chasing after your tail for quite some time. However, if you'd write if (null = str) you'll get an error saying you cannot assign a value to null and thus save yourself a lot of time and effort. Again, this is not relevant to JAVA.
An example which might be relevant for Java, is the use of method invocation on constant values. For example, if (str.equals("constantString"). If str is null you'll get a NullPointerException. However, if you use a Yoad pattern and write if ("constantString".equals(str)) you'll get false as ConstantString does not equal null. This of course is only relevant for comparison, and not say contains etc.

null == foo versus foo == null [duplicate]

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 ==

Check if null Boolean is true results in exception

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.

What is the value of the test !"".equals(someString)

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/

Categories