I am working in a project there is a statement like below
if(null == object)
{
//do something
}
is it same as
if(object == null){
// do something
}
Give some example so that both are same or different .
There is no difference in this specific case. Matter of style. The first style is Yoda style of coding usually write to avoid null pointer. But this case, it's the same.
The example from wiki
String myString = null;
if (myString.equals("foobar")) { /* ... */ }
// This causes a NullPointerException in Java
With Yoda conditions:
String myString = null;
if ("foobar".equals(myString)) { /* ... */ }
// This is false, as expected
Note that avoiding NullPointerException is not always an advantage. Covering them may cause other bugs or eat more time to debug your code.
The operator == is symmetric.
x == null is equalent to null == x. But using the first way is more readable and habitually.
There are other ways to check for null value in the object:
1. boolean Objects.nonNull(Object obj) // obj != null
2. T Objects.requireNonNull(T obj) // checks out obj and returns it if it isn't null
Example:
String v = "value";
System.out.println(v == null ? null : v);
System.out.println(null == v ? null : v);
Output:
value
value
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