Return to site

☕🎓JAVA CERTIFICATION QUESTION: Optional & null value

· java,ocp

Given the following method:

and the code fragment:

What is the result? Choose one.

* There is no output.

* One blank line is printed.

* Two blank lines are printed.

* 0 is printed and then nothing else.

* 0 is printed followed by a blank line.

#java #certificationquestion #ocp

 

 

Answer: There is no output.

The method Optional.ofNullable creates a new Optional object that either contains the provided argument or,if that argument value is null, is empty.

So, line 1 in the code snippet above creates an Optional that contains an autoboxed Integer that has a value of zero.

Line 2 creates an Optional object representing emptiness.

We cannot use null as a parameter in Java Optional.

The purpose of the Optional class is to provide a container that may or may not contain a non-null value.

Therefore, passing a null value as a parameter to Optional defeats the purpose of the class,

as it is not able to distinguish between an empty value and a null value.

Instead, we should use the Optional.ofNullable() method to create an Optional object that may or may not contain a non-null value.

This method takes a single parameter, which can be either a non-null value or null.

If the parameter is null, the resulting Optional object will be empty, otherwise it will contain the non-null value.

For example, to create an Optional object that may or may not contain a String value, we can use the following code:

Optional optionalValue = Optional.ofNullable(someStringValue);

If someStringValue is null, optionalValue will be an empty Optional object.

If someStringValue is not null, optionalValue will be an Optional object that contains the value of someStringValue.

Concerning the Predicate, anytime "v -> v == null" is used in a filter operation on an Optional, the result must be an empty Optional.

So the Optional is always empty regardless of the situation.

This in turn shows that no printing is ever invoked.

Conclusion: There is no output.