Free Java 17 OCP Practice Test 2

10 more challenging exam questions for 1Z0-829 — with detailed explanations

10
Questions
20 min
Suggested Time
~65%
To Pass
Free
No Signup

📋 How This Practice Test Works

Test 2 covers different topics than Test 1: generics, polymorphism, collections, method references, and tricky exam patterns. Click an answer for each question.

When done, click Submit & Show Answers to see your score and detailed explanations for every question.

These questions reflect actual OCP exam difficulty. Aim for 65%+ to be exam-ready.

Question 1

What is the result of the following code?

import java.util.*; List<? extends Number> nums = new ArrayList<Integer>(); nums.add(42); // line 1 Number n = nums.get(0); // line 2 System.out.println(n);

✅ Correct Answer: C

An upper-bounded wildcard List<? extends Number> is read-only for writes. You cannot add any element (except null) because the compiler can't guarantee type safety — the list could be List<Integer>, List<Long>, or any other Number subtype. Line 1 fails to compile. Line 2 is fine because we can safely read elements as the upper bound (Number).

Question 2

What is the output?

class Animal { String name = "Animal"; String getName() { return name; } } class Dog extends Animal { String name = "Dog"; String getName() { return name; } } Animal a = new Dog(); System.out.println(a.name + " " + a.getName());

✅ Correct Answer: B

Fields are not polymorphic — they're resolved by the reference type (Animal), so a.name returns "Animal". Methods are polymorphic — they're resolved by the actual object type (Dog), so a.getName() returns "Dog". This is a classic OCP trap.

Question 3

What is the output?

import java.util.*; import java.util.stream.*; List<String> names = List.of("Alice", "Bob", "Anna", "Charlie"); Map<Character, Long> grouped = names.stream() .collect(Collectors.groupingBy( s -> s.charAt(0), Collectors.counting() )); System.out.println(grouped.get('A'));

✅ Correct Answer: C

Collectors.groupingBy with a downstream collector counting() groups by first character and counts elements in each group. The result is: {A=2, B=1, C=1}. Both "Alice" and "Anna" start with 'A', so grouped.get('A') returns 2L (boxed to Long for display).

Question 4

Which method reference is INVALID for the functional interface Function<String, Integer>?

✅ Correct Answer: D

Function<String, Integer> requires a method that takes a String and returns an Integer.

(A) String::length is VALID. It effectively translates to: (String s) -> s.length(). The return type is int, which is autoboxed to Integer.

(B) Integer::parseInt is VALID. It references the static method Integer.parseInt(String s), which takes a String and returns an int.

(C) String::hashCode is VALID. It effectively translates to: (String s) -> s.hashCode(), returning an int.

(D) System.out::println is INVALID because println returns void, not Integer. It is compatible with Consumer<String>, not Function<String, Integer>.

Question 5

What is the output?

String s = "Hello"; StringBuilder sb = new StringBuilder("Hello"); System.out.println(s == "Hello"); System.out.println(s.equals(sb.toString()));

✅ Correct Answer: A

First line: "Hello" literal is interned in the String pool. The variable s also references that interned literal. So s == "Hello" is true (same reference).

Second line: sb.toString() returns "Hello" (content equal to s). String.equals() compares content, so the result is true.

Question 6

What is the output?

int x = 5; String result = switch (x) { case 1, 2, 3 -> "low"; case 4, 5, 6 -> { String s = "medium"; yield s.toUpperCase(); } default -> "high"; }; System.out.println(result);

✅ Correct Answer: B

The switch expression with arrow syntax -> uses yield when the case branch is a block. The case 4, 5, 6 matches x=5, executes the block, and yields "medium".toUpperCase() which is "MEDIUM".

Question 7

What is the result?

class Counter { private static int count = 0; private int instanceCount = 0; public Counter() { count++; instanceCount++; } } Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); // What are the values of count and instanceCount (from c3) at this point?

✅ Correct Answer: A

count is static — shared across all instances. Three constructor calls increment it three times, so count = 3.

instanceCount is an instance variable — each Counter has its own. For c3 (just created), instanceCount was initialized to 0, then the constructor incremented it to 1.

Question 8

What is the output?

try { try { throw new RuntimeException("first"); } catch (RuntimeException e) { throw new IllegalStateException("second", e); } } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e.getCause().getMessage()); }

✅ Correct Answer: C

The inner try throws RuntimeException("first"). The inner catch wraps it: new IllegalStateException("second", e) — "second" becomes the message, e becomes the cause. The outer catch receives this IllegalStateException. e.getMessage() returns "second", and e.getCause().getMessage() returns "first" (the original wrapped exception's message).

Question 9

Which statement about sealed classes is FALSE?

✅ Correct Answer: C

This is FALSE. Subclasses of a sealed class must be in the same module as the sealed class (or in the same package if the sealed class is in the unnamed module). They cannot be in any arbitrary module.

The other statements are TRUE: (A) Permits clause is required (except for nested classes in the same file). (B) Subclasses must specify their inheritance behavior. (D) Sealed type hierarchies allow the compiler to verify exhaustive pattern matching.

Question 10

What is the output?

import java.util.*; Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 2); map.put("c", 3); map.merge("a", 10, Integer::sum); map.merge("d", 100, Integer::sum); System.out.println(map.get("a") + " " + map.get("d"));

✅ Correct Answer: A

map.merge(key, value, remappingFunction): if the key is absent or maps to null, associates it with value. Otherwise replaces with remappingFunction.apply(oldValue, value).

For "a" (existing, value=1): merge applies Integer.sum(1, 10) = 11.
For "d" (absent): merge stores 100 directly without calling the function.

Answered 0 of 10 questions

🎉 Test Complete!

0/10

Great work! Review your answers below.

Ready for the Full Question Bank?

You've completed Test 2. The full JavaOCP platform has 1,884 Java 17 OCP questions across 37 timed certification tests — every topic, every difficulty level.

Plus 2,074 Java 21 OCP questions if you're targeting the newer exam.

Start 3-Day Free Trial → How to Pass First Attempt

From ₹1,400 / $16 • 6 months unlimited access