Java OCA OCP Practice Question 2225

Question

Choose the best option based on this program:

import java.util.Optional;
import java.util.stream.Stream;

public class Main {
     public static void main(String args[]){
         Stream.of("abcd ","java",null).forEach(Main::toUpper);
     }//  ww  w. j  av a 2 s.com
     private static void toUpper(String str) {
         Optional <String> string = Optional.ofNullable(str);
         System.out.print(string.map(String::toUpperCase).orElse("dummy"));
     }
}
A.  this program prints:  ABCD JAVAdummy
B.  this program prints:  abcd javadummy
C.  this program prints:  Abcd Java null
D.  this program prints:  Optional[ABCD] Optional[JAVA] Optional[dummy]
e.  this program prints:  Optional[ABCD] Optional[JAVA] Optional[DUMMY]


A.

Note

Note that the variable string points to Optional.ofNullable(str).

When the element null is encountered in the stream, it cannot be converted to uppercase and hence the orElse() method executes to return the string "dummy".

In this program, if Optional.of(str) were used instead of Optional.ofNullable(str) the program would have resulted in throwing a NullPointerException.




PreviousNext

Related