Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it correct to compare like if(null == object) or if(object == null) in java [closed]

Tags:

java

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 .

like image 814
SarthAk Avatar asked Apr 26 '26 01:04

SarthAk


2 Answers

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.

like image 110
Suresh Atta Avatar answered Apr 27 '26 15:04

Suresh Atta


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
like image 35
Andrew Tobilko Avatar answered Apr 27 '26 13:04

Andrew Tobilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!