Advanced Java

Test Your Knowledge

Answer all 10 questions, then submit to see your score.

1. Which statement correctly distinguishes `throw` from `throws`?

2. In the Template Method pattern, why is the skeleton method (like `run()`) typically marked `final`?

3. What does this print?

Set<Integer> a = new HashSet<>(Set.of(1, 2, 3, 4));
Set<Integer> b = new HashSet<>(Set.of(3, 4, 5, 6));
a.retainAll(b);
System.out.println(a.size());

4. What does this print?

import java.util.stream.IntStream;

public class Demo {
    public static void main(String[] args) {
        System.out.println(IntStream.range(1, 5).sum());
        System.out.println(IntStream.rangeClosed(1, 5).sum());
    }
}

5. What does this print?

class InvalidOrderQuantityException extends RuntimeException {
    private final int quantity;
    InvalidOrderQuantityException(int quantity) {
        super("invalid quantity: " + quantity);
        this.quantity = quantity;
    }
    int getQuantity() { return quantity; }
}

public class Demo {
    static void placeOrder(int quantity) {
        if (quantity <= 0) {
            throw new InvalidOrderQuantityException(quantity);
        }
    }
    public static void main(String[] args) {
        try {
            placeOrder(-3);
        } catch (InvalidOrderQuantityException e) {
            System.out.println(e.getMessage() + " / qty=" + e.getQuantity());
        }
    }
}

6. According to this lesson, what does a growing chain of `if (obj instanceof TypeA) {...} else if (obj instanceof TypeB) {...}` usually indicate?

7. What does this print?

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Demo {
    public static void main(String[] args) {
        List<String> words = List.of("cat", "car", "dog", "door", "duck");
        Map<Character, Long> countByFirst = words.stream()
                .collect(Collectors.groupingBy(w -> w.charAt(0), Collectors.counting()));
        System.out.println(countByFirst.get('c'));
        System.out.println(countByFirst.get('d'));
    }
}

8. What happens when this code runs?

import java.util.List;
import java.util.stream.Stream;

public class Demo {
    public static void main(String[] args) {
        Stream<String> stream = List.of("a", "b", "c").stream();
        long count = stream.count();
        System.out.println(count);
        stream.forEach(System.out::println);
    }
}

9. What are the two direct subclasses of `Throwable`?

10. Which statement correctly compares ArrayList and LinkedList performance for get(index)?