OCP Question 10, Explanation

Given the code fragment:

List<Integer> num = Arrays.asList(1, 2);
UnaryOperator<Double> unop = x -> x + 1.0;
num.replaceAll(unop);
num.forEach(x -> System.out.println(x));

What is the result?

A. 2.0
3.0
B. 1
C. A compilation error occurs.
D. A NumberFormatException is thrown at run time.

 

The correct answer is option C.

The fault lies with replaceAll() invocation since the num object can hold Integers only but the specified UnaryOperator returns Doubles. Also note that we can’t just change num’s type variable from Integer to Double because of a comperr: ints will be autoboxed to Integers but not Doubles. This rule – that the compiler can perform only a single-step conversion on its own – can be applied many times on the exam.

Okay, so how would we fix the problem? Populating num with doubles like this

List<Integer> num = Arrays.asList(1d, 2d);

won’t work, either: the values will be autoboxed to Double and then what? We still have the List that is typed to Integer.

Typing UnaryOperator to Integer cannot be done as its lambda returns a Double, too.

Nothing to do but apply changes in two places simultaneously affecting a type variable and some of the literals, for example:

List<Double> num = Arrays.asList(1d, 2d);

Or like this:

UnaryOperator<Integer> unop = x -> x + 1;

Now please tell me if this

List<Double> num = Arrays.asList(1f, 2f);

will work or not? After all, there’s a feature called promotion…

Click here to view the answer to this additional question
No, it won’t work because automatic promotion from float to double is a conversion, too, and we know that the compiler cannot perform multiple-step conversions, in this particular case from float to double first and then double to Double.

Leave Comment

Your email address will not be published. Required fields are marked *