null == foo versus foo == null [duplicate] - java

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

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.

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

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")){
//...
}

Is there any reason for "Boolean.TRUE.equals(x)" in Java?

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?

Coding standard for null checking [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
What's the comparison difference?
Null check in Java
Most of the developers have the habit of writing the null checking with null in the left hand side.like,
if(null == someVariable)
Does this help any way? According to me this is affecting the readability of the code.
No, it has no purpose whatsoever in Java.
In C and some of its related languages, it was sometimes used to avoid making this mistake:
if (someVariable = null)
Note the = rather than ==, the author has inadvertently assigned null to someVariable rather than checking for null. But that will result in a compiler error in Java.
Even in C, any modern compiler will have an option to treat the if (someVariable = null) as a warning (or even an error).
Stylistically, I agree with you — I wouldn't say "if 21 you are, I will serve you a drink" (unless I'd already had a couple several and was doing my Yoda impersonation). Mind you, that's English; for all I know it would make perfect sense in other languages, in which case it would be perfectly reasonable style for speakers of those languages.
It used to help in 'the olden days' when C compilers would not complain about missing an =, when wanting ==:
// OOps forgot an equals, and got assignment
if (someVariable = null)
{
}
Any modern C#/Java/C++/C compiler should raise a warning (and hopefully an error).
Personally, I find
if (someVariable == null)
{
}
more readable than starting with the null.
In your case, I don't see any merit in doing that way. But I prefer the following...
if("a string".equals(strVariable))
{
}
over this..
if(strVariable != null && strVariable.equals("a string"))
{
}

Categories