Java 8 Optional, why of and ofNullable
up vote
7
down vote
favorite
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
add a comment |
up vote
7
down vote
favorite
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
You may want to return a value wrapped with Optional. In this case, you can useOptional.of(value);
.
– Emre Savcı
34 mins ago
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
18 mins ago
Because they didn't think it through, that most normal expectation is thatof(value)
should check for null. This design choice is as absurd as thejava.util.Date
type.
– coladict
11 mins ago
add a comment |
up vote
7
down vote
favorite
up vote
7
down vote
favorite
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
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
java java-8 optional
edited 22 mins ago
asked 46 mins ago
hades
74411030
74411030
You may want to return a value wrapped with Optional. In this case, you can useOptional.of(value);
.
– Emre Savcı
34 mins ago
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
18 mins ago
Because they didn't think it through, that most normal expectation is thatof(value)
should check for null. This design choice is as absurd as thejava.util.Date
type.
– coladict
11 mins ago
add a comment |
You may want to return a value wrapped with Optional. In this case, you can useOptional.of(value);
.
– Emre Savcı
34 mins ago
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
18 mins ago
Because they didn't think it through, that most normal expectation is thatof(value)
should check for null. This design choice is as absurd as thejava.util.Date
type.
– coladict
11 mins ago
You may want to return a value wrapped with Optional. In this case, you can use
Optional.of(value);
.– Emre Savcı
34 mins ago
You may want to return a value wrapped with Optional. In this case, you can use
Optional.of(value);
.– Emre Savcı
34 mins ago
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
18 mins ago
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
18 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
11 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
11 mins ago
add a comment |
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 isOptional
should never itself benull
; it should always point to anOptional
instance.
add a comment |
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.
add a comment |
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/
No more NullPointerException at run-time.
. Well, due toOptional.of
there is still a chance of human factor to produce NPEs at runtime.
– Andrii Abramov
15 mins ago
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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 isOptional
should never itself benull
; it should always point to anOptional
instance.
add a comment |
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 isOptional
should never itself benull
; it should always point to anOptional
instance.
add a comment |
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 isOptional
should never itself benull
; it should always point to anOptional
instance.
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 isOptional
should never itself benull
; it should always point to anOptional
instance.
edited 15 mins ago
answered 43 mins ago
nullpointer
38.8k1074147
38.8k1074147
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered 32 mins ago
ETO
1,203217
1,203217
add a comment |
add a comment |
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/
No more NullPointerException at run-time.
. Well, due toOptional.of
there is still a chance of human factor to produce NPEs at runtime.
– Andrii Abramov
15 mins ago
add a comment |
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/
No more NullPointerException at run-time.
. Well, due toOptional.of
there is still a chance of human factor to produce NPEs at runtime.
– Andrii Abramov
15 mins ago
add a comment |
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/
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/
edited 7 mins ago
answered 37 mins ago
NullPointer
4,24921130
4,24921130
No more NullPointerException at run-time.
. Well, due toOptional.of
there is still a chance of human factor to produce NPEs at runtime.
– Andrii Abramov
15 mins ago
add a comment |
No more NullPointerException at run-time.
. Well, due toOptional.of
there is still a chance of human factor to produce NPEs at runtime.
– Andrii Abramov
15 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
15 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
15 mins ago
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
You may want to return a value wrapped with Optional. In this case, you can use
Optional.of(value);
.– Emre Savcı
34 mins ago
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
18 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 thejava.util.Date
type.– coladict
11 mins ago