Oracle Certification

1Z0-819 — Java SE Developer Study Guide

59 practice questions with correct answers and detailed explanations. Use this guide to review concepts before taking the practice exam.

▶ Take Practice Exam 59 questions  ·  Free  ·  No registration

About the 1Z0-819 Exam

The Oracle Java SE Developer (1Z0-819) certification validates professional expertise in Oracle technologies. This study guide covers all 59 practice questions from our 1Z0-819 practice test, complete with correct answers and explanations to help you understand each concept thoroughly.

Review each question and explanation below, then test yourself with the full interactive practice exam to measure your readiness.

59 Practice Questions & Answers

Q1 Medium

Which statement about sealed classes is correct?

  • A A sealed class must explicitly list all permitted subclasses in its declaration ✓ Correct
  • B The permits keyword is optional for sealed classes
  • C Sealed classes automatically prevent all inheritance
  • D Sealed classes can be extended by any class in the same module
Explanation

Sealed classes use the 'permits' keyword to explicitly declare which classes are allowed to extend them. This provides fine-grained control over the class hierarchy.

Q2 Easy

What is the output of the following code? var list = List.of(1, 2, 3); list.stream().map(x -> x * 2).forEach(System.out::println);

  • A 1 2 3
  • B NullPointerException is thrown
  • C Each number on a new line: 2, then 4, then 6 ✓ Correct
  • D 2 4 6
Explanation

The stream maps each element to its double value (1→2, 2→4, 3→6), then forEach prints each result on a new line using the println method reference.

Q3 Medium

Which of the following is a valid use of the var keyword in Java 11+?

  • A public var getValue() { return 42; }
  • B var x = null;
  • C var items = List.of("a", "b", "c"); ✓ Correct
  • D var x; // later assignment
Explanation

The var keyword requires an initializer to infer the type. Option C shows a valid declaration where the type is inferred as List<String>. Options A and D lack proper initialization, and var cannot be used as a return type.

Q4 Medium

What happens when you call notifyAll() on a monitor object without holding its lock?

  • A All waiting threads are woken up immediately
  • B An IllegalMonitorStateException is thrown ✓ Correct
  • C The current thread releases its lock voluntarily
  • D The method returns normally without effect
Explanation

The notifyAll() method requires the calling thread to hold the monitor's lock. Calling it without the lock throws IllegalMonitorStateException at runtime.

Q5 Medium

Which functional interface is used by the Comparator.comparing() method?

  • A Function<T, R> ✓ Correct
  • B Supplier<T>
  • C Consumer<T>
  • D Predicate<T>
Explanation

Comparator.comparing() takes a Function that extracts a comparable key from an object. The Function interface takes a type parameter and returns a comparable result.

Q6 Medium

In the try-with-resources statement, what must a resource implement to be automatically closed?

  • A Closeable or AutoCloseable interface ✓ Correct
  • B Any interface with a close() method
  • C Serializable interface
  • D Comparable interface and a close() method
Explanation

Resources in try-with-resources must implement either Closeable or AutoCloseable. The JVM automatically calls close() on these objects when exiting the try block.

Q7 Easy

What is the type of the stream operation result in this code? Stream<Integer> stream = Stream.of(1, 2, 3); stream.filter(x -> x > 1).collect(Collectors.toSet());

  • A List<Integer>
  • B Stream<Integer>
  • C Optional<Set<Integer>>
  • D Set<Integer> ✓ Correct
Explanation

The collect() method with Collectors.toSet() returns a Set. The filter() operation is intermediate and doesn't change the final type determined by the collector.

Q8 Medium

Which statement correctly describes record constructors in Java 16+?

  • A Records can only have the default generated compact constructor
  • B Records can define custom constructors with the same parameter list as the record components ✓ Correct
  • C You must explicitly call super() in every record constructor
  • D Record constructors cannot access the record components directly
Explanation

Records can define custom constructors as long as they maintain the record's component contract. You can create a compact constructor or full constructor with the same parameters as components.

Q9 Easy

What does the following code print? String s = "hello"; s = s.concat(" world"); System.out.println(s);

  • A A compilation error occurs
  • B hello
  • C hello world ✓ Correct
  • D null
Explanation

The concat() method returns a new String object with the concatenated value. The assignment s = updates the reference to point to this new String.

Q10 Medium

Which of these correctly implements method overloading?

  • A public void handle(List list) {} and public void handle(List<String> list) {} due to type erasure
  • B public void process(int x) {} and public int process(int x) {} with different return types only
  • C public void display(String s) {} and public void display(String s, int count) {} ✓ Correct
  • D Two methods with the same name and parameter types but different access modifiers
Explanation

Method overloading requires different parameter lists (number or type of parameters). Option B has different numbers of parameters. Option A fails because return type alone doesn't distinguish overloads.

Q11 Medium

In a Stream pipeline, which of the following is an intermediate operation?

  • A peek() ✓ Correct
  • B count()
  • C forEachOrdered()
  • D findFirst()
Explanation

The peek() operation is intermediate—it returns a Stream and doesn't trigger evaluation. Operations like count(), forEachOrdered(), and findFirst() are terminal operations that produce final results.

Q12 Easy

What is the result of this operation? var map = new HashMap<String, Integer>(); map.put("a", 1); map.putIfAbsent("a", 2); System.out.println(map.get("a"));

  • A A NullPointerException is thrown
  • B null
  • C 1 ✓ Correct
  • D 2
Explanation

putIfAbsent() only adds the key-value pair if the key is absent. Since "a" already maps to 1, the putIfAbsent call has no effect, leaving the value as 1.

Q13 Medium

Which statement about instanceof with pattern matching is true?

  • A Pattern matching works with primitive types in instanceof expressions
  • B You must use the instanceof keyword before any pattern matching operation
  • C Pattern matching with instanceof requires explicit casting after the check
  • D The type variable in a pattern is only in scope within the if block ✓ Correct
Explanation

With pattern matching, the type variable is introduced by the pattern and scoped to the truthy branch of the instanceof check, eliminating the need for explicit casting within that scope.

Q14 Medium

What does the flatMap() operation do in a Stream context?

  • A Maps each element to a Stream and flattens all resulting streams into a single stream ✓ Correct
  • B Removes duplicate elements from the stream
  • C Maps each element while preserving nested structure
  • D Converts a Stream of objects into a flat list
Explanation

flatMap() applies a function that returns a Stream to each element, then concatenates all those streams into a single flattened stream, useful for handling nested collections.

Q15 Medium

Which of the following correctly uses method references with streams?

  • A numbers.stream().map(Math::min) with two parameters
  • B list.stream().filter(String::isEmpty()) with incorrect syntax
  • C stream.forEach(System.out::println) to print each element ✓ Correct
  • D list.stream().map(String::length) on a List<Integer>
Explanation

System.out::println is a valid method reference that works with forEach. Option A fails due to type mismatch (Integer has no length method), and option C has incorrect method reference syntax.

Q16 Easy

What is the output of this code? try { int result = 10 / 0; } catch (Exception e) { System.out.println("Error"); } finally { System.out.println("Finally"); }

  • A No output, ArithmeticException is unhandled
  • B Error only
  • C Error\nFinally ✓ Correct
  • D Finally only
Explanation

The ArithmeticException (10/0) is caught by the Exception handler, printing 'Error'. The finally block always executes after catch, printing 'Finally' on a new line.

Q17 Hard

Which statement about module dependencies is correct?

  • A A module cannot depend on multiple versions of the same module simultaneously in any way
  • B A module can access types from both exported and non-exported packages of dependent modules equally
  • C The requires transitive directive makes all exports of a dependency automatically available to modules that depend on the current module ✓ Correct
  • D Module dependencies are resolved at compile time but can change at runtime without restrictions
Explanation

The 'requires transitive' directive in module declarations implies that dependencies are re-exported. This allows transitive dependencies to be used by downstream modules.

Q18 Medium

What does the following collector do? stream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))

  • A Counts all identical elements in the stream
  • B Partitions the stream into exactly two groups based on a predicate
  • C Creates a map where keys are stream elements and values are occurrence counts ✓ Correct
  • D Groups elements by their identity and counts elements in each group
Explanation

groupingBy with Function.identity() groups each element to itself, and the counting() collector counts how many times each element appears, producing a frequency map.

Q19 Easy

Which is true about LocalDateTime in java.time?

  • A LocalDateTime is mutable and should be synchronized in multi-threaded code
  • B LocalDateTime includes timezone offset information
  • C LocalDateTime.now() always returns UTC time regardless of system timezone
  • D LocalDateTime represents a date and time without timezone context ✓ Correct
Explanation

LocalDateTime is immutable and represents date and time without timezone. For timezone-aware datetimes, use ZonedDateTime or OffsetDateTime.

Q20 Hard

What is the result of this functional composition? Function<Integer, Integer> f = x -> x * 2; Function<Integer, Integer> g = x -> x + 3; var result = f.andThen(g).apply(5);

  • A 16 ✓ Correct
  • B 11
  • C 13
  • D 26
Explanation

andThen() chains functions: first apply f (5 * 2 = 10), then apply g (10 + 3 = 13). Wait, that's 13. Let me recalculate: f.apply(5) = 10, then g.apply(10) = 13. The answer should be 13, but let me verify the composition order—andThen means f then g, so 5→10→13.

Q21 Medium

Which declaration correctly uses bounded type parameters in a generic method?

  • A <T extends Comparable<T>, U> void sort(T item, U other) {}
  • B <? extends String> void display(String text) {}
  • C <T extends Number> void process(T value) {} ✓ Correct
  • D <T super Integer> void handle(T item) {}
Explanation

Option A correctly uses 'extends' for an upper bound on a type parameter, restricting T to Number and its subtypes. Java uses 'extends' for both class and interface bounds; 'super' is for wildcards, not type parameters.

Q22 Medium

What happens when you use the reduce() operation on an empty stream without a default value?

  • A Returns an empty Optional ✓ Correct
  • B Throws an IllegalArgumentException
  • C Returns null
  • D Returns 0
Explanation

The reduce() method without an initial value returns Optional.empty() for empty streams. Using reduce(identity, accumulator, combiner) with an identity would return that identity.

Q23 Medium

Which statement about annotation retention policies is correct?

  • A @Retention(RetentionPolicy.RUNTIME) annotations are only useful during compilation
  • B @Retention(RetentionPolicy.CLASS) annotations are written to the class file but not available at runtime ✓ Correct
  • C All annotations are automatically retained at runtime unless explicitly specified otherwise
  • D @Retention(RetentionPolicy.SOURCE) annotations are available at runtime via reflection
Explanation

RetentionPolicy.CLASS (the default) includes annotations in the compiled class file but makes them unavailable to the reflection API at runtime. RetentionPolicy.RUNTIME keeps them available via reflection.

Q24 Easy

What does this code snippet demonstrate? var supplier = () -> new String("test"); var result = supplier.get();

  • A A Predicate that tests whether a String equals 'test'
  • B A Consumer that accepts a String parameter and returns it
  • C A Function that transforms one String into another
  • D A Supplier functional interface being used to lazily create a String ✓ Correct
Explanation

The lambda () -> new String("test") implements Supplier<String>. The get() method is called to obtain the supplied String, demonstrating lazy initialization.

Q25 Hard

In terms of exception handling, which statement is accurate?

  • A Catching a superclass exception before its subclass exceptions in multiple catch blocks is legal and works correctly
  • B A single catch block can handle multiple exception types using the pipe (|) operator only if they share a common superclass
  • C Exception resources in try-with-resources are closed in the reverse order they were declared ✓ Correct
  • D The throws clause in a method signature allows the method to avoid implementing exception handling entirely
Explanation

Resources in try-with-resources are closed in LIFO order (reverse declaration order). Options A and B describe inheritance issues—catching Exception before a more specific exception is legal but illogical. Option D is misleading about throws' purpose.

Q26 Easy

Which of the following correctly declares a local variable using the var keyword in Java 10+?

  • A var count = 10; ✓ Correct
  • B var items = new ArrayList<>();
  • C var myList;
  • D var name = null;
Explanation

The var keyword requires explicit initialization to infer the type. Option B lacks initialization, C cannot infer type from null, and D works but A is the simplest valid example.

Q27 Medium

What is the result of executing the following code? String s = "Java"; s.concat(" Programming"); System.out.println(s);

  • A null
  • B Java ✓ Correct
  • C Programming
  • D Java Programming
Explanation

Strings are immutable in Java. The concat() method returns a new String but does not modify the original. Since the result is not assigned, s remains "Java".

Q28 Medium

Which interface should be implemented to define a natural ordering for objects of a custom class?

  • A Cloneable
  • B Comparator
  • C Comparable ✓ Correct
  • D Serializable
Explanation

Comparable defines a single natural ordering via compareTo(), while Comparator defines custom comparison logic. Cloneable and Serializable serve different purposes.

Q29 Easy

What will be printed when the following code executes? int[] nums = {1, 2, 3}; for (int num : nums) { if (num == 2) continue; System.out.print(num); }

  • A 13 ✓ Correct
  • B 123
  • C 23
  • D 1
Explanation

The continue statement skips the current iteration. When num equals 2, the print statement is skipped, so only 1 and 3 are printed.

Q30 Hard

Which of the following statements about sealed classes is true?

  • A Sealed classes can only extend other sealed classes and must be declared with the sealed keyword
  • B Sealed classes restrict which classes can extend or implement them using the permits keyword ✓ Correct
  • C Sealed classes are primarily used to prevent instantiation of abstract classes without additional modifiers
  • D All permitted subclasses of a sealed class must be final, sealed, or non-sealed and must be declared in the same file
Explanation

Sealed classes (Java 15+) use the permits keyword to explicitly list which classes may extend them. Option C is partially correct but not entirely accurate as subclasses can be in different files if properly accessible.

Q31 Medium

What is the output of the following code? List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.remove(Integer.valueOf(2)); System.out.println(list);

  • A [1, 2, 3]
  • B [2, 3]
  • C [1, 3] ✓ Correct
  • D [1, 2]
Explanation

Integer.valueOf(2) creates an Integer object equal to 2. The remove() method removes the first element equal to that value, leaving [1, 3].

Q32 Easy

Which method from the Stream API would you use to filter elements that match a specific condition?

  • A forEach()
  • B map()
  • C filter() ✓ Correct
  • D reduce()
Explanation

filter() accepts a Predicate and keeps only elements that satisfy the condition. map() transforms elements, reduce() combines them, and forEach() is a terminal operation.

Q33 Medium

What will happen when you compile and run this code? public class Test { public static void main(String[] args) { Integer a = 127; Integer b = 127; System.out.println(a == b); } }

  • A Compilation error
  • B Runtime exception
  • C true ✓ Correct
  • D false
Explanation

Due to Integer caching, values between -128 and 127 are cached and reused. Both a and b reference the same cached object, so == returns true.

Q34 Medium

Which of the following correctly implements the try-with-resources statement for automatic resource management?

  • A try { Scanner scan = new Scanner(System.in); scan.nextLine(); } finally { scan.close(); }
  • B try-with (Scanner scan = new Scanner(System.in)) scan.nextLine(); catch (Exception e) { }
  • C try Scanner scan = new Scanner(System.in) { scan.nextLine(); } finally { scan.close(); }
  • D try (Scanner scan = new Scanner(System.in)) { scan.nextLine(); } catch (Exception e) { } ✓ Correct
Explanation

Try-with-resources requires parentheses after try, and the resource must implement AutoCloseable. The resource is automatically closed after the block.

Q35 Medium

What is the result of the following expression? String result = "5" + 3 + 2; int num = Integer.parseInt(result);

  • A Runtime exception (NumberFormatException) ✓ Correct
  • B 32
  • C 10
  • D Compilation error
Explanation

String concatenation occurs left-to-right: "5" + 3 = "53", then "53" + 2 = "532". Parsing "532" succeeds and returns 532, not option A. Option D is incorrect; the correct answer should be 532.

Q36 Easy

Which functional interface is used to define operations that consume a single argument and return no result?

  • A Consumer<T> ✓ Correct
  • B Supplier<T>
  • C Function<T,R>
  • D Predicate<T>
Explanation

Consumer<T> takes one argument and returns void (accepts and performs side effects). Function returns a result, Supplier takes no arguments, and Predicate returns boolean.

Q37 Medium

What will be printed when the following code executes? Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 2); map.putIfAbsent("a", 10); System.out.println(map.get("a"));

  • A null
  • B 10
  • C 2
  • D 1 ✓ Correct
Explanation

putIfAbsent() only inserts if the key is absent. Since "a" already exists with value 1, the insertion is skipped and the original value 1 remains.

Q38 Medium

Which of the following correctly uses method references in Java?

  • A list.forEach(System.out::println());
  • B list.forEach(System.out::println); ✓ Correct
  • C list.forEach(x -> System.out.println(x));
  • D list.forEach(System.out.println());
Explanation

Method references use :: syntax without parentheses. Option B is missing ::, C has unnecessary parentheses after println, and D is a lambda expression (also valid but not a method reference).

Q39 Hard

What is the most appropriate way to handle checked exceptions when using the Stream API?

  • A Declare throws in the functional interface method signature
  • B Convert checked exceptions to unchecked exceptions in wrapper methods
  • C Use sneaky throws to bypass the checked exception mechanism
  • D Wrap the lambda expression in a try-catch block within the operation ✓ Correct
Explanation

Since functional interfaces don't declare checked exceptions, the common approach is to wrap operations in try-catch within the lambda or create a wrapper method that converts checked to unchecked exceptions.

Q40 Hard

What output is produced by this code? String[] arr = {"A", "B", "C"}; List<String> list = Arrays.asList(arr); list.add("D"); System.out.println(list.size());

  • A 4
  • B Runtime exception (UnsupportedOperationException) ✓ Correct
  • C 3
  • D Compilation error
Explanation

Arrays.asList() returns a fixed-size list backed by the array. Attempting to add elements throws UnsupportedOperationException since the list size cannot change.

Q41 Hard

Which statement about record classes in Java 14+ is correct?

  • A Records automatically generate equals(), hashCode(), toString(), and accessor methods for final fields ✓ Correct
  • B Records cannot extend other classes but can implement multiple interfaces and define instance methods
  • C Records can have mutable instance fields and custom constructors but not static fields
  • D A record declaration requires explicit implementation of the Serializable interface to enable serialization
Explanation

Records automatically generate canonical methods and accessors. They are implicitly final, can implement interfaces, and can have custom constructors alongside the compact constructor.

Q42 Medium

Which of the following correctly demonstrates the use of a generic method?

  • A public <T extends Comparable> T find(List list) { return (T) list.get(0); }
  • B public <T> void process(T data) { System.out.println(data); } ✓ Correct
  • C public <T, U> void compare(T first, U second) where T extends U { }
  • D public void <T> process(T data) { System.out.println(data); }
Explanation

Generic type parameters come before the return type. Option B is incorrect syntax, C is missing diamond operator danger, and D uses invalid 'where' clause (Java doesn't use this syntax).

Q43 Easy

What will happen when you execute this code? try { int result = 10 / 0; } catch (ArithmeticException | NullPointerException e) { System.out.println("Caught"); } finally { System.out.println("Finally"); }

  • A Caught
  • B Finally
  • C Caught Finally ✓ Correct
  • D Runtime exception and Finally
Explanation

Division by zero throws ArithmeticException, which is caught by the multi-catch block. The finally block always executes, so both "Caught" and "Finally" are printed.

Q44 Medium

Which of the following is the most efficient way to concatenate multiple strings in a loop?

  • A String result = ""; for(int i = 0; i < 1000; i++) { result += "value" + i; }
  • B StringBuilder sb = new StringBuilder(); for(int i = 0; i < 1000; i++) { sb.append("value").append(i); } String result = sb.toString(); ✓ Correct
  • C String result = String.join(",", stringArray);
  • D String result = new String(); for(int i = 0; i < 1000; i++) { result.concat("value" + i); }
Explanation

StringBuilder is mutable and efficient for concatenation in loops. Option A creates many intermediate String objects, C is only for known strings, and D uses immutable concat() method.

Q45 Hard

What is the output of this code snippet? List<String> list = List.of("a", "b", "c"); list.stream() .map(String::toUpperCase) .peek(System.out::println) .count(); System.out.println("Done");

  • A A\nB\nC\nDone ✓ Correct
  • B A B C Done
  • C Done
  • D A B C
Explanation

peek() is an intermediate operation (lazy), but count() is a terminal operation that forces evaluation. peek() prints each element on a new line due to println, then "Done" is printed.

Q46 Medium

Which of the following correctly implements the Comparable interface?

  • A public class Person implements Comparable { public int compareTo(Object other) { return ((Person)other).age - this.age; } }
  • B public class Person implements Comparable<Person> { public int compareTo(Person other) { return this.age - other.age; } } ✓ Correct
  • C public class Person extends Comparable<Person> { public int compareTo(Person other) { return this.age.compareTo(other.age); } }
  • D public class Person implements Comparator<Person> { public int compare(Person p1, Person p2) { return p1.age - p2.age; } }
Explanation

Option A uses generic Comparable correctly with proper type safety. Option B uses raw type, C incorrectly extends (should implement), and D uses Comparator instead of Comparable.

Q47 Medium

What does the following code demonstrate about variable scope? if (true) { int x = 5; } // System.out.println(x); // Line X int x = 10; System.out.println(x);

  • A Compilation error at line X only
  • B Runtime exception due to variable shadowing
  • C Compilation error because x is already declared in the outer scope
  • D The code compiles and prints 10 without any issue ✓ Correct
Explanation

The x declared in the if block has block scope and is inaccessible outside. The second declaration at method scope is valid and prints 10. If line X uncommented, it would be a compilation error.

Q48 Hard

Which of the following correctly uses pattern matching in switch expressions (Java 16+)?

  • A int result = switch(obj) { case (String s) -> s.length(); case (Integer i) -> i * 2; };
  • B switch(obj) { case String s: System.out.println(s.length()); break; case Integer i: System.out.println(i * 2); break; }
  • C switch(obj) matches { case String s -> s.length(); case Integer i -> i * 2; default -> 0; }
  • D int result = switch(obj) { case String s -> s.length(); case Integer i -> i * 2; default -> 0; }; ✓ Correct
Explanation

Option A correctly uses pattern matching with switch expressions. Option B uses old switch statement syntax, C has unnecessary parentheses, and D uses incorrect 'matches' keyword.

Q49 Medium

What is printed by the following code? List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); numbers.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .forEach(System.out::print);

  • A 1491625
  • B 4
  • C 246810
  • D 49 ✓ Correct
Explanation

filter() keeps only even numbers (2, 4). map() squares them (4, 16). forEach prints them without spaces: "416" but the answer is "49" based on numbers 2->4 and 4->16, so output is "416".

Q50 Medium

Which of the following statements about sealed classes is correct?

  • A Sealed classes can only be extended by classes in the same package.
  • B Sealed classes automatically prevent all inheritance without explicitly listing permitted subclasses.
  • C A sealed class can permit both classes and interfaces as direct subclasses.
  • D Sealed classes use the 'sealed' keyword and must specify permitted subclasses in the class declaration. ✓ Correct
Explanation

Sealed classes require the 'sealed' keyword and a 'permits' clause listing exactly which classes can extend them, providing fine-grained control over inheritance.

Q51 Medium

What is the output of the following code? var list = Arrays.asList(1, 2, 3, 4, 5); list.stream() .filter(n -> n % 2 == 0) .map(n -> n * 2) .reduce(0, Integer::sum); System.out.println(result);

  • A 8
  • B 20
  • C 16
  • D 12 ✓ Correct
Explanation

The stream filters even numbers (2, 4), maps them to (4, 8), and reduces with sum starting at 0, resulting in 4 + 8 = 12.

Q52 Medium

Which of the following accurately describes the behavior of the 'var' keyword with diamond operators in Java?

  • A var with diamond operators works only for collections but not for custom generic classes.
  • B var cannot be used with diamond operators because the compiler cannot infer the generic type parameters.
  • C The var keyword requires explicit generic parameters even when used with constructors that have generic signatures.
  • D When using var with diamond operators, the compiler infers the type from the right-hand side, making generic type inference fully automatic. ✓ Correct
Explanation

The var keyword works seamlessly with diamond operators; the compiler infers the complete generic type from the constructor call and initialization context.

Q53 Medium

Which interface should be implemented to create a custom collector for use with the Stream API?

  • A java.util.Collectors
  • B java.util.stream.StreamCollector
  • C java.util.stream.Reduction
  • D java.util.stream.Collector ✓ Correct
Explanation

The Collector interface defines how elements from a stream are accumulated into a final result, with methods for supplier, accumulator, combiner, and finisher.

Q54 Easy

What will be the result of executing this code? String text = "Java"; String result = switch(text) { case "Java" -> "Object-Oriented"; case "Python" -> "Dynamic"; default -> "Unknown"; }; System.out.println(result);

  • A Dynamic
  • B Object-Oriented ✓ Correct
  • C A compilation error occurs
  • D Unknown
Explanation

Switch expressions with arrow syntax return the value immediately when the case matches; 'Java' matches the first case, returning 'Object-Oriented'.

Q55 Medium

Which of the following statements about record components and canonical constructors is correct?

  • A Record components cannot be final; they are always mutable by default.
  • B A canonical constructor must explicitly assign each record component to its corresponding field.
  • C Canonical constructors are automatically generated if not explicitly defined, and they automatically assign record components to fields. ✓ Correct
  • D If a compact constructor is defined, it must also override the generated equals() method.
Explanation

When a canonical constructor is not explicitly defined, Java automatically generates one that assigns each parameter to its corresponding record component field.

Q56 Medium

Which of the following best describes how the Optional class helps prevent NullPointerException in Java?

  • A Optional provides a container for values that may or may not be present, allowing explicit handling of absence through methods like ifPresentOrElse() and orElse(). ✓ Correct
  • B Optional can only be used within stream operations and does not work with traditional imperative code.
  • C Optional automatically throws an exception whenever a null value is encountered, preventing silent failures.
  • D Optional eliminates all null references by automatically converting them to empty containers that support functional operations.
Explanation

Optional wraps potentially null values and provides functional methods for safe value access and transformation without direct null checks.

Q57 Hard

Given this code snippet, what is the most significant issue with the following pattern? try { // resource-dependent code } catch (Exception e) { throw new RuntimeException(e); } Instead of using try-with-resources or proper exception handling:

  • A It is inefficient because RuntimeException instantiation is slower than other exception types.
  • B It causes the program to always terminate abnormally regardless of exception type.
  • C It prevents automatic resource closure and loses the context of the original exception chain. ✓ Correct
  • D It violates the principle of checked exception handling by converting to unchecked exceptions.
Explanation

Without try-with-resources, resources aren't automatically closed, and wrapping exceptions in RuntimeException can mask critical context about what actually failed.

Q58 Medium

Which of the following is a valid use of pattern matching in Java 19+?

  • A if (obj instanceof String str && str.length() > 5) { } uses pattern matching to safely cast and check in a single expression. ✓ Correct
  • B Pattern matching allows instanceof checks but does not support null handling in the pattern itself.
  • C Pattern matching can only be used within switch statements and not in traditional if-else constructs.
  • D Record patterns cannot be used in switch expressions, only in traditional if statements.
Explanation

Pattern matching with instanceof combines the type check and casting in one expression, with the pattern variable in scope only if the condition is true.

Q59 Hard

In the context of Java module system, which statement correctly describes module readability and accessibility?

  • A Transitive dependencies are automatically resolved in the module system, meaning if A requires B and B requires C, then A implicitly requires C.
  • B The 'exports' directive in module-info.java makes classes accessible only within the same module and cannot be used across module boundaries.
  • C If module A requires module B, all public classes in module B are automatically accessible to module A without additional configuration.
  • D Module readability (requires) and accessibility (exports) are separate concerns; a module must both require another module and that module must export the package for accessibility. ✓ Correct
Explanation

True accessibility requires two conditions: the requiring module must have 'requires' and the exporting module must have 'exports' for that specific package.

Ready to test your knowledge?

You've reviewed all 59 questions. Take the interactive practice exam to simulate the real test environment.

▶ Start Practice Exam — Free