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 ?
Objects. requireNonNull is a helpful method to spot NullPointerExceptions effectively while developing.
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.
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().
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.
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());
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