22

Java 8 introduces Optional to deal with NPE. In practical application,I can‘t understand a problem.

I have the method A

public void doSomethingA(String para) {
    Optional<String> name = Optional.of(para);
    if (name.isPresent()) {
        //do
    }
}

But if para = null, it will throw NPE.

method B

public void doSomethingB(String para) {
    if (para != null) {
        //do
    }
}

if I check para is not null, What's the difference between A and B.

Where is the meaning of Optional.

dai
  • 1,025
  • 2
  • 13
  • 33
  • 2
    Use [Optional.ofNullable()](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ofNullable-T-) instead – ymonad Apr 11 '17 at 07:30

2 Answers2

33

Use Optional.ofNullable if you are unsure whether you have a value or not, but you do not want a NullPointerException to be thrown.

Use Optional.of if you know you have a non-null-value or if it's ok for you if a NullPointerException is thrown otherwise.

Regarding the rest of your question: why null or Optional you may find the following question useful: Optional vs. null. What is the purpose of Optional in Java 8?

Your question may also be related to: Why use Optional.of over Optional.ofNullable?

Community
  • 1
  • 1
Roland
  • 22,259
  • 4
  • 57
  • 84
  • if it's ok for a NullPointerException is thrown, Do I need to use it? – dai Apr 11 '17 at 07:41
  • 1
    it depends on your use case. Most of the time I am dealing with values that I have no control of (they come from legacy systems, etc.) and then I use `ofNullable`. If I have control of the values, I rather prefer `of` as I want to see that `NullPointerException` if someone tries to deliver a `null`-value where I am certainly not expecting any. – Roland Apr 11 '17 at 07:44
  • Thank you for this. But why the hell would you ever wrap a value in optional that you KNOW is non-null? Is this just like a verbose way of forcing java to null-check something that should never be null? – Adam Hughes Aug 10 '22 at 14:35
  • Because of the cases where it might be absent due to a condition or something (try/catch? etc.)... I think the stream methods `findFirst` or `findAny` are good examples for it: if you filter a stream it could be that nothing matches... in that case `findFirst`/`findAny` would return an empty `Optional`, which I personally prefer instead of `null` (also due to the convenience methods that `Optional` offers)... – Roland Aug 15 '22 at 11:34
1

Optional does not prevent from throwing an NPE, It makes it very easy to avoid, but you have to do your part, for example, I would refactor your code to something like this.

     public void doSomethingA(String para) {
           
           Optional<String> optName = Optional.ofNullable(para);
        
           String name = optName.orElse("Unknown");
    //At his point, you are completely sure that name is even given name or "Unknown" 
    //and can do wherever you want without being afraid of throwing a NPE
    
        }

You can use other optional Method like: optName.orElseThrow() to throw and error if your param is null, optName.orElseGet(() -> { return "Unknown" ;}); practically does the same than the example but you can add more logic to get the default value, or many other methods.

luisZavaleta
  • 1,160
  • 11
  • 21