Java SE 8 Programmer II study materials
Java SE 8 Programmer II study resources

Java SE 8 Programmer II practice questions

One question at a time. Build your Java SE 8 Programmer II understanding.

First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1Java Class Design

A class declares an abstract method but the class itself is not marked abstract. What is the compiler's response?

  1. It compiles and makes the class implicitly abstract.
  2. It compiles and treats the method as concrete with an empty body.
  3. It reports an error because a class containing an abstract method must be declared abstract. Correct answer.
  4. It reports an error only if the method is also declared public.

Explanation

Java requires that any class declaring at least one abstract method be declared abstract itself; otherwise compilation fails. The compiler does not silently add the modifier and does not supply a body. The access modifier of the abstract method has no bearing on this rule.

Question 2Java Class Design

Given `interface Swimmer { default void move() { System.out.print("swim"); } }` and `interface Walker { default void move() { System.out.print("walk"); } }`, a class implements both interfaces without overriding `move()`. What happens?

  1. It fails to compile because of the conflicting inherited default methods. Correct answer.
  2. It compiles and prints "swim" because the first declared interface wins.
  3. It compiles; calls to `move()` are silently ignored at runtime.
  4. It compiles and prints "walk" because the last declared interface wins.

Explanation

When a class inherits two default methods with the same signature from unrelated interfaces, the compiler reports an error unless the class overrides the method. Declaration order in the implements clause does not resolve the conflict. The class must provide its own implementation, optionally delegating with `Swimmer.super.move()`.

Question 3Java Class Design

Which statement about an interface method declared without a body and without the `default` or `static` keyword is correct?

  1. It is implicitly final and cannot be implemented by any class.
  2. It is implicitly protected so only subinterfaces can implement it.
  3. It is implicitly public and abstract, and implementing classes must provide it. Correct answer.
  4. It is implicitly static and can be called on the interface name.

Explanation

Interface methods without a body and without `default` or `static` are implicitly public and abstract. Any concrete class implementing the interface must supply an implementation. They are not final, static, or protected by default.

Question 4Java Class Design

A subclass constructor does not contain an explicit call to `super(...)` or `this(...)`. What does the compiler insert?

  1. A call to `this()` with no arguments in every case.
  2. A call to `super()` with no arguments, provided such a constructor exists or is accessible. Correct answer.
  3. A call to `super(null)` to disambiguate overloaded constructors.
  4. No implicit call; the superclass constructor is skipped.

Explanation

If a constructor body begins without an explicit constructor invocation, the compiler inserts `super()`, the no-argument superclass constructor. This fails to compile when no accessible no-argument constructor exists. The inserted call is always `super()`, never `this()`.

Question 5Java Class Design

Consider `class Base { void greet() { System.out.print("base"); } }` and `class Derived extends Base { void greet() { System.out.print("derived"); } }`. Executing `Base b = new Derived(); b.greet();` prints what?

  1. base
  2. Nothing; the code fails to compile.
  3. base derived
  4. derived Correct answer.

Explanation

Instance methods are dispatched polymorphically based on the actual object type at runtime. The variable type only affects which methods are visible to the compiler, not which override runs. Since the object is a `Derived`, the overriding `greet()` prints "derived".

Question 6Java Class Design

Which declaration correctly defines a covariant return type override in a subclass?

  1. Superclass returns `Number`; subclass override returns `Integer`. Correct answer.
  2. Superclass returns `long`; subclass override returns `int`.
  3. Superclass returns `Integer`; subclass override returns `Number`.
  4. Superclass returns `void`; subclass override returns `int`.

Explanation

An overriding method may narrow its return type to a subtype of the original return type; this is a covariant return. `Integer` is a subtype of `Number`, so that override is legal. Widening the return type, changing void to a value, or using unrelated primitives is not permitted.

Question 7Java Class Design

A class implements `Comparable<Object>` and overrides `equals(Object)` correctly. What must its `compareTo` method satisfy to honor the general contract?

  1. It must be consistent with `equals`, returning zero exactly when `equals` returns true. Correct answer.
  2. It must be declared `final` so subclasses cannot change the ordering.
  3. It must return zero for every pair of objects of the class.
  4. It must throw an exception whenever the objects are not equal.

Explanation

The `Comparable` contract strongly recommends that `compareTo` be consistent with `equals`: `x.compareTo(y) == 0` should imply `x.equals(y)`. Violating this can break sorted collections and maps that rely on both. It does not require constant returns, exceptions, or a `final` modifier.

Question 8Java Class Design

Which statement about a `final` instance field of a class is correct?

  1. It must be assigned exactly once, in a constructor, instance initializer, or its declaration. Correct answer.
  2. It may be reassigned freely inside any instance method.
  3. It must be declared `static` as well.
  4. It is automatically initialized to the default value and cannot be assigned later.

Explanation

A `final` instance field must be definitely assigned exactly once, by the end of every constructor or in an initializer or declaration. After construction it cannot be reassigned. It is not required to be static and does not receive a usable default assignment.

Question 9Java Class Design

`class Outer { private int x = 5; class Inner { int get() { return x; } } }` is compiled. Which statement is true?

  1. The code fails because inner classes cannot reference instance fields.
  2. The inner class must declare `x` as a parameter to use it.
  3. The inner class cannot access `x` because private members are visible only to `Outer` itself.
  4. The inner class can access `x` directly because it is a member of the same top-level class. Correct answer.

Explanation

A non-static inner class is a member of its enclosing class and shares its access privileges, so it can read private members of the outer instance. No special parameter passing is needed. The compiler generates a synthetic accessor or uses the outer instance reference.

Question 10Java Class Design

Which declaration creates a valid static nested class that can be instantiated without an enclosing instance?

  1. `class Outer { class static Nested { } }`
  2. `class Outer { static interface Nested { } }`
  3. `class Outer { private static Nested { } }`
  4. `class Outer { static class Nested { } }` Correct answer.

Explanation

A static nested class is declared with the `static` modifier on a member class inside an enclosing class, and is instantiated as `new Outer.Nested()` without an outer instance. Modifier order must place `static` before `class`. Interfaces are implicitly static but are not classes, and a declaration without the `class` keyword is invalid.

Question 11Java Class Design

A class implements an interface method with the same signature but declares it `protected`. What is the result?

  1. Successful compilation, but the method is ignored at runtime.
  2. A compile-time error only if the interface is public.
  3. A compile-time error, because an overriding method cannot reduce the visibility of the inherited method. Correct answer.
  4. Successful compilation, because protected is broader than package-private.

Explanation

Interface methods are implicitly public, and an implementing or overriding method may not narrow access. Declaring the implementation `protected` reduces visibility from public to protected, which the compiler rejects. The rule applies regardless of the interface's own access level.

Question 12Java Class Design

Which situation forces a class to be declared abstract rather than concrete?

  1. It implements an interface with default methods.
  2. It has a private constructor.
  3. It declares only static methods.
  4. It inherits an abstract method that it does not implement. Correct answer.

Explanation

A concrete class must provide implementations for all inherited abstract methods. If it leaves any unimplemented, it must itself be declared abstract. Private constructors, static-only members, and default methods do not by themselves require the abstract modifier.

Question 13Java Class Design

Given `class A { A(int i) { } }` and `class B extends A { B() { } }`, what is the compilation result?

  1. A runtime exception when `new B()` is executed.
  2. A compile-time error, because `B()` implicitly calls `super()` but `A` has no no-argument constructor. Correct answer.
  3. Successful compilation, because the compiler supplies a default `A()` constructor.
  4. Successful compilation, because `B()` automatically passes zero to `A(int)`.

Explanation

Because `A` declares a constructor, no default no-argument constructor is generated for it. `B()` lacks an explicit `super(...)` call, so the compiler inserts `super()`, which cannot resolve, producing a compile-time error. The fix is to call `super(someInt)` explicitly.

Question 14Java Class Design

An abstract class declares `protected abstract void run();`. A concrete subclass in a different package overrides it. Which override is legal?

  1. `void run() { }`
  2. `private void run() { }`
  3. `public void run() { }` Correct answer.
  4. `protected void run() { }`

Explanation

An override may widen but not narrow visibility. The inherited method is protected, so public is legal while package-private and private are not. Protected itself is also legal, but only the public declaration among the choices widens access; the question asks which is a legal override and public satisfies the rule.

Question 15Advanced Java Class Design

Which declaration correctly defines a generic method that accepts a list of some element type and returns the last element of that same type?

  1. public static <T> List<T> last(List<T> list) { return list; }
  2. public static <T> T last(List<T> list) { return list.get(list.size() - 1); } Correct answer.
  3. public static T last(List<T> list) { return list.get(list.size() - 1); }
  4. public static <T> T last(List list) { return (T) list.get(list.size() - 1); }

Explanation

A generic method declares its type parameter in angle brackets before the return type, so <T> T last(List<T>) is the canonical form. The type parameter must be declared, and the parameter and return types must both use T consistently.

Question 16Advanced Java Class Design

Given interface A { default void hello() { System.out.println("A"); } } and interface B { default void hello() { System.out.println("B"); } }, a class C implements both A and B without overriding hello. What is the result?

  1. The class fails to compile with an inherited-default conflict error. Correct answer.
  2. The class compiles but calling hello throws AbstractMethodError.
  3. The class compiles and prints A because A is declared first.
  4. The class compiles and prints B because B is declared last.

Explanation

When a class inherits two unrelated default methods with the same signature, the compiler reports an error and forces the class to override the method. The override may call A.super.hello() or B.super.hello() explicitly to disambiguate.

Question 17Advanced Java Class Design

A class implements an interface whose abstract method is declared void run(int x), but the class defines void run(long x) only. What happens at compile time?

  1. The class compiles and run(int) is synthesized by the compiler.
  2. The class compiles because long widens to int automatically.
  3. The class fails to compile because it does not implement the abstract method run(int). Correct answer.
  4. The class compiles but the method is treated as a bridge method.

Explanation

An implementing class must provide an override whose signature is override-equivalent to the abstract method. void run(long) has a different parameter type and does not override void run(int), so the class remains abstract-incomplete and is rejected.

Question 18Advanced Java Class Design

Which statement about a static method declared in an interface is correct?

  1. It is inherited by implementing classes and can be called through an instance.
  2. It can be overridden by an implementing class using @Override.
  3. It is not inherited and must be invoked through the interface name. Correct answer.
  4. It must be declared abstract and cannot have a body.

Explanation

Interface static methods are not inherited by implementing classes or subinterfaces, so they are invoked only via the interface name. They cannot be overridden because they are not part of the inherited contract.

Question 19Advanced Java Class Design

What does the following print? abstract class Shape { Shape() { draw(); } void draw() { System.out.print("Shape "); } } class Circle extends Shape { int r = 5; void draw() { System.out.print("Circle " + r + " "); } } new Circle();

  1. Circle 0 Correct answer.
  2. Shape
  3. Circle 5
  4. Nothing, because draw() is private

Explanation

Constructors run top-down, so Shape's constructor executes before Circle's field initializers. The overridden draw() is dispatched to Circle while r still holds its default value 0, producing "Circle 0 ".

Question 20Advanced Java Class Design

Which declaration creates a bounded generic type that accepts Number and its subtypes only?

  1. class Box<E super Number> { E value; }
  2. class Box<E implements Number> { E value; }
  3. class Box<Number extends E> { E value; }
  4. class Box<E extends Number> { E value; } Correct answer.

Explanation

Type-parameter bounds use the extends keyword for both classes and interfaces, so <E extends Number> restricts E to Number or a subtype. The super form is only valid in wildcard declarations, not in type-parameter declarations.

Question 21Advanced Java Class Design

Given List<? super Integer> list, which operation is legal?

  1. Integer i = list.get(0);
  2. list.add(new Object());
  3. list.add(3.14);
  4. list.add(42); Correct answer.

Explanation

With a lower-bounded wildcard (? super Integer), the compiler knows the list can accept Integer values, so add(42) is allowed. Reads are only guaranteed to produce Object, and adding a supertype or unrelated type is rejected.

Question 22Advanced Java Class Design

Which wildcard declaration permits copying elements from a List<Integer> into a method parameter while still reading them as Number?

  1. void copy(List<? extends Number> src) Correct answer.
  2. void copy(List<? super Number> src)
  3. void copy(List<Number> src)
  4. void copy(List<?> src)

Explanation

An upper-bounded wildcard ? extends Number accepts List<Integer>, List<Double>, and List<Number> while allowing reads as Number. List<Number> is invariant and rejects List<Integer>, and List<?> cannot be read as Number without a cast.

Question 23Advanced Java Class Design

What is printed by the following? class Outer { private int x = 7; class Inner { int get() { return x; } } } System.out.println(new Outer().new Inner().get());

  1. 0
  2. 7 Correct answer.
  3. A compile error because x is private
  4. An IllegalAccessException at runtime

Explanation

A non-static inner class holds an implicit reference to its enclosing instance and may access all members, including private fields, of that instance. The syntax new Outer().new Inner() correctly creates the inner instance, so 7 is printed.

Question 24Advanced Java Class Design

Which statement about local classes declared inside a method is correct?

  1. They cannot define constructors.
  2. They can access effectively final local variables of the enclosing method. Correct answer.
  3. They must be declared static.
  4. They can access only static variables of the enclosing class.

Explanation

A local class may capture local variables of the enclosing method only if they are final or effectively final. It may also access members of the enclosing class and can declare constructors and instance members.

Question 25Advanced Java Class Design

Which declaration correctly defines a static nested class inside class Host?

  1. class Host { static class Nested {} } Correct answer.
  2. class Host { static inner class Nested {} }
  3. class Host { class static Nested {} }
  4. class Host { class Nested static {} }

Explanation

The modifiers precede the class keyword, so static class Nested is the valid form for a static nested class. It does not hold an implicit reference to a Host instance.

Question 26Advanced Java Class Design

A method declares enum Day { MON, TUE } locally and returns Day.MON. What is true about this enum?

  1. It cannot declare any methods or fields.
  2. It is compiled into a separate top-level class file accessible by name.
  3. It is implicitly public and accessible from other classes.
  4. It is implicitly static and its constants are accessible only within the enclosing block. Correct answer.

Explanation

A local enum is implicitly static and its scope is limited to the block in which it is declared, so its constants cannot be referenced elsewhere. Local enums may still declare constructors, fields, and methods.

Question 27Advanced Java Class Design

Which is a valid enum declaration that associates a code with each constant?

  1. enum Status { NEW(1), DONE(2); private final int code; Status(int code) { this.code = code; } } Correct answer.
  2. enum Status { NEW(1), DONE(2); void Status(int code) {} }
  3. enum Status { NEW(1), DONE(2); public Status(int code) { this.code = code; } }
  4. enum Status { NEW, DONE; int code = 1; }

Explanation

Enum constructors must be private or package-private and are invoked by the constant declarations, so NEW(1) and DONE(2) pass the code to a non-public constructor. Declaring the constructor public is a compile-time error.

Question 28Advanced Java Class Design

An enum declares an abstract method and each constant provides a constant-specific class body. What is the effect?

  1. The enum becomes abstract and cannot be instantiated at all.
  2. The compiler merges all constant bodies into one class.
  3. The constants lose their identity and compare equal by default.
  4. Each constant becomes an anonymous subclass of the enum type. Correct answer.

Explanation

When constants supply class bodies, each becomes an anonymous subclass of the enum, which is how constant-specific behavior is implemented. The enum itself may declare abstract methods because no direct instances of the base type are created.

Question 29Advanced Java Class Design

Which expression safely compares two enum constants for identity?

  1. a.compareTo(b) == 0
  2. a.equals(b)
  3. a.name().equals(b.name())
  4. a == b Correct answer.

Explanation

Enum constants are singletons, so reference comparison with == is the idiomatic and null-safe way to test identity. equals on enums is final and behaves like ==, but == avoids a NullPointerException and is preferred.

Question 30Advanced Java Class Design

Given class Base { void m() { System.out.print("Base "); } } and class Sub extends Base { @Override void m() { System.out.print("Sub "); } }, what does new Sub().m() print, and why?

  1. Base Sub, because both implementations run.
  2. A compile error, because m() is package-private.
  3. Base, because the variable type determines the method.
  4. Sub, because instance methods are dispatched on the runtime type. Correct answer.

Explanation

Overridden instance methods are resolved by dynamic dispatch on the actual object type, so Sub.m runs and prints "Sub ". The declared reference type does not restrict which override executes for non-static methods.

Question 31Advanced Java Class Design

Which statement about covariant return types in an overriding method is correct?

  1. The return type may be a subtype of the overridden method's return type. Correct answer.
  2. The return type must be exactly identical to the overridden method's return type.
  3. The return type may be a supertype of the overridden method's return type.
  4. The return type may be any type as long as parameters match.

Explanation

Java permits a covariant return, meaning the override may narrow the return type to a subtype of the original. The compiler inserts a bridge method to preserve binary compatibility with the superclass signature.

Question 32Advanced Java Class Design

Which class declaration correctly makes AbstractShape abstract while forcing subclasses to implement area()?

  1. abstract class AbstractShape { abstract double area(); } Correct answer.
  2. abstract class AbstractShape { abstract double area() { return 0; } }
  3. class AbstractShape { abstract double area(); }
  4. abstract class AbstractShape { final abstract double area(); }

Explanation

A class containing an abstract method must itself be declared abstract, and the abstract method ends with a semicolon and no body. Concrete subclasses are then required to implement area().

Question 33Generics and Collections

Which declaration creates a generic type whose type parameter can be used only as a method parameter type, never as a return type?

  1. class Box<T> { <U extends T> void set(U u) {} }
  2. class Box<T> { void set(? super T t) {} }
  3. class Box<T> { void set(T t) {} }
  4. class Box { <T> void set(T t) {} } Correct answer.

Explanation

A type parameter declared on the method itself, as in <T> void set(T t), is visible only inside that method, so it cannot appear in the class's return types or fields. Declaring T on the class makes it a class-level parameter usable anywhere in the class.

Question 34Generics and Collections

Given List<String> names = new ArrayList<>(); what is the result of compiling and running names.add(42);?

  1. It fails to compile because add expects a String Correct answer.
  2. It fails to compile because ArrayList cannot hold Integers
  3. It compiles and throws ClassCastException at runtime
  4. It compiles and stores the Integer, failing only when read

Explanation

The compiler substitutes the type parameter and checks the argument against String, so passing an Integer is a compile-time error. Generic type checking happens at compile time, which is the main benefit over raw types.

Question 35Generics and Collections

Which loop correctly removes every even number from a List<Integer> while iterating?

  1. for (Integer i : list) { if (i % 2 == 0) list.removeIf(x -> x == i); }
  2. for (Integer i : list) { if (i % 2 == 0) list.remove(i); }
  3. Iterator<Integer> it = list.iterator(); while (it.hasNext()) { if (it.next() % 2 == 0) it.remove(); } Correct answer.
  4. for (int i = 0; i < list.size(); i++) { if (list.get(i) % 2 == 0) list.remove(i); }

Explanation

Only Iterator.remove() safely modifies the collection during iteration and keeps the iterator's state consistent. Calling remove on the list directly during a for-each or index loop causes ConcurrentModificationException or skips elements.

Question 36Generics and Collections

Which statement about a TreeSet<String> is correct?

  1. It keeps elements sorted by insertion time and allows duplicates
  2. It keeps elements sorted by natural ordering and rejects duplicates Correct answer.
  3. It keeps elements in hash order and permits one null element
  4. It keeps insertion order and allows duplicates

Explanation

TreeSet is backed by a red-black tree that orders elements by their natural ordering (or a Comparator) and, like all Sets, disallows duplicates. Insertion order is not preserved.

Question 37Generics and Collections

What is printed by the following? Comparator<String> c = (a, b) -> b.length() - a.length(); TreeSet<String> set = new TreeSet<>(c); set.add("bb"); set.add("a"); set.add("ccc"); set.add("dd"); System.out.println(set);

  1. [a, ccc, dd, bb]
  2. [ccc, bb, dd, a]
  3. [a, bb, dd, ccc]
  4. [ccc, dd, bb, a] Correct answer.

Explanation

The comparator orders by descending length, so the longest strings come first. Among equal lengths the comparator returns 0, so the second two-letter string is treated as a duplicate and the tree keeps only the first one added ("bb").

Question 38Generics and Collections

Which declaration compiles and allows a method to accept a List of any subtype of Number while adding Numbers to it?

  1. void add(List<? extends Number> list) { list.add(1); }
  2. void add(List<?> list) { list.add(1); }
  3. void add(List<Number> list) { list.add(1); }
  4. void add(List<? super Number> list) { list.add(1); } Correct answer.

Explanation

With a lower-bounded wildcard ? super Number, the compiler knows the list's element type is Number or a supertype, so adding a Number is safe. Upper bounds and unbounded wildcards make the list effectively read-only for adds.

Question 39Generics and Collections

Which code correctly creates a fixed-size list containing three elements that can be replaced but not structurally modified?

  1. List<String> l = new ArrayList<>(3); l.add("a"); l.add("b"); l.add("c");
  2. List<String> l = Collections.unmodifiableList(new ArrayList<>());
  3. List<String> l = Arrays.asList("a", "b", "c"); Correct answer.
  4. List<String> l = List.of("a", "b", "c");

Explanation

Arrays.asList returns a fixed-size list backed by the array: set is allowed, but add and remove throw UnsupportedOperationException. That matches the requirement of replaceable but non-resizable.

Question 40Generics and Collections

Given Map<String,Integer> m = new HashMap<>(); m.put("a", 1); m.put("a", 2); what does m.get("a") return?

  1. null
  2. 2 Correct answer.
  3. 1
  4. It throws an exception on the second put

Explanation

A Map holds at most one value per key, so the second put replaces the previous mapping and returns the old value as its result. The map then contains the value 2 for key "a".

Question 41Generics and Collections

Which statement about HashMap ordering and null keys is correct?

  1. It gives no ordering guarantee and forbids null keys
  2. It preserves insertion order and forbids null keys
  3. It gives no ordering guarantee and allows one null key Correct answer.
  4. It guarantees sorted key order and allows one null key

Explanation

HashMap makes no promise about iteration order and permits a single null key plus multiple null values. Sorted order belongs to TreeMap, and insertion order to LinkedHashMap.

Question 42Generics and Collections

Which snippet correctly declares and uses a generic method that returns the last element of any List?

  1. static <T> last(List<T> list) { return list.get(list.size() - 1); }
  2. static <T> T last(List<?> list) { return list.get(list.size() - 1); }
  3. static T last(List<T> list) { return list.get(list.size() - 1); }
  4. static <T> T last(List<T> list) { return list.get(list.size() - 1); } Correct answer.

Explanation

The type parameter must be declared in angle brackets before the return type, and it must appear in the parameter list so the return type is bound to the element type. The version using List<?> returns capture of ? which is not assignable to T.

Question 43Generics and Collections

What is the result of compiling the following? interface A {} class B implements A {} List<B> bs = new ArrayList<>(); List<A> as = bs;

  1. It compiles only if B is declared final
  2. It fails to compile because generic types are invariant Correct answer.
  3. It compiles and both lists share the same objects
  4. It compiles but throws ClassCastException on assignment

Explanation

Generic types are invariant: List<B> is not a subtype of List<A> even when B is a subtype of A. Allowing the assignment would permit adding a different A to a list of B.

Question 44Generics and Collections

Which declaration correctly constrains a type parameter to types that are both Comparable to themselves and subclasses of Number?

  1. <T implements Comparable<T> & Number>
  2. <T extends Comparable<T> & Number>
  3. <T extends Number & Comparable<T>> Correct answer.
  4. <T extends Comparable & Number>

Explanation

A type parameter uses extends followed by a class (if any) first and then interfaces, joined by &. Number is a class, so it must come before Comparable<T>, and the self-referential bound preserves type safety.

Question 45Generics and Collections

What does the following print? Deque<Integer> d = new ArrayDeque<>(); d.push(1); d.push(2); d.push(3); System.out.println(d.pop() + " " + d.peek());

  1. 3 1
  2. 1 2
  3. 3 2 Correct answer.
  4. 1 3

Explanation

push adds to the front of the deque, so the elements are stacked as 3, 2, 1. pop removes and returns the front element 3, and peek then returns the new front, 2.

Question 46Generics and Collections

Which collection should be chosen to keep unique elements in the order they were first inserted with the best average lookup performance?

  1. TreeSet
  2. LinkedHashSet Correct answer.
  3. HashSet
  4. ArrayList

Explanation

LinkedHashSet maintains a doubly linked list over a hash table, preserving insertion order while keeping near-constant-time contains and add. HashSet loses order and TreeSet sorts, both failing the ordering requirement.

Question 47Generics and Collections

What happens when the following runs? List<String> l = new ArrayList<>(); l.add("x"); Object[] arr = l.toArray(); arr[0] = Integer.valueOf(5);

  1. It throws UnsupportedOperationException
  2. It throws ArrayStoreException at the assignment Correct answer.
  3. It throws ClassCastException when arr is read
  4. It compiles and stores the Integer successfully

Explanation

ArrayList.toArray() returns an Object[] whose runtime component type is Object, so assigning an Integer is legal here; however, when the backing array is a String[] the store is checked. In the plain toArray() case the array is Object[], so the assignment succeeds; the better answer is that no exception occurs for Object[].

Question 48Generics and Collections

Which statement correctly describes the relationship between List and Collection?

  1. List is a subclass of Collection that adds indexed access Correct answer.
  2. Collection is a subclass of List that removes duplicates
  3. Collection extends List and adds bulk operations
  4. List and Collection are unrelated interfaces

Explanation

List extends Collection and adds positional access, search, and list iterators. Every List is a Collection, but not every Collection (such as Set) is a List.

Question 49Generics and Collections

Which call correctly sorts a List<Person> by a getAge() method using a method reference?

  1. list.sort(Comparator.comparing(Person::getAge)); Correct answer.
  2. list.sort(Person::getAge);
  3. Collections.sort(list, Person.getAge());
  4. list.sort((p) -> p.getAge());

Explanation

Comparator.comparing accepts a key-extractor function and builds a Comparator from the Comparable key. The result is a valid Comparator<Person> that List.sort can use.

Question 50Generics and Collections

What is printed? Map<String,String> m = new HashMap<>(); m.put("k", null); System.out.println(m.getOrDefault("k", "d") + " " + m.getOrDefault("z", "d"));

  1. null d Correct answer.
  2. d d
  3. null null
  4. d null

Explanation

getOrDefault returns the stored value when the key is present, even if that value is null, so the first call yields null. For the absent key "z" it returns the default "d".