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

Question 27

//StringListTest.java


import java.util.ArrayList;

import java.util.List;


public class StringListTest {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();

        list.add("ONE");

        list.add("TWO");

        list.add("THREE");

        list.add("THREE");


        if (list.remove(2)) {

            list.remove("THREE");

        }


        System.out.println(list);

    }

}

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

  • A

    An exception is thrown at runtime

  • B

    [ONE, TWO]

  • C

    [ONE, TWO, THREE]

  • D

    Compilation error

  • E

    [ONE, TWO, THREE, THREE]

Reveal correct answer

Correct answer: D

Explanation

The method list.remove(Object) returns a boolean result, but list.remove(int index) returns the removed item from the list, which in this case is of String type and not Boolean type. Therefore, the statement if(list.remove(2)) causes a compilation error because it expects a boolean expression.

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