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

Question 33

//IntegerListTest.java


import java.util.ArrayList;

import java.util.List;


public class IntegerListTest {

    public static void main(String[] args) {

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


        list.add(27);

        list.add(27);


        list.add(new Integer(27));

        list.add(new Integer(27));


        System.out.println(list.get(0) == list.get(1));

        System.out.println(list.get(2) == list.get(3));

    }

}

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

  • A

    false true

  • B

    false false

  • C

    true false

  • D

    true true

Reveal correct answer

Correct answer: C

Explanation

This is a bit tricky. Just remember this: Two instances of the following wrapper objects, created through auto-boxing, will always be the same if their primitive values are the same:

  • Boolean,

  • Byte,

  • Character from \u0000 to \u007f (7f equals to 127),

  • Short and Integer from -128 to 127.

For the 1st statement, list.add(27); => Auto-boxing creates an integer object for 27. For the 2nd statement, list.add(27); => Java compiler finds that there is already an Integer object in the memory with value 27, so it uses the same object. That is why System.out.println(list.get(0) == list.get(1)); returns true. new Integer(27) creates a new object in the memory, so System.out.println(list.get(2) == list.get(3)); returns false.

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