Java 8 Optional. Why of and ofNullable? [duplicate]
This question already has an answer here:
Why use Optional.of over Optional.ofNullable?
3 answers
Uses for Optional
13 answers
Is there a real reason to use Optional.of()?
8 answers
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 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 a NullPointerException.
Expanded my question after some replies:
Why would people opt for Optional instead of normal if-else for null checking?
java java-8 optional
marked as duplicate by Roland, Boann, Daniel Pryden
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 17 at 14:02
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
|
show 6 more comments
This question already has an answer here:
Why use Optional.of over Optional.ofNullable?
3 answers
Uses for Optional
13 answers
Is there a real reason to use Optional.of()?
8 answers
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 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 a NullPointerException.
Expanded my question after some replies:
Why would people opt for Optional instead of normal if-else for null checking?
java java-8 optional
marked as duplicate by Roland, Boann, Daniel Pryden
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 17 at 14:02
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
1
You may want to return a value wrapped with Optional. In this case, you can useOptional.of(value);.
– Emre Savcı
Dec 17 at 6:51
3
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
Dec 17 at 7:07
7
Because, as others have said in answers,Optionalis designed to reduce NPEs at the method caller level, not necessarily at the method implementation level.Optional.ofis for when one knows the value is notnull(and an error should be thrown if it is),Optional.emptyis for when one knows the value isnull, andOptional.ofNullableis for when one is not sure if the value isnullor not.
– Slaw
Dec 17 at 7:58
2
Biggest question for me is why the chose the naming that way. I would use.of()for nullable values and then makeofNotNull()for non null values, as this latter is way less used.
– Robert Niestroj
Dec 17 at 7:59
2
@JollyJoker In cases where the logic of the (Optionalreturning) method deems the result has been found and is not, or should not be,null. One example would be "short-circuiting" a loop when a match is found by returningOptional.of(matchedItem). If no match was found the loop would complete and the method would returnOptional.empty. However, there are (perhaps more frequent, perhaps not) cases where even the method cannot know if the result isnullor not and must useOptional.ofNullablewhen returning.
– Slaw
Dec 17 at 9:10
|
show 6 more comments
This question already has an answer here:
Why use Optional.of over Optional.ofNullable?
3 answers
Uses for Optional
13 answers
Is there a real reason to use Optional.of()?
8 answers
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 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 a NullPointerException.
Expanded my question after some replies:
Why would people opt for Optional instead of normal if-else for null checking?
java java-8 optional
This question already has an answer here:
Why use Optional.of over Optional.ofNullable?
3 answers
Uses for Optional
13 answers
Is there a real reason to use Optional.of()?
8 answers
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 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 a NullPointerException.
Expanded my question after some replies:
Why would people opt for Optional instead of normal if-else for null checking?
This question already has an answer here:
Why use Optional.of over Optional.ofNullable?
3 answers
Uses for Optional
13 answers
Is there a real reason to use Optional.of()?
8 answers
java java-8 optional
java java-8 optional
edited Dec 17 at 13:37
Boann
36.7k1287121
36.7k1287121
asked Dec 17 at 6:38
hades
81211132
81211132
marked as duplicate by Roland, Boann, Daniel Pryden
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 17 at 14:02
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by Roland, Boann, Daniel Pryden
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Dec 17 at 14:02
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
1
You may want to return a value wrapped with Optional. In this case, you can useOptional.of(value);.
– Emre Savcı
Dec 17 at 6:51
3
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
Dec 17 at 7:07
7
Because, as others have said in answers,Optionalis designed to reduce NPEs at the method caller level, not necessarily at the method implementation level.Optional.ofis for when one knows the value is notnull(and an error should be thrown if it is),Optional.emptyis for when one knows the value isnull, andOptional.ofNullableis for when one is not sure if the value isnullor not.
– Slaw
Dec 17 at 7:58
2
Biggest question for me is why the chose the naming that way. I would use.of()for nullable values and then makeofNotNull()for non null values, as this latter is way less used.
– Robert Niestroj
Dec 17 at 7:59
2
@JollyJoker In cases where the logic of the (Optionalreturning) method deems the result has been found and is not, or should not be,null. One example would be "short-circuiting" a loop when a match is found by returningOptional.of(matchedItem). If no match was found the loop would complete and the method would returnOptional.empty. However, there are (perhaps more frequent, perhaps not) cases where even the method cannot know if the result isnullor not and must useOptional.ofNullablewhen returning.
– Slaw
Dec 17 at 9:10
|
show 6 more comments
1
You may want to return a value wrapped with Optional. In this case, you can useOptional.of(value);.
– Emre Savcı
Dec 17 at 6:51
3
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
Dec 17 at 7:07
7
Because, as others have said in answers,Optionalis designed to reduce NPEs at the method caller level, not necessarily at the method implementation level.Optional.ofis for when one knows the value is notnull(and an error should be thrown if it is),Optional.emptyis for when one knows the value isnull, andOptional.ofNullableis for when one is not sure if the value isnullor not.
– Slaw
Dec 17 at 7:58
2
Biggest question for me is why the chose the naming that way. I would use.of()for nullable values and then makeofNotNull()for non null values, as this latter is way less used.
– Robert Niestroj
Dec 17 at 7:59
2
@JollyJoker In cases where the logic of the (Optionalreturning) method deems the result has been found and is not, or should not be,null. One example would be "short-circuiting" a loop when a match is found by returningOptional.of(matchedItem). If no match was found the loop would complete and the method would returnOptional.empty. However, there are (perhaps more frequent, perhaps not) cases where even the method cannot know if the result isnullor not and must useOptional.ofNullablewhen returning.
– Slaw
Dec 17 at 9:10
1
1
You may want to return a value wrapped with Optional. In this case, you can use
Optional.of(value); .– Emre Savcı
Dec 17 at 6:51
You may want to return a value wrapped with Optional. In this case, you can use
Optional.of(value); .– Emre Savcı
Dec 17 at 6:51
3
3
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
Dec 17 at 7:07
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
Dec 17 at 7:07
7
7
Because, as others have said in answers,
Optional is designed to reduce NPEs at the method caller level, not necessarily at the method implementation level. Optional.of is for when one knows the value is not null (and an error should be thrown if it is), Optional.empty is for when one knows the value is null, and Optional.ofNullable is for when one is not sure if the value is null or not.– Slaw
Dec 17 at 7:58
Because, as others have said in answers,
Optional is designed to reduce NPEs at the method caller level, not necessarily at the method implementation level. Optional.of is for when one knows the value is not null (and an error should be thrown if it is), Optional.empty is for when one knows the value is null, and Optional.ofNullable is for when one is not sure if the value is null or not.– Slaw
Dec 17 at 7:58
2
2
Biggest question for me is why the chose the naming that way. I would use
.of() for nullable values and then make ofNotNull() for non null values, as this latter is way less used.– Robert Niestroj
Dec 17 at 7:59
Biggest question for me is why the chose the naming that way. I would use
.of() for nullable values and then make ofNotNull() for non null values, as this latter is way less used.– Robert Niestroj
Dec 17 at 7:59
2
2
@JollyJoker In cases where the logic of the (
Optional returning) method deems the result has been found and is not, or should not be, null. One example would be "short-circuiting" a loop when a match is found by returning Optional.of(matchedItem). If no match was found the loop would complete and the method would return Optional.empty. However, there are (perhaps more frequent, perhaps not) cases where even the method cannot know if the result is null or not and must use Optional.ofNullable when returning.– Slaw
Dec 17 at 9:10
@JollyJoker In cases where the logic of the (
Optional returning) method deems the result has been found and is not, or should not be, null. One example would be "short-circuiting" a loop when a match is found by returning Optional.of(matchedItem). If no match was found the loop would complete and the method would return Optional.empty. However, there are (perhaps more frequent, perhaps not) cases where even the method cannot know if the result is null or not and must use Optional.ofNullable when returning.– Slaw
Dec 17 at 9:10
|
show 6 more comments
6 Answers
6
active
oldest
votes
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):
Optionalis primarily intended for use as a method return type where
there is a clear need to represent "no result," and where using
nullis likely to cause error. A variable whose type isOptionalshould never itself benull; it should always point to anOptionalinstance.
purpose of Optional is to tackle NullPointerException exception.
Aside: Just to call it out clearly, that the choice would of course implicitly let you define if an NPE should be thrown at runtime or not. It's not determined at the compile time though.
4
So shouldn't you beOptional.empty()pointer?
– chrylis
Dec 17 at 9:42
3
@chrylis oh I don't want to be that safe, I can afford to be thrown at the runtime. :)
– nullpointer
Dec 17 at 10:34
1
If this is to become the answer, I suggest adding something @ETO mentioned below: "[Throws NPE] at usage time not at creation"
– bohemian
Dec 17 at 10:36
add a comment |
the purpose of Optional is to tackle
NullPointerExceptionexception
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 |
I think it's 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?
add a comment |
Why would people opt for Optional instead of normal if-else method for null checking?
The main point of Optional<T> class is to provide a mean for performing null safe mapping operations.
employeeOptional.map(Employee::getName).map(String::toUpperCase).ifPresent(upperCasedNameConsumer)
The expression above can replace a cascade of if-else statements in a single readable expression.
Optional.of provides an assertion for the given argument to be a null-null value, otherwise, you can opt for Optional.ofNullable if you are not sure about the input.
I strongly recommend you to read the javadoc for Optional<T> class for more optional chaining methods that you can use for your advantage.
add a comment |
After reading some answers and comments I think this explanation is missing. Consider a method like
public Optional<String> name(Customer c) {
return c.isNew() ? Optional.ofNullable(getName(c)) : Optional.of(getName(c));
}
Here you want to throw a NullPointerException if the customer isn't new and is supposed to have a name; your code is inconsistent if that's ever null. Yet the name may not yet exist if the customer is new, hence ofNullable in that case and the method returns Optional.
add a comment |
Optional.ofNullableis a wrapper around existing APIs that can returnnull. You would call it as a consumer of an API.
Optional.of/Optional.emptyis for new code written withOptionalin mind. You would return anOptionalcreated withof/emptyas a provider of an API.
add a comment |
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
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):
Optionalis primarily intended for use as a method return type where
there is a clear need to represent "no result," and where using
nullis likely to cause error. A variable whose type isOptionalshould never itself benull; it should always point to anOptionalinstance.
purpose of Optional is to tackle NullPointerException exception.
Aside: Just to call it out clearly, that the choice would of course implicitly let you define if an NPE should be thrown at runtime or not. It's not determined at the compile time though.
4
So shouldn't you beOptional.empty()pointer?
– chrylis
Dec 17 at 9:42
3
@chrylis oh I don't want to be that safe, I can afford to be thrown at the runtime. :)
– nullpointer
Dec 17 at 10:34
1
If this is to become the answer, I suggest adding something @ETO mentioned below: "[Throws NPE] at usage time not at creation"
– bohemian
Dec 17 at 10:36
add a comment |
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):
Optionalis primarily intended for use as a method return type where
there is a clear need to represent "no result," and where using
nullis likely to cause error. A variable whose type isOptionalshould never itself benull; it should always point to anOptionalinstance.
purpose of Optional is to tackle NullPointerException exception.
Aside: Just to call it out clearly, that the choice would of course implicitly let you define if an NPE should be thrown at runtime or not. It's not determined at the compile time though.
4
So shouldn't you beOptional.empty()pointer?
– chrylis
Dec 17 at 9:42
3
@chrylis oh I don't want to be that safe, I can afford to be thrown at the runtime. :)
– nullpointer
Dec 17 at 10:34
1
If this is to become the answer, I suggest adding something @ETO mentioned below: "[Throws NPE] at usage time not at creation"
– bohemian
Dec 17 at 10:36
add a comment |
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):
Optionalis primarily intended for use as a method return type where
there is a clear need to represent "no result," and where using
nullis likely to cause error. A variable whose type isOptionalshould never itself benull; it should always point to anOptionalinstance.
purpose of Optional is to tackle NullPointerException exception.
Aside: Just to call it out clearly, that the choice would of course implicitly let you define if an NPE should be thrown at runtime or not. It's not determined at the compile time though.
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):
Optionalis primarily intended for use as a method return type where
there is a clear need to represent "no result," and where using
nullis likely to cause error. A variable whose type isOptionalshould never itself benull; it should always point to anOptionalinstance.
purpose of Optional is to tackle NullPointerException exception.
Aside: Just to call it out clearly, that the choice would of course implicitly let you define if an NPE should be thrown at runtime or not. It's not determined at the compile time though.
edited Dec 17 at 10:48
answered Dec 17 at 6:42
nullpointer
41.7k1088175
41.7k1088175
4
So shouldn't you beOptional.empty()pointer?
– chrylis
Dec 17 at 9:42
3
@chrylis oh I don't want to be that safe, I can afford to be thrown at the runtime. :)
– nullpointer
Dec 17 at 10:34
1
If this is to become the answer, I suggest adding something @ETO mentioned below: "[Throws NPE] at usage time not at creation"
– bohemian
Dec 17 at 10:36
add a comment |
4
So shouldn't you beOptional.empty()pointer?
– chrylis
Dec 17 at 9:42
3
@chrylis oh I don't want to be that safe, I can afford to be thrown at the runtime. :)
– nullpointer
Dec 17 at 10:34
1
If this is to become the answer, I suggest adding something @ETO mentioned below: "[Throws NPE] at usage time not at creation"
– bohemian
Dec 17 at 10:36
4
4
So shouldn't you be
Optional.empty()pointer?– chrylis
Dec 17 at 9:42
So shouldn't you be
Optional.empty()pointer?– chrylis
Dec 17 at 9:42
3
3
@chrylis oh I don't want to be that safe, I can afford to be thrown at the runtime. :)
– nullpointer
Dec 17 at 10:34
@chrylis oh I don't want to be that safe, I can afford to be thrown at the runtime. :)
– nullpointer
Dec 17 at 10:34
1
1
If this is to become the answer, I suggest adding something @ETO mentioned below: "[Throws NPE] at usage time not at creation"
– bohemian
Dec 17 at 10:36
If this is to become the answer, I suggest adding something @ETO mentioned below: "[Throws NPE] at usage time not at creation"
– bohemian
Dec 17 at 10:36
add a comment |
the purpose of Optional is to tackle
NullPointerExceptionexception
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 |
the purpose of Optional is to tackle
NullPointerExceptionexception
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 |
the purpose of Optional is to tackle
NullPointerExceptionexception
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
NullPointerExceptionexception
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.
edited Dec 17 at 11:07
answered Dec 17 at 6:53
ETO
1,656321
1,656321
add a comment |
add a comment |
I think it's 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?
add a comment |
I think it's 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?
add a comment |
I think it's 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?
I think it's 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?
edited Dec 21 at 8:43
Pang
6,8601563101
6,8601563101
answered Dec 17 at 6:48
NullPointer
4,29921130
4,29921130
add a comment |
add a comment |
Why would people opt for Optional instead of normal if-else method for null checking?
The main point of Optional<T> class is to provide a mean for performing null safe mapping operations.
employeeOptional.map(Employee::getName).map(String::toUpperCase).ifPresent(upperCasedNameConsumer)
The expression above can replace a cascade of if-else statements in a single readable expression.
Optional.of provides an assertion for the given argument to be a null-null value, otherwise, you can opt for Optional.ofNullable if you are not sure about the input.
I strongly recommend you to read the javadoc for Optional<T> class for more optional chaining methods that you can use for your advantage.
add a comment |
Why would people opt for Optional instead of normal if-else method for null checking?
The main point of Optional<T> class is to provide a mean for performing null safe mapping operations.
employeeOptional.map(Employee::getName).map(String::toUpperCase).ifPresent(upperCasedNameConsumer)
The expression above can replace a cascade of if-else statements in a single readable expression.
Optional.of provides an assertion for the given argument to be a null-null value, otherwise, you can opt for Optional.ofNullable if you are not sure about the input.
I strongly recommend you to read the javadoc for Optional<T> class for more optional chaining methods that you can use for your advantage.
add a comment |
Why would people opt for Optional instead of normal if-else method for null checking?
The main point of Optional<T> class is to provide a mean for performing null safe mapping operations.
employeeOptional.map(Employee::getName).map(String::toUpperCase).ifPresent(upperCasedNameConsumer)
The expression above can replace a cascade of if-else statements in a single readable expression.
Optional.of provides an assertion for the given argument to be a null-null value, otherwise, you can opt for Optional.ofNullable if you are not sure about the input.
I strongly recommend you to read the javadoc for Optional<T> class for more optional chaining methods that you can use for your advantage.
Why would people opt for Optional instead of normal if-else method for null checking?
The main point of Optional<T> class is to provide a mean for performing null safe mapping operations.
employeeOptional.map(Employee::getName).map(String::toUpperCase).ifPresent(upperCasedNameConsumer)
The expression above can replace a cascade of if-else statements in a single readable expression.
Optional.of provides an assertion for the given argument to be a null-null value, otherwise, you can opt for Optional.ofNullable if you are not sure about the input.
I strongly recommend you to read the javadoc for Optional<T> class for more optional chaining methods that you can use for your advantage.
answered Dec 17 at 8:53
HPH
1287
1287
add a comment |
add a comment |
After reading some answers and comments I think this explanation is missing. Consider a method like
public Optional<String> name(Customer c) {
return c.isNew() ? Optional.ofNullable(getName(c)) : Optional.of(getName(c));
}
Here you want to throw a NullPointerException if the customer isn't new and is supposed to have a name; your code is inconsistent if that's ever null. Yet the name may not yet exist if the customer is new, hence ofNullable in that case and the method returns Optional.
add a comment |
After reading some answers and comments I think this explanation is missing. Consider a method like
public Optional<String> name(Customer c) {
return c.isNew() ? Optional.ofNullable(getName(c)) : Optional.of(getName(c));
}
Here you want to throw a NullPointerException if the customer isn't new and is supposed to have a name; your code is inconsistent if that's ever null. Yet the name may not yet exist if the customer is new, hence ofNullable in that case and the method returns Optional.
add a comment |
After reading some answers and comments I think this explanation is missing. Consider a method like
public Optional<String> name(Customer c) {
return c.isNew() ? Optional.ofNullable(getName(c)) : Optional.of(getName(c));
}
Here you want to throw a NullPointerException if the customer isn't new and is supposed to have a name; your code is inconsistent if that's ever null. Yet the name may not yet exist if the customer is new, hence ofNullable in that case and the method returns Optional.
After reading some answers and comments I think this explanation is missing. Consider a method like
public Optional<String> name(Customer c) {
return c.isNew() ? Optional.ofNullable(getName(c)) : Optional.of(getName(c));
}
Here you want to throw a NullPointerException if the customer isn't new and is supposed to have a name; your code is inconsistent if that's ever null. Yet the name may not yet exist if the customer is new, hence ofNullable in that case and the method returns Optional.
edited Dec 17 at 9:16
answered Dec 17 at 9:09
JollyJoker
1514
1514
add a comment |
add a comment |
Optional.ofNullableis a wrapper around existing APIs that can returnnull. You would call it as a consumer of an API.
Optional.of/Optional.emptyis for new code written withOptionalin mind. You would return anOptionalcreated withof/emptyas a provider of an API.
add a comment |
Optional.ofNullableis a wrapper around existing APIs that can returnnull. You would call it as a consumer of an API.
Optional.of/Optional.emptyis for new code written withOptionalin mind. You would return anOptionalcreated withof/emptyas a provider of an API.
add a comment |
Optional.ofNullableis a wrapper around existing APIs that can returnnull. You would call it as a consumer of an API.
Optional.of/Optional.emptyis for new code written withOptionalin mind. You would return anOptionalcreated withof/emptyas a provider of an API.
Optional.ofNullableis a wrapper around existing APIs that can returnnull. You would call it as a consumer of an API.
Optional.of/Optional.emptyis for new code written withOptionalin mind. You would return anOptionalcreated withof/emptyas a provider of an API.
answered Dec 17 at 12:24
dnt
335
335
add a comment |
add a comment |
1
You may want to return a value wrapped with Optional. In this case, you can use
Optional.of(value);.– Emre Savcı
Dec 17 at 6:51
3
Two out of three answers provided by people call NullPointer. How apt for this question....
– Thilo
Dec 17 at 7:07
7
Because, as others have said in answers,
Optionalis designed to reduce NPEs at the method caller level, not necessarily at the method implementation level.Optional.ofis for when one knows the value is notnull(and an error should be thrown if it is),Optional.emptyis for when one knows the value isnull, andOptional.ofNullableis for when one is not sure if the value isnullor not.– Slaw
Dec 17 at 7:58
2
Biggest question for me is why the chose the naming that way. I would use
.of()for nullable values and then makeofNotNull()for non null values, as this latter is way less used.– Robert Niestroj
Dec 17 at 7:59
2
@JollyJoker In cases where the logic of the (
Optionalreturning) method deems the result has been found and is not, or should not be,null. One example would be "short-circuiting" a loop when a match is found by returningOptional.of(matchedItem). If no match was found the loop would complete and the method would returnOptional.empty. However, there are (perhaps more frequent, perhaps not) cases where even the method cannot know if the result isnullor not and must useOptional.ofNullablewhen returning.– Slaw
Dec 17 at 9:10