Java 8 Optional. Why of and ofNullable?

后端 未结 8 1515
旧时难觅i
旧时难觅i 2021-02-07 01:01

I have a question regarding Java 8\'s Optional, the purpose of which is to tackle NullPointerException exceptions.

The question is, what is the reason for h

8条回答
  •  星月不相逢
    2021-02-07 01:56

    Code example: Optional.of() VS Optional.ofNullable()

    @Test
    public void TestOptional() {
    
        String message = "Hello World!";
        System.out.println("message -> " + message + "\n");
    
        Optional genderOptional = Optional.of(message);
        System.out.println("Optional.of(message) -> " + genderOptional);
        System.out.println("Optional.of(message).get() -> " + genderOptional.get());
        try {
            Optional.of(null);
        } catch (java.lang.NullPointerException e) {
            System.out.println("Optional.of(null) -> java.lang.NullPointerException \n");
        }
    
        System.out.println("Optional.empty() -> " + Optional.empty() + "\n");
    
        System.out.println("Optional.ofNullable(null) -> " + Optional.ofNullable(null));
        System.out.println("Optional.ofNullable(message) -> " + Optional.ofNullable(message));
        System.out.println("Optional.ofNullable(message).get() -> " + Optional.ofNullable(message).get());
    
    }
    

    Output:

    message -> Hello World!
    
    Optional.of(message) -> Optional[Hello World!]
    Optional.of(message).get() -> Hello World!
    Optional.of(null) -> java.lang.NullPointerException 
    
    Optional.empty() -> Optional.empty
    
    Optional.ofNullable(null) -> Optional.empty
    Optional.ofNullable(message) -> Optional[Hello World!]
    Optional.ofNullable(message).get() -> Hello World!
    

提交回复
热议问题