Oracle Certified Associate Java Se 8 Programmer · Free Practice Question Hard

Question 15

What will be the result of compiling and executing Test class?

  • A

    []

  • B

    [110, 110]

  • C

    [110, 110, 110]

  • D

    [110]

Reveal correct answer

Correct answer: A

Explanation

As list can store only wrapper objects and not primitives, hence 

for list.add(110); auto-boxing creates an Integer object {110}. 

for list.add(new Integer(110)); as new keyword is used so another Integer object {110} is created. 

for 3rd add method call, list.add(110); auto-boxing kicks in and as 110 is between -128 to 127, hence Integer object created at 1st statement is referred.


removeIf(Predicate) method was added as a default method in Collection interface in JDK 8 and it removes all the elements of this collection that satisfy the given predicate. 


Boolean expression is : i == 110; in this expression i is wrapper object and 110 is int literal so java extracts int value of wrapper object, i and then equates. As all the 3 objects store 110, hence true is returned. All integer objects are removed form the list.


If list.removeIf(i -> i == new Integer(110)); was used, then all three list elements would return false as object references are equated and not contents.

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.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need