Course contents

Utilities & patterns: interview questions & scenarios

Premium12 questions · 20 what-if follow-ups

These are the utility-method questions I ask when I want to know whether you understand the contract behind the convenient one-liner. The method names are easy to memorize; the interview signal is whether you can predict mutability, null handling, ordering and failure modes before the code runs.

Use this page like a mock interview: read the question, say your answer out loud first, then open the model answer. If a detail feels slippery, go back to the lessons on Collections and Arrays utility methods, immutable collections, converting between arrays, lists, sets and maps and combining, flattening, zipping and splitting collections.

Question 1. What does it print?CoreAsked very often

What does this print, and which operations throw: Arrays.asList, new ArrayList<>(...) or List.of?

Tests fixed-size list, immutable factory, null handling

Show answerHide answer2 follow-ups

Model answer

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String[] raw = {"new", "paid"};

        List<String> fixed = Arrays.asList(raw);
        List<String> mutable = new ArrayList<>(Arrays.asList(raw));
        List<String> immutable = List.of("new", "paid");

        fixed.set(1, "settled");
        mutable.add("refunded");

        System.out.println(Arrays.toString(raw));
        System.out.println(mutable);

        try {
            fixed.add("shipped");
        } catch (UnsupportedOperationException ex) {
            System.out.println("fixed add throws");
        }

        try {
            immutable.set(0, "created");
        } catch (UnsupportedOperationException ex) {
            System.out.println("immutable set throws");
        }

        try {
            List.of("ok", null);
        } catch (NullPointerException ex) {
            System.out.println("List.of rejects null");
        }
    }
}

It prints:

[new, settled]
[new, paid, refunded]
fixed add throws
immutable set throws
List.of rejects null

Arrays.asList(raw) is a fixed-size list backed by the array. set works because it replaces an existing array slot, and the array sees the change. add cannot work because the array length cannot grow.

new ArrayList<>(Arrays.asList(raw)) copies the references into a normal resizable list. List.of(...) creates an unmodifiable, null-rejecting factory list, so add, remove and set all throw.

How I’d say it in the interview

"Arrays.asList is the array bridge: fixed size, set is allowed, add and remove throw, and changes write through to the array. Wrapping it in a new ArrayList gives me a normal mutable list. List.of is different: it is an unmodifiable Java 9 factory list and rejects nulls."

Signals depth

Separating fixed-size from immutable. Many candidates use those words as if they are the same thing, but Arrays.asList allows set and List.of does not.

Red flags

"They are all lists, so add should work" or "Arrays.asList makes an immutable copy." Both miss the optional-operation part of the List contract.

Follow-ups interviewers ask next

  1. What if I do raw[0] = "created" after creating fixed?

    fixed.get(0) returns "created", because the list and the array share storage. The mutable ArrayList copy does not change.

    1. What if I want a mutable list initialized with literal values?

      Use new ArrayList<>(List.of("new", "paid")) or new ArrayList<>(Arrays.asList(raw)). I prefer the List.of form for literals when I know there are no nulls.

Question 2. DebuggingCoreAsked very often

A production service throws UnsupportedOperationException on orders.add(order). How do you debug it?

Tests optional operations, source of list, defensive copying

Show answerHide answer2 follow-ups

Model answer

I first ask where the list came from. UnsupportedOperationException usually means the runtime implementation does not support that operation, even though the variable type is List.

Common sources are:

Source What is unsupported Fix if you need mutation
Arrays.asList(array) add, remove new ArrayList<>(Arrays.asList(array))
List.of(...) add, remove, set build a new ArrayList
List.copyOf(input) add, remove, set copy into ArrayList before mutating
Stream.toList() add, remove, set new ArrayList<>(stream.toList())
Collections.unmodifiableList(input) writes through wrapper mutate the owner, or copy intentionally

The debugging move is boring and effective: log or inspect orders.getClass().getName() at the boundary, then search the construction path. The fix should match intent. If this is internal working state, copy into a mutable list. If this is an API return value, keep it unmodifiable and change the caller.

How I’d say it in the interview

"A List reference does not promise every List operation. I would trace the construction path: Arrays.asList, List.of, List.copyOf, Stream.toList and unmodifiableList are the usual suspects. Then I would decide whether the caller should get a mutable working copy or whether mutation is the real bug."

Signals depth

Mentioning Stream.toList() is a good Java 16+ tell. A lot of older interview answers still assume every stream list is a mutable ArrayList because they are thinking of Collectors.toList().

Red flags

Catching and ignoring UnsupportedOperationException, or changing the method parameter type from List to ArrayList without fixing the construction path.

Follow-ups interviewers ask next

  1. What if the list came from Collections.unmodifiableList(cache)?

    That is a live read-only view. If the owning cache mutates, readers see the change, but writes through the view throw. At an API boundary I usually prefer List.copyOf(cache) so callers see a snapshot.

  2. What if the list is shared between threads?

    Do not fix mutability and thread safety in the same breath. A mutable ArrayList is not thread-safe. If threads share it, decide whether you need immutable snapshots, a synchronized policy, or a concurrent design.

Question 3. ConceptCoreAsked very often

Compare Collections.unmodifiableList, List.copyOf and List.of. Which one would you use for an API boundary?

Tests view versus copy, null policy, shallow immutability

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 4. ConceptCoreAsked very often

How do Stream.toList(), Collectors.toList() and Collectors.toUnmodifiableList() differ?

Tests stream result mutability, null handling, Java versions

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 5. What does it print?CoreCommonly asked

What happens with duplicates in Set.of, and can I rely on Map.of iteration order?

Tests factory collections, duplicate policy, iteration order

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 6. What does it print?CoreCommonly asked

What does this print: Arrays.asList(int[]), Arrays.equals and Arrays.deepEquals?

Tests primitive arrays, varargs, nested array comparison

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 7. ConceptWarm-upCommonly asked

Which array conversion would you use: toArray(new String[0]) or toArray(String[]::new)?

Tests typed array conversion, Java 11 constructor reference, stale pre-sizing advice

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 8. DebuggingCoreAsked very often

This Collectors.toMap line fails in production. What are the two likely causes?

Tests duplicate keys, null values, merge function

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 9. CodingCoreAsked very often

Code a list-to-map conversion that keeps input order and handles duplicate ids.

Tests LinkedHashMap, merge rule, encounter order

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 10. What does it print?CoreCommonly asked

What do Collections.max and binarySearch do on these edge cases?

Tests empty collections, sorted precondition, negative insertion point

Model answer, how to say it, 1 follow-up: unlock with the Java Pass

Question 11. CodingCoreCommonly asked

Code flatten(List<List<T>>) and zip(List<A>, List<B>) in Java.

Tests flatMap, zip stop rule, generic helpers

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Question 12. DesignSeniorCommonly asked

Design a constructor for an immutable object that stores a list of dates.

Tests defensive copies, copy-then-validate, shallow immutability

Model answer, how to say it, 2 follow-ups: unlock with the Java Pass

Premium question set

Keep reading with the Java Pass

The rest of this question set is part of Java One-Stop Interview Prep: in-depth explanations, diagrams, model answers and how to say them in the interview.

From ₹199 · one-time payment · No auto-renewal

Lessons in Utilities & patterns