Java Optional Class MCQ Questions and Answers
Q. What is the purpose of the Optional
class in Java?
A. To provide a way to represent optional values that may or may not be presentB. To handle null values and prevent null pointer exceptions
C. To create a collection of optional objects
D. To perform functional programming operations
Q. How do you create an Optional
object?
A. 'Optional<Type> optional = Optional.of(value);'B. 'Optional<Type> optional = Optional.empty();'
C. 'Optional<Type> optional = new Optional<>(value);'
D. 'Optional<Type> optional = Optional.fromNullable(value);'
Q. What is the difference between Optional.of
and Optional.ofNullable
?
A. 'of' creates an 'Optional' with a non-null value, 'ofNullable' creates an 'Optional' with a nullable valueB. 'of' creates an empty 'Optional' if the value is null, 'ofNullable' creates an 'Optional' with the null value
C. 'of' throws an exception if the value is null, 'ofNullable' creates an empty 'Optional'
D. There is no difference, both methods do the same thing
Q. What does the orElse
method do?
A. Returns the value if present, otherwise returns the default valueB. Returns the value if present, otherwise throws an exception
C. Returns the value if present, otherwise returns null
D. Returns the value if present, otherwise executes a lambda expression
Q. What is the purpose of the orElseThrow
method?
A. To return a default value if the 'Optional' is emptyB. To throw a custom exception if the 'Optional' is empty
C. To return null if the 'Optional' is empty
D. To execute a lambda expression if the 'Optional' is empty
Q. How do you perform a mapping operation on an Optional
?
A. 'optional.map(value -> ...)'B. 'optional.flatMap(value -> ...)'
C. 'optional.filter(value -> ...)'
D. 'optional.orElse(value -> ...)'
Q. What is the difference between map
and flatMap
?
A. 'map' transforms the value, 'flatMap' transforms the 'Optional' itselfB. 'map' is used for simple transformations, 'flatMap' is used for complex transformations
C. 'map' returns an 'Optional', 'flatMap' returns the transformed value directly
D. There is no difference, both methods do the same thing
Q. How do you filter an Optional
?
A. 'optional.filter(condition)'B. 'optional.map(condition)'
C. 'optional.orElse(condition)'
D. 'optional.ifPresent(condition)'
Q. What does the ifPresent
method do?
A. Executes a lambda expression if a value is presentB. Returns a default value if a value is present
C. Throws an exception if a value is present
D. Returns the value if a value is present
Q. How do you get the value from an Optional
?
A. 'optional.get()'B. 'optional.orElse(null)'
C. 'optional.orElseThrow()'
D. 'optional.map(value -> value)'