Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

oop

java-7

I was going through Java 7 features and they talked about java.util.Objects class.

What I am failing to understand is what is the functional difference betwee

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

All I could see extra was a null check and functional notation instead of OOP style.

What am I missing ?

like image 934
Ajeet Ganga Avatar asked Jul 03 '15 06:07

Ajeet Ganga


People also ask

Is it good to use objects requireNonNull?

Objects. requireNonNull is a helpful method to spot NullPointerExceptions effectively while developing.

Why do we use object class in Java?

The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java. The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.

What is objects hash for?

Objects. hashCode() is a null-safe method we can use to get the hashcode of an object. Hashcodes are necessary for hash tables and the proper implementation of equals().

What is objects nonNull in Java?

The nonNull method is a static method of the Objects class in Java that checks whether the input object reference supplied to it is non-null or not. If the passed object is non-null, then the method returns true. If the passed object is null , then the method returns false.


1 Answers

The main advantage of java.util.Objects.toString() is that you can easily use it on a return value that might be null, rather than needing to create a new local variable (or worse calling the function twice).

Compare

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

or the cringe-worthy and bug inducing

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

to the Objects.toString based version

String foo = Objects.toString(getFoo());
like image 122
Michael Anderson Avatar answered Nov 05 '22 07:11

Michael Anderson