Java 8 Optional, why of and ofNullable











up vote
7
down vote

favorite
2












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



The question is, what is the reason for having both types to let us choose:



Optional.of(T value)     <-----non-null value, null value will throw NPE
Optional.ofNullable(T value) <----- nullable value


Because what I expect is, when I use



Optional.of(nullValue);


It won't throw NullPointerException





Enhanced my question after some replies:



Why would people opt for Optional instead of normal if-else method for null checking?










share|improve this question
























  • You may want to return a value wrapped with Optional. In this case, you can use Optional.of(value); .
    – Emre Savcı
    48 mins ago










  • Two out of three answers provided by people call NullPointer. How apt for this question....
    – Thilo
    32 mins ago










  • Because they didn't think it through, that most normal expectation is that of(value) should check for null. This design choice is as absurd as the java.util.Date type.
    – coladict
    26 mins ago















up vote
7
down vote

favorite
2












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



The question is, what is the reason for having both types to let us choose:



Optional.of(T value)     <-----non-null value, null value will throw NPE
Optional.ofNullable(T value) <----- nullable value


Because what I expect is, when I use



Optional.of(nullValue);


It won't throw NullPointerException





Enhanced my question after some replies:



Why would people opt for Optional instead of normal if-else method for null checking?










share|improve this question
























  • You may want to return a value wrapped with Optional. In this case, you can use Optional.of(value); .
    – Emre Savcı
    48 mins ago










  • Two out of three answers provided by people call NullPointer. How apt for this question....
    – Thilo
    32 mins ago










  • Because they didn't think it through, that most normal expectation is that of(value) should check for null. This design choice is as absurd as the java.util.Date type.
    – coladict
    26 mins ago













up vote
7
down vote

favorite
2









up vote
7
down vote

favorite
2






2





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



The question is, what is the reason for having both types to let us choose:



Optional.of(T value)     <-----non-null value, null value will throw NPE
Optional.ofNullable(T value) <----- nullable value


Because what I expect is, when I use



Optional.of(nullValue);


It won't throw NullPointerException





Enhanced my question after some replies:



Why would people opt for Optional instead of normal if-else method for null checking?










share|improve this question















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



The question is, what is the reason for having both types to let us choose:



Optional.of(T value)     <-----non-null value, null value will throw NPE
Optional.ofNullable(T value) <----- nullable value


Because what I expect is, when I use



Optional.of(nullValue);


It won't throw NullPointerException





Enhanced my question after some replies:



Why would people opt for Optional instead of normal if-else method for null checking?







java java-8 optional






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 37 mins ago

























asked 1 hour ago









hades

74411030




74411030












  • You may want to return a value wrapped with Optional. In this case, you can use Optional.of(value); .
    – Emre Savcı
    48 mins ago










  • Two out of three answers provided by people call NullPointer. How apt for this question....
    – Thilo
    32 mins ago










  • Because they didn't think it through, that most normal expectation is that of(value) should check for null. This design choice is as absurd as the java.util.Date type.
    – coladict
    26 mins ago


















  • You may want to return a value wrapped with Optional. In this case, you can use Optional.of(value); .
    – Emre Savcı
    48 mins ago










  • Two out of three answers provided by people call NullPointer. How apt for this question....
    – Thilo
    32 mins ago










  • Because they didn't think it through, that most normal expectation is that of(value) should check for null. This design choice is as absurd as the java.util.Date type.
    – coladict
    26 mins ago
















You may want to return a value wrapped with Optional. In this case, you can use Optional.of(value); .
– Emre Savcı
48 mins ago




You may want to return a value wrapped with Optional. In this case, you can use Optional.of(value); .
– Emre Savcı
48 mins ago












Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
32 mins ago




Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
32 mins ago












Because they didn't think it through, that most normal expectation is that of(value) should check for null. This design choice is as absurd as the java.util.Date type.
– coladict
26 mins ago




Because they didn't think it through, that most normal expectation is that of(value) should check for null. This design choice is as absurd as the java.util.Date type.
– coladict
26 mins ago












3 Answers
3






active

oldest

votes

















up vote
4
down vote













The javadoc of Optional.of reads that explicitly :



@throws NullPointerException if value is null


and that is where the requirement of handling the cases as expected by you comes into picture with the use of Optional.ofNullable which is a small block of code as :



public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value); // 'Optional.of'
}


That said, the decision of choosing one over the other would still reside with the application design as if your value could possibly be null or not.





On your expectation part, that was not what the Optional was actually intended for. The API note clarifies this further (formatting mine):




Optional is primarily intended for use as a method return type where
there is a clear need to represent "no result," and where using
null is likely to cause error. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.







share|improve this answer






























    up vote
    3
    down vote














    the purpose of Optional is to tackle NullPointerException exception




    Yes, it is, but at usage time not at creation.



    So when you receive an Optional from a method then you can avoid NPE by using Optional.ifPresent, Optional.orElse,Optional.orElseGet and Optional.orElseThrow methods.



    But this is not the case when you're creating an Optional. Since it's your own method you have to know whether the object is nullable or not.






    The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.



    Stuart Marks




    Please read this post for more detailed explanation.






    share|improve this answer




























      up vote
      1
      down vote













      I think its quite simple and Clear with Javadoc:



      Optional.of(T value) is used when you are sure that there is never a null value and incase null value occurs than program throws NullPointerException and consider as bug.



      Optional.ofNullable(T value) is used when you know that there can be a null value and in case of it your program should behave normally.





      --Why would people opt for Optional instead of normal if-else method for null checking?---



      Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications. Like Collections and arrays, it is also a Container to hold at most one value.



      Source:https://www.mkyong.com/java8/java-8-optional-in-depth/






      share|improve this answer























      • No more NullPointerException at run-time.. Well, due to Optional.of there is still a chance of human factor to produce NPEs at runtime.
        – Andrii Abramov
        29 mins ago











      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53810048%2fjava-8-optional-why-of-and-ofnullable%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      4
      down vote













      The javadoc of Optional.of reads that explicitly :



      @throws NullPointerException if value is null


      and that is where the requirement of handling the cases as expected by you comes into picture with the use of Optional.ofNullable which is a small block of code as :



      public static <T> Optional<T> ofNullable(T value) {
      return value == null ? empty() : of(value); // 'Optional.of'
      }


      That said, the decision of choosing one over the other would still reside with the application design as if your value could possibly be null or not.





      On your expectation part, that was not what the Optional was actually intended for. The API note clarifies this further (formatting mine):




      Optional is primarily intended for use as a method return type where
      there is a clear need to represent "no result," and where using
      null is likely to cause error. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.







      share|improve this answer



























        up vote
        4
        down vote













        The javadoc of Optional.of reads that explicitly :



        @throws NullPointerException if value is null


        and that is where the requirement of handling the cases as expected by you comes into picture with the use of Optional.ofNullable which is a small block of code as :



        public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value); // 'Optional.of'
        }


        That said, the decision of choosing one over the other would still reside with the application design as if your value could possibly be null or not.





        On your expectation part, that was not what the Optional was actually intended for. The API note clarifies this further (formatting mine):




        Optional is primarily intended for use as a method return type where
        there is a clear need to represent "no result," and where using
        null is likely to cause error. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.







        share|improve this answer

























          up vote
          4
          down vote










          up vote
          4
          down vote









          The javadoc of Optional.of reads that explicitly :



          @throws NullPointerException if value is null


          and that is where the requirement of handling the cases as expected by you comes into picture with the use of Optional.ofNullable which is a small block of code as :



          public static <T> Optional<T> ofNullable(T value) {
          return value == null ? empty() : of(value); // 'Optional.of'
          }


          That said, the decision of choosing one over the other would still reside with the application design as if your value could possibly be null or not.





          On your expectation part, that was not what the Optional was actually intended for. The API note clarifies this further (formatting mine):




          Optional is primarily intended for use as a method return type where
          there is a clear need to represent "no result," and where using
          null is likely to cause error. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.







          share|improve this answer














          The javadoc of Optional.of reads that explicitly :



          @throws NullPointerException if value is null


          and that is where the requirement of handling the cases as expected by you comes into picture with the use of Optional.ofNullable which is a small block of code as :



          public static <T> Optional<T> ofNullable(T value) {
          return value == null ? empty() : of(value); // 'Optional.of'
          }


          That said, the decision of choosing one over the other would still reside with the application design as if your value could possibly be null or not.





          On your expectation part, that was not what the Optional was actually intended for. The API note clarifies this further (formatting mine):




          Optional is primarily intended for use as a method return type where
          there is a clear need to represent "no result," and where using
          null is likely to cause error. A variable whose type is Optional should never itself be null; it should always point to an Optional instance.








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 29 mins ago

























          answered 57 mins ago









          nullpointer

          38.8k1074147




          38.8k1074147
























              up vote
              3
              down vote














              the purpose of Optional is to tackle NullPointerException exception




              Yes, it is, but at usage time not at creation.



              So when you receive an Optional from a method then you can avoid NPE by using Optional.ifPresent, Optional.orElse,Optional.orElseGet and Optional.orElseThrow methods.



              But this is not the case when you're creating an Optional. Since it's your own method you have to know whether the object is nullable or not.






              The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.



              Stuart Marks




              Please read this post for more detailed explanation.






              share|improve this answer

























                up vote
                3
                down vote














                the purpose of Optional is to tackle NullPointerException exception




                Yes, it is, but at usage time not at creation.



                So when you receive an Optional from a method then you can avoid NPE by using Optional.ifPresent, Optional.orElse,Optional.orElseGet and Optional.orElseThrow methods.



                But this is not the case when you're creating an Optional. Since it's your own method you have to know whether the object is nullable or not.






                The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.



                Stuart Marks




                Please read this post for more detailed explanation.






                share|improve this answer























                  up vote
                  3
                  down vote










                  up vote
                  3
                  down vote










                  the purpose of Optional is to tackle NullPointerException exception




                  Yes, it is, but at usage time not at creation.



                  So when you receive an Optional from a method then you can avoid NPE by using Optional.ifPresent, Optional.orElse,Optional.orElseGet and Optional.orElseThrow methods.



                  But this is not the case when you're creating an Optional. Since it's your own method you have to know whether the object is nullable or not.






                  The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.



                  Stuart Marks




                  Please read this post for more detailed explanation.






                  share|improve this answer













                  the purpose of Optional is to tackle NullPointerException exception




                  Yes, it is, but at usage time not at creation.



                  So when you receive an Optional from a method then you can avoid NPE by using Optional.ifPresent, Optional.orElse,Optional.orElseGet and Optional.orElseThrow methods.



                  But this is not the case when you're creating an Optional. Since it's your own method you have to know whether the object is nullable or not.






                  The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.



                  Stuart Marks




                  Please read this post for more detailed explanation.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 46 mins ago









                  ETO

                  1,203217




                  1,203217






















                      up vote
                      1
                      down vote













                      I think its quite simple and Clear with Javadoc:



                      Optional.of(T value) is used when you are sure that there is never a null value and incase null value occurs than program throws NullPointerException and consider as bug.



                      Optional.ofNullable(T value) is used when you know that there can be a null value and in case of it your program should behave normally.





                      --Why would people opt for Optional instead of normal if-else method for null checking?---



                      Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications. Like Collections and arrays, it is also a Container to hold at most one value.



                      Source:https://www.mkyong.com/java8/java-8-optional-in-depth/






                      share|improve this answer























                      • No more NullPointerException at run-time.. Well, due to Optional.of there is still a chance of human factor to produce NPEs at runtime.
                        – Andrii Abramov
                        29 mins ago















                      up vote
                      1
                      down vote













                      I think its quite simple and Clear with Javadoc:



                      Optional.of(T value) is used when you are sure that there is never a null value and incase null value occurs than program throws NullPointerException and consider as bug.



                      Optional.ofNullable(T value) is used when you know that there can be a null value and in case of it your program should behave normally.





                      --Why would people opt for Optional instead of normal if-else method for null checking?---



                      Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications. Like Collections and arrays, it is also a Container to hold at most one value.



                      Source:https://www.mkyong.com/java8/java-8-optional-in-depth/






                      share|improve this answer























                      • No more NullPointerException at run-time.. Well, due to Optional.of there is still a chance of human factor to produce NPEs at runtime.
                        – Andrii Abramov
                        29 mins ago













                      up vote
                      1
                      down vote










                      up vote
                      1
                      down vote









                      I think its quite simple and Clear with Javadoc:



                      Optional.of(T value) is used when you are sure that there is never a null value and incase null value occurs than program throws NullPointerException and consider as bug.



                      Optional.ofNullable(T value) is used when you know that there can be a null value and in case of it your program should behave normally.





                      --Why would people opt for Optional instead of normal if-else method for null checking?---



                      Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications. Like Collections and arrays, it is also a Container to hold at most one value.



                      Source:https://www.mkyong.com/java8/java-8-optional-in-depth/






                      share|improve this answer














                      I think its quite simple and Clear with Javadoc:



                      Optional.of(T value) is used when you are sure that there is never a null value and incase null value occurs than program throws NullPointerException and consider as bug.



                      Optional.ofNullable(T value) is used when you know that there can be a null value and in case of it your program should behave normally.





                      --Why would people opt for Optional instead of normal if-else method for null checking?---



                      Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications. Like Collections and arrays, it is also a Container to hold at most one value.



                      Source:https://www.mkyong.com/java8/java-8-optional-in-depth/







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 22 mins ago

























                      answered 51 mins ago









                      NullPointer

                      4,24921130




                      4,24921130












                      • No more NullPointerException at run-time.. Well, due to Optional.of there is still a chance of human factor to produce NPEs at runtime.
                        – Andrii Abramov
                        29 mins ago


















                      • No more NullPointerException at run-time.. Well, due to Optional.of there is still a chance of human factor to produce NPEs at runtime.
                        – Andrii Abramov
                        29 mins ago
















                      No more NullPointerException at run-time.. Well, due to Optional.of there is still a chance of human factor to produce NPEs at runtime.
                      – Andrii Abramov
                      29 mins ago




                      No more NullPointerException at run-time.. Well, due to Optional.of there is still a chance of human factor to produce NPEs at runtime.
                      – Andrii Abramov
                      29 mins ago


















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53810048%2fjava-8-optional-why-of-and-ofnullable%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Plaza Victoria

                      Puebla de Zaragoza

                      Musa