When to use "java.util.Objects. *"?

I went through Java 7 and they talked about java.util.Objects .

What I don't understand is what the betwee functional difference means

 java.util.Objects.toString(foo) vs foo == null ? "":foo.toString() 

All I could see further was null check and functional notation instead of OOP .

What am I missing?

+7
java oop java-7
source share
2 answers

The main advantage of java.util.Objects.toString() is that you can easily use it by the return value, which can be null and not need to create a new local variable (or, even worse, call the function twice).

Comparison

 Foo f = getFoo(); String foo = (f==null) ? "null" : f.toString(); 

or worthy embellishment and error causing

 String foo = (getFoo()==null) ? "null" : getFoo().toString() 

to version Objects.toString based

 String foo = Objects.toString(getFoo()); 
+8
source share

Calling Objects.toString(foo) just eliminates the need for you to perform null checks and means that you can use it directly when returning a method value (e.g. Objects.toString(getPossibleNullObject()) ) without first storing it in a variable (or call method twice).

Note that the method does return:

the result of calling toString for a non-empty argument and "null" for the null argument

therefore it is actually equivalent to:

 foo == null ? "null" : foo.toString(); 

if you want "" for a null value, you can use an overload that passes the return value nullDefault Objects.toString(foo, "")

+5
source share

All Articles