🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Records and Sealed Classes: all 10 questions

Quiz: Records and Sealed Classes · Question 8 of 10

What does this print? (code)

What does this print?

import java.util.*;
record Order(int id, List<String> items) { }
public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("pen"));
        Order o = new Order(1, list);
        list.add("book");
        System.out.println(o.items().size());
    }
}
  1. A.1
  2. B.2
  3. C.0
  4. D.UnsupportedOperationException
Answer & explanation

Correct answer: 2

Without List.copyOf in a compact constructor, the record stores the same list object, so outside changes show through.

Can you get the rest right without peeking?

Take the timed Quiz: Records and Sealed Classes quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →