In both the cases, we have to put the if conditions, so, what is the advantage of optional actually? There, we used to check if obj is not null and here we call ifPresent method, so,what is the difference?
One of the big advantages of Optionals is that it allows to avoid NullPointerExceptions in a more elegant way. For example, in case a variable has a value of null, you can specify an alternative action, e.g. returning a default value.
I am also just learning about Optionals and I found this page very useful.
Beginning programmer - self-taught
Oracle Certified Associate Java SE 8
The difference is that Optional forces the programmer to think about it, because you can't use an Optional<Foo> where a Foo is expected, while you CAN use null where a Foo is expected. Additionally, Optional provides methods to perform transformations and actions optionally, i.e. only when there is a value present, without calling isPresent().
Vaibhav Gargs wrote:. . . . Please let me know if I am missing anything.
Yes, you are missing the orElse()/orElseSomething() methods. Those methods allow you to return some sort of other value if the Optional is empty. Did you read the Baeldung link or Urma's article? If you have any possible risk of a null, writeAnother advantage of the orElseGet() method is that in the likely instance of the Optional not being empty, the code used as an argument to orElseGet() isn't executed, which may cause faster execution.
Avoid the of() and get() methods if possible, because they will throw an exception immediately if presented with a null.
What's that smell? I think this tiny ad may have stepped in something.