Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 49
Question ID: UKOCP22069
Given code:
- package com.udayankhattry.ocp;
- import java.util.Arrays;
- import java.util.List;
- public class Test {
- public static void main(String[] args) {
- StringBuilder [] arr = {new StringBuilder("A"), new StringBuilder("A")};
- List<StringBuilder> list = Arrays.asList(arr);
- for(int i = 0; i < 2; i++)
- if(i == 0)
- list.forEach(sb -> sb.append("B"));
- else
- list.forEach(sb -> sb.append("C"));
- list.forEach(sb -> System.out.println(sb));
- }
- }
What is the result?
-
A
A
A
-
B
ABC
ABC
-
C
ABB
ACC
-
D
BC
BC
-
E
AB
AB
-
F
AC
AC
-
G
Runtime exception is thrown
Reveal correct answer
Correct answer: B
Explanation
UKOCP22069:
Arrays.asList(...) method returns a fixed-size list backed by the specified array and as list is backed by the specified array therefore, you cannot add or remove elements from this list. Using add/remove methods cause an exception at runtime. But you can invoke the set(int index, E element) method on the returned list.
This behavior is bit different from the List.of(...) method, which returns unmodifiable list, hence calling add/remove/set methods on the unmodifiable list throws an exception at runtime.
Given code, does not try to add new elements to the list or does not try to remove elements from the list, hence no question of any runtime exception.
Iterable<T> interface has forEach(Consumer<? super T>) method. List<E> extends Collection<E> & Collection<E> extends Iterable<E>, therefore forEach(Consumer) can easily be invoked on reference variable of List<E> type.
As Consumer is a Functional Interface, hence a lambda expression can be passed as argument to forEach() method.
forEach(Consumer) method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
Initially,
list --> {["A"], ["A"]}
1st iteration: i = 0, i == 0 evaluates to true, code inside if-block gets executed. "B" is appended to both the list elements. list --> {["AB"], ["AB"]}
2nd iteration: i = 1, i == 0 evaluates to false, code inside else-block gets executed. "C" is appended to both the list elements. list --> {["ABC"], ["ABC"]}
list.forEach(sb -> System.out.println(sb)); prints below on to the console:
ABC
ABC
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
