Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 49
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.Arrays;
- import java.util.List;
- public class Test {
- public static void main(String[] args) {
- List<Integer> list = Arrays.asList(0,2,4,6,8);
- list.replaceAll(i -> i + 1);
- System.out.println(list);
- }
- }
What will be the result of compiling and executing Test class?
- A [1, 3, 5, 7, 9]
- B [0, 2, 4, 6, 8]
- C Compilation error
- D Runtime Exception
Reveal correct answer
Correct answer: A
Explanation
replaceAll(UnaryOperator<E> operator) is a default method available in List interface, it replaces each element of this list with the result of applying the operator to that element.
list.replaceAll(i -> i + 1); => Adds 1 to each element of the list. Result is [1, 3, 5, 7, 9].
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
