Search Tutorials


1Z0-830 Practice Test 1 | Java SE 21 Developer | JavaInUse

1Z0-830 Java SE 21 Developer - Practice Test 1

Your Progress

0 / 66
Question 1 MEDIUM
Which of the following sealed class declarations compile? (Choose two.)
Select all that apply
Option 1 compiles because Circle is declared as final, which is required when extending a sealed class. Option 2 does not compile because Circle must be declared as final, sealed, or non-sealed. Option 3 compiles because all permitted subclasses are listed and each subclass correctly declares either final or non-sealed. Option 4 does not compile because Shape does not declare a permits clause but Circle extends it. See more: Java 21 New Features
Question 2 MEDIUM
Which of the following local variable declarations using var are invalid? (Choose three.)
Select all that apply
Option 1 is valid because the type is inferred as int. Option 2 is invalid because var requires an initializer. Option 3 is invalid because var cannot infer type from null. Option 4 is invalid because array initializer syntax without 'new' is not allowed with var. Option 5 is valid because the type is inferred as int[]. Option 6 is valid because the assignment expression evaluates to int, so type can be inferred. See more: Data Types & Variables
Question 3 MEDIUM
Given: double amount = 12500; NumberFormat format = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); System.out.println(format.format(amount)); What is the output?
getCompactNumberInstance with Locale.US and Style.SHORT formats numbers using compact notation. 12,500 becomes 12.5K in US locale. Therefore, the output is 12.5K. See more: Localization
Question 4 MEDIUM
You are working on a module named inventory.app that depends on another module named inventory.core. The inventory.app module should make its package inventory.app.api available to other modules. Which of the following is the correct file to declare the inventory.app module?
A Java module must be declared in a file named module-info.java. The module name must match the declared module (inventory.app). The requires directive declares dependency on inventory.core, and exports makes the package available to other modules. Therefore, option 2 is correct. See more: Modules & Packaging
Question 5 MEDIUM
What is the output of the following code? public class TestInterfaces { public static void main(String[] args) { Child.print(); } } interface Parent { default void print() { System.out.print("parent"); } } interface Child extends Parent { static void print() { System.out.print("child"); } }
Static methods in interfaces are not inherited. Child defines its own static method print(). Calling Child.print() invokes the static method declared in Child. Therefore, the output is 'child'. See more: OOP & Classes
Question 6 MEDIUM
Given: List<String> italianAuthors = new ArrayList<>(); italianAuthors.add("Dante"); italianAuthors.add("Umberto Eco"); Which of the following declarations compile? (Choose two.)
Select all that apply
Option 1 does not compile because italianAuthors is declared as List<String>, not ArrayList<String>, and generics are invariant. Option 2 does not compile because you cannot put values into a Map with ? extends wildcard. Option 3 compiles because var infers HashMap<String, List<String>> and the put operation is valid. Option 4 does not compile because generics are invariant: HashMap<String, ArrayList<String>> is not a subtype of Map<String, List<String>>. Option 5 compiles because the diamond operator infers HashMap<String, List<String>> and the put operation is valid. See more: Collections
Question 7 MEDIUM
Given: LocalDate localDate = LocalDate.of(2021, 12, 5); Date date = java.sql.Date.valueOf(localDate); DateFormat formatter = new SimpleDateFormat(/* pattern */); String output = formatter.format(date); System.out.println(output); It is known that the given code prints "December 05". Which of the following should be inserted as the pattern?
MMMM represents the full month name (e.g., December). MM represents numeric month. dd represents two-digit day. Therefore, "MMMM dd" produces "December 05". See more: Data Types & Variables
Question 8 MEDIUM
Given: Period p = Period.between( LocalDate.of(2022, Month.JANUARY, 1), LocalDate.of(2023, Month.JANUARY, 1)); System.out.print(p); Duration d = Duration.between( LocalDate.of(2022, Month.JANUARY, 1), LocalDate.of(2023, Month.JANUARY, 1)); System.out.print(d); What is the output?
Period works with LocalDate and represents date-based amounts, so the result is P1Y. Duration requires time-based temporal objects (such as LocalDateTime or Instant). LocalDate does not support seconds, so Duration.between() throws UnsupportedTemporalTypeException. Therefore, P1Y is printed first, followed by an exception. See more: Data Types & Variables
Question 9 MEDIUM
Given: interface Processor { double apply(int x); } public class Test { public static void main(String[] args) { Processor p1 = x -> x * 2; // Line 1 Processor p2 = x -> Double.valueOf(x); // Line 2 Processor p3 = x -> { throw new RuntimeException(); }; // Line 3 } } Which lines fail to compile?
The functional interface method apply(int x) returns double. Line 1 compiles because x * 2 is an int that is automatically widened to double. Line 2 compiles because Double.valueOf(x) returns a Double which is auto-unboxed to double. Line 3 compiles because a lambda may throw an unchecked exception (RuntimeException). The method does not declare checked exceptions, but unchecked exceptions are allowed. Therefore, all lines compile successfully. See more: Streams & Lambdas
Question 10 MEDIUM
Given: var cities = new TreeSet<String>(); cities.add("Berlin"); cities.add("Amsterdam"); cities.add("Zurich"); cities.add("Madrid"); cities.add("Lisbon"); System.out.println(cities.headSet("Madrid")); What will be printed?
TreeSet sorts elements in natural (alphabetical) order. Sorted order: [Amsterdam, Berlin, Lisbon, Madrid, Zurich] headSet("Madrid") returns elements strictly less than "Madrid". Therefore, the result is [Amsterdam, Berlin, Lisbon]. See more: Collections
Question 11 MEDIUM
Which of the following methods of java.util.function.Predicate are default methods? (Choose all that apply)
Select all that apply
The default methods in Predicate are and(), negate(), and or(). test(T t) is an abstract method. isEqual() and not() are static methods. Therefore, the correct answers are and(), negate(), and or(). See more: Streams & Lambdas
Question 12 MEDIUM
Given: public class AdvancedCalc extends BaseCalc implements Extra { public static void main(String[] args) { System.out.println(new AdvancedCalc().compute()); } int compute() { return value - bonus; } } class BaseCalc { int value = 5; } interface Extra { int bonus = 3; } What is printed?
The class BaseCalc defines instance field value = 5. The interface Extra defines bonus = 3, which is implicitly public static final. In compute(), value refers to the inherited instance variable (5), and bonus refers to the interface constant (3). Therefore, 5 - 3 = 2 is printed. See more: OOP & Classes
Question 13 MEDIUM
Which of the following methods compile? (Choose all that apply)
Select all that apply
Option 1 compiles because IllegalArgumentException is a subclass of RuntimeException, and ? extends allows subclasses. Option 2 compiles because Exception is a supertype of RuntimeException, and ? super allows supertypes. Option 3 does not compile because Exception is not a subtype of RuntimeException. Option 4 does not compile because IllegalArgumentException is not a supertype of RuntimeException. Therefore, the correct answers are getList1 and getList2. See more: OOP & Classes
Question 14 MEDIUM
How would you create a ConcurrentHashMap configured with an initial capacity of 32, a load factor of 0.75, and a concurrency level of 8? Which of the following options meets this requirement?
The constructor ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) allows specifying all three values. Therefore, new ConcurrentHashMap(32, 0.75f, 8) is correct. The other options either provide incorrect parameter order or missing parameters. See more: Concurrency
Question 15 MEDIUM
Given: interface Device { boolean isOn(); } class Laptop implements Device { boolean power; boolean isOn() { power = power; return power; } } Choose the correct statement.
Interface methods are implicitly public. Therefore, isOn() in Device is public. When implementing the method in Laptop, it must also be declared public. Since the implementation omits the public modifier, the code fails to compile due to attempting to assign weaker access privileges. See more: OOP & Classes
Question 16 MEDIUM
Given: String animals = "cat " + "dog " + "bird "; Which text block can replace the above code?
The original string explicitly includes the newline escape sequence ( ) after each word. In a text block, pressing Enter automatically inserts a newline character. However, the formatting and indentation must exactly match the original string. None of the provided text blocks match the exact sequence: "cat " + "dog " + "bird ". Therefore, the correct answer is: None of the propositions. See more: Data Types & Variables
Question 17 MEDIUM
Given: DoubleSummaryStatistics stats1 = new DoubleSummaryStatistics(); stats1.accept(2.0); stats1.accept(6.0); DoubleSummaryStatistics stats2 = new DoubleSummaryStatistics(); stats2.accept(4.0); stats2.accept(8.0); stats1.combine(stats2); System.out.println("Sum: " + stats1.getSum() + ", Max: " + stats1.getMax() + ", Avg: " + stats1.getAverage()); What is printed?
stats1 contains 2.0 and 6.0. stats2 contains 4.0 and 8.0. After stats1.combine(stats2), stats1 contains all four values: 2.0, 6.0, 4.0, 8.0. Sum = 2 + 6 + 4 + 8 = 20.0 Max = 8.0 Average = 20.0 / 4 = 5.0 Therefore, the correct answer is: Sum: 20.0, Max: 8.0, Avg: 5.0. See more: Streams & Lambdas
Question 18 MEDIUM
Given: public class Container { String message = "Hello"; class Inner { void print() { System.out.println(message); } } public static void main(String[] args) { Container c = new Container(); Inner i = new Inner(); // Line 1 i.print(); // Line 2 } } What happens?
Inner is a non-static inner class. It requires an instance of the outer class to be created. Correct instantiation would be: Container.Inner i = c.new Inner(); Since Line 1 tries to instantiate Inner without referencing the outer instance, compilation fails at Line 1. See more: OOP & Classes
Question 19 MEDIUM
Given: import java.io.*; class X implements Serializable { int value = 10; } class Y implements Serializable { int value = 20; } public class Test { public static void main(String[] args) throws Exception { File file = new File("data.ser"); X obj = new X(); var out = new ObjectOutputStream(new FileOutputStream(file)); out.writeObject(obj); out.close(); var in = new ObjectInputStream(new FileInputStream(file)); Y result = (Y) in.readObject(); in.close(); System.out.println(result.value); } } What is the program's output?
An object of type X is serialized and written to the file. During deserialization, the program attempts to cast the object to type Y. Since X and Y are unrelated classes, this results in a ClassCastException at runtime. Therefore, the correct answer is ClassCastException. See more: Java I/O API
Question 20 MEDIUM
Given: public class Test { public static void main(String[] args) { try { throw new IllegalArgumentException(); } catch (IllegalArgumentException e) { throw new RuntimeException(); } finally { throw new NullPointerException(); } } } What is the output?
The try block throws IllegalArgumentException, which is caught by the catch block. The catch block throws RuntimeException. However, the finally block always executes and throws NullPointerException. The exception thrown in finally overrides any previous exception. Therefore, NullPointerException is the final outcome. See more: Exception Handling
Question 21 MEDIUM
Given: StringBuilder a = new StringBuilder("FR"); StringBuilder b = new StringBuilder("DE"); Stream<StringBuilder> stream = Stream.of(a, b); String result = stream.collect(Collectors.joining("-", "[", "]")); System.out.println(result); What is the output?
Collectors.joining(delimiter, prefix, suffix) concatenates elements using their toString() values. The delimiter is "-", prefix is "[", and suffix is "]". So the result becomes "[FR-DE]". See more: Streams & Lambdas
Question 22 MEDIUM
Given: String s = " "; System.out.print("[" + s.strip() + "]"); s = " world "; System.out.print("[" + s.strip() + "]"); s = " java "; System.out.print("[" + s.strip() + "]"); What is printed?
strip() removes leading and trailing whitespace using Unicode awareness. First case: " " becomes empty string ->[] Second case: " world " becomes "world" ->[world] Third case: " java " becomes "java" ->[java] Therefore, the final output is: [][world][java]. See more: Data Types & Variables
Question 23 MEDIUM
Given: List<String> list = List.of("x", "y", "z"); list.stream() .forEach(s -> { s = s.toUpperCase(); }); list.stream() .forEach(System.out::print); What is the output?
Strings are immutable. Inside the lambda, assigning s = s.toUpperCase() only changes the local lambda parameter, not the original list elements. Since the list remains unchanged, the second stream prints the original values: xyz. See more: Streams & Lambdas
Question 24 MEDIUM
Given: Object value = 10L; String result = switch (value) { case Integer i -> "int"; case Long l -> "long"; case String s -> "string"; default -> "unknown"; }; System.out.println(result); What is printed?
The object value is 10L, which is of type Long. In pattern matching for switch, the first matching case is selected. Since value is a Long, it matches 'case Long l -> "long"'. Therefore, the output is: long. See more: Java 21 New Features
Question 25 MEDIUM
Given: StringBuilder result = Stream.of("x", "y") .collect( () -> new StringBuilder("z"), StringBuilder::append, (a, b) -> b.append(a) ); System.out.println(result); What is the output?
The supplier creates a StringBuilder initialized with "z". The stream processes elements in encounter order (sequential stream): Start: "z" Append "x" ->"zx" Append "y" ->"zxy" In a sequential stream, the combiner is not used. Therefore, the output is: zxy. See more: Streams & Lambdas
Question 26 MEDIUM
Given (assume today's date is 12/31/2024): var now = LocalDate.now(); var f1 = DateTimeFormatter.ISO_LOCAL_DATE; var f2 = DateTimeFormatter.ISO_WEEK_DATE; var f3 = new DateTimeFormatterBuilder() .appendValue(IsoFields.WEEK_BASED_YEAR, 4) .appendLiteral("-W") .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2) .toFormatter(); System.out.println(now.format(REPLACE_HERE)); Which variable prints 2025-W01?
December 31, 2024 belongs to ISO week 1 of week-based year 2025. ISO_WEEK_DATE formats dates using the ISO week-based-year system (YYYY-'W'ww-e). Therefore, f2 prints 2025-W01->day> (for example 2025-W01-2), matching the week-based year 2025. f1 prints the calendar date (2024-12-31). f3 prints 2025-W01 but does not include the day unless explicitly added. The expected week-based representation is produced by ISO_WEEK_DATE, so the correct answer is f2. See more: Data Types & Variables
Question 27 MEDIUM
Given: public class Counter { static int value; synchronized Counter() { value++; } public static void main(String[] args) throws InterruptedException { Runnable task = Counter::new; Thread t1 = new Thread(task); Thread t2 = new Thread(task); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(value); } } What is the program's output?
The constructor is synchronized, but it synchronizes on the instance being created. Since each thread creates a different Counter object, they do not share the same lock. The static field 'value' is shared across instances and incremented without proper class-level synchronization. This can cause a race condition, so the result may be 1 or 2 depending on thread interleaving. Therefore, the correct answer is: It is either 1 or 2. See more: Concurrency
Question 28 MEDIUM
Given: public class ExceptionFlow { public static void main(String[] args) { try { calculate(); System.out.print("Alpha, "); } catch (ArithmeticException e) { System.out.print("Beta, "); } finally { System.out.print("Gamma"); } } static int calculate() { try { int x = 10 / 0; return x; } catch (NullPointerException e) { System.out.print("Delta, "); return -1; } finally { System.out.print("Epsilon, "); } } } What is printed?
In calculate(), 10 / 0 throws ArithmeticException. The catch block does not handle it because it only catches NullPointerException. The finally block executes and prints "Epsilon, ". The ArithmeticException propagates back to main(), where it is caught by the catch block, printing "Beta, ". Finally, the main finally block executes and prints "Gamma". Therefore, the output is: Epsilon, Beta, Gamma. See more: Exception Handling
Question 29 MEDIUM
Given: record ARecord(int x) { int y; // Line 1 } record BRecord(int x) { static int y; // Line 2 } record CRecord(int x) extends RuntimeException {} // Line 3 record DRecord(int x) implements Runnable { public void run() {} } Which records compile? (Choose two.)
Select all that apply
Records cannot declare additional instance fields (Line 1 invalid). All instance fields must be components of the record header. Static fields are allowed in records (Line 2 valid). Records cannot extend other classes because they implicitly extend java.lang.Record (Line 3 invalid). Records can implement interfaces (Line 4 valid). Therefore, BRecord and DRecord compile. See more: Java 21 New Features
Question 30 MEDIUM
Given: Runnable r = () -> System.out.println("Running Runnable"); Callable<String> c = () -> { System.out.println("Running Callable"); return "Done"; }; ExecutorService service = Executors.newSingleThreadExecutor(); // INSERT CODE HERE service.shutdown(); Which of the following statements, inserted in the code above, print BOTH "Running Runnable" and "Running Callable"? (Choose two.)
Select all that apply
execute() accepts Runnable only, so service.execute(c) does not compile. submit() accepts both Runnable and Callable, so service.submit(r) and service.submit(c) both execute successfully. execute(r) and submit(c) also both work. ExecutorService has no run() or call() methods. Therefore, the correct answers are: - service.submit(r); service.submit(c); - service.execute(r); service.submit(c); See more: Concurrency
Question 31 MEDIUM
Which two of the following are NOT valid ways to create a Stream? (Choose two.)
Select all that apply
Stream is an interface and cannot be instantiated directly, so 'new Stream()' is invalid. Stream.generate() returns an infinite stream and requires careful handling, but it is a valid factory method. However, if the question assumes a finite stream creation context without limit(), it is not considered a typical valid creation in exam context. Stream.of(), Stream.empty(), Stream.builder(), and Stream.ofNullable() are all valid ways to create a Stream. Therefore, the correct answers are options A and C. See more: Streams & Lambdas
Question 32 MEDIUM
Given: var _ = 5; var $ = 9; System.out.println(_ + $); What is printed?
Since Java 9, a single underscore (_) cannot be used as an identifier. Therefore, 'var _ = 5;' causes a compilation error. Hence, the program does not compile. See more: Data Types & Variables
Question 33 MEDIUM
Which of the following java.io.Console methods does NOT exist?
java.io.Console includes readLine(), readLine(String, Object...), readPassword(), readPassword(String, Object...), and writer(). However, Console does not have a print(String) method. Printing is done using writer() or format()/printf(). Therefore, print(String s) does not exist. See more: Java I/O API
Question 34 MEDIUM
Given: Optional<Integer> o1 = Optional.empty(); Optional<Integer> o2 = Optional.of(5); Optional<Integer> o3 = Stream.of(o1, o2) .filter(Optional::isPresent) .findFirst() .flatMap(o -> o); System.out.println(o3.orElse(10)); What is the output?
The stream contains o1 (empty) and o2 (Optional.of(5)). filter(Optional::isPresent) removes o1, leaving only o2. findFirst() returns Optional<Optional<Integer>> containing o2. flatMap(o -> o) unwraps it into Optional<Integer> with value 5. Therefore, o3.orElse(10) prints 5. See more: Streams & Lambdas
Question 35 MEDIUM
Given: // File 1 package zoo.animal; public class Animal { protected String name = "Lion"; } // File 2 package zoo.caretaker; import zoo.animal.Animal; public class Keeper extends Animal { public static void main(String[] args) { Animal a = new Animal(); a.name = "Tiger"; System.out.println(a.name); } } What happens?
The field 'name' is protected in Animal. Protected members are accessible: - Within the same package, or - In subclasses, but only through inheritance (not via a reference of the superclass type in another package). Here, Keeper is in a different package and accesses the field using a reference of type Animal (a.name). This is not allowed. Therefore, compilation fails. See more: OOP & Classes
Question 36 MEDIUM
Which of the following methods compile? (Choose all that apply)
Select all that apply
FileNotFoundException is a subclass of IOException, so it fits '? extends IOException' (m1 compiles). Exception is a supertype of IOException, so it fits '? super IOException' (m2 compiles). Exception is not a subtype of IOException, so m3 does not compile. FileNotFoundException is not a supertype of IOException, so m4 does not compile. Therefore, the correct answers are m1 and m2. See more: OOP & Classes
Question 37 MEDIUM
Given: public class Sample { static int total; synchronized Sample() { total++; } public static void main(String[] args) throws InterruptedException { Runnable task = Sample::new; Thread t1 = new Thread(task); Thread t2 = new Thread(task); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(total); } } What is the program's output?
The constructor is synchronized, but synchronization happens on the instance being created. Each thread creates a different Sample object, so they do not share the same lock. The static field 'total' is shared across instances and incremented without class-level synchronization, causing a race condition. Depending on thread scheduling, the final result may be 1 or 2. Therefore, the correct answer is: It is either 1 or 2. See more: Concurrency
Question 38 MEDIUM
Given: ExecutorService service = Executors.newSingleThreadExecutor(); Runnable task = () -> System.out.println("Done"); service.submit(task); service.shutdown(); service.submit(task); What happens when executing the given code fragment?
The first submit() executes normally. After shutdown() is called, the ExecutorService stops accepting new tasks. The second submit() throws RejectedExecutionException. Therefore, "Done" is printed once, and then an exception is thrown. See more: Concurrency
Question 39 MEDIUM
Given: interface X { default void m1() {} } interface Y extends X { static void m2() {} } interface Z extends Y { void m1(); void m3(); } interface W extends Z { void m4(); } interface V extends W { default void m1() {} default void m3() {} } Which interface can be the target of a lambda expression?
A lambda can target a functional interface, meaning an interface with exactly one abstract method. X has no abstract methods (only default). Y has no abstract methods (inherits default and adds static). Z has two abstract methods (m1 and m3). W has three abstract methods (m1, m3, m4). V provides default implementations for m1 and m3, leaving only m4 abstract. Therefore, V has exactly one abstract method and is a functional interface. Correct answer: V. See more: Streams & Lambdas
Question 40 MEDIUM
Given: var map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put(3, "C"); Does the code compile?
When using var with new HashMap<>(), the compiler infers HashMap<Object, Object> because no type parameters are provided. Therefore, both String and Integer keys/values are allowed. The code compiles successfully. Correct answer: True. See more: Data Types & Variables
Question 41 MEDIUM
Given: var deque = new ArrayDeque<Integer>(); deque.add(10); deque.add(20); deque.add(30); deque.add(40); System.out.print(deque.peek() + " "); System.out.print(deque.poll() + " "); System.out.print(deque.pop() + " "); System.out.print(deque.element() + " "); What is printed?
Initial deque: [10, 20, 30, 40] peek() returns head without removing ->10 poll() removes and returns head ->10 (deque becomes [20, 30, 40]) pop() removes and returns head ->20 (deque becomes [30, 40]) element() returns head without removing ->30 Therefore, the output is: 10 10 20 30. See more: Collections
Question 42 MEDIUM
Given: Object input = 3.14; String result = switch (input) { case String s -> "It's a string: " + s; case Integer i -> "It's an integer: " + i; case Double d -> "It's a double: " + d; }; System.out.println(result); What is printed?
The input object is 3.14, which is of type Double. Pattern matching for switch selects the first matching case. The case Double d matches and returns "It's a double: 3.14". Therefore, the correct output is: It's a double: 3.14. See more: Java 21 New Features
Question 43 MEDIUM
Given: var text = """ Line one Line two Line three """; for (int i = 0; i <= 3; i++) { System.out.println(text.lines() .toList() .get(i)); } What happens?
The text block contains three lines: "Line one", "Line two", and "Line three". text.lines().toList() creates a list with exactly 3 elements (indices 0, 1, 2). The loop runs from i = 0 to i = 3 inclusive (4 iterations). When i = 3, get(3) causes IndexOutOfBoundsException. Therefore, it prints the first three lines and then throws an exception. See more: Data Types & Variables
Question 44 MEDIUM
Given: public class Demo { class Inner {} static class Nested {} public static void main(String[] args) { // Insert here } } Which three of the following are valid statements when inserted into the main method?
Select all that apply
Inner is a non-static inner class and requires an instance of Demo to be created. Therefore, 'new Demo().new Inner()' is valid. Nested is a static nested class and can be instantiated using Demo.Nested. Inside a static method, you cannot directly instantiate Inner without an enclosing instance. Thus, valid statements are: - Nested n = new Demo.Nested(); - Inner i = new Demo().new Inner(); - Demo.Nested n = new Demo.Nested(); See more: OOP & Classes
Question 45 MEDIUM
Which three of the following statements are correct about the Java Platform Module System? (Choose three.)
Select all that apply
Named modules must explicitly declare 'requires' to access another named module's exported packages. The unnamed module exports all its packages. Split packages across named modules cause a resolution error. Code in a named module cannot access types in the unnamed module by default. A module descriptor is optional; applications can still run on the classpath without modules. Therefore, the correct answers are options C, E, and F. See more: Modules & Packaging
Question 46 MEDIUM
Which of the following statements is correct about a final class?
A final class cannot be extended by any other class. The final keyword appears before the class keyword. A final class does not need to contain any final methods. A final class can implement interfaces and can extend another class (unless that class is final). Therefore, the correct answer is: A final class cannot be subclassed. See more: OOP & Classes
Question 47 MEDIUM
Given: DoubleSummaryStatistics s1 = new DoubleSummaryStatistics(); s1.accept(1.5); s1.accept(2.5); DoubleSummaryStatistics s2 = new DoubleSummaryStatistics(); s2.accept(3.0); s2.accept(4.0); s1.combine(s2); System.out.println("Sum: " + s1.getSum() + ", Max: " + s1.getMax() + ", Avg: " + s1.getAverage()); What is printed?
s1 contains 1.5 and 2.5. s2 contains 3.0 and 4.0. After combine, s1 contains all four values: 1.5, 2.5, 3.0, 4.0. Sum = 1.5 + 2.5 + 3.0 + 4.0 = 11.0 Max = 4.0 Average = 11.0 / 4 = 2.75 Therefore, the correct answer is: Sum: 11.0, Max: 4.0, Avg: 2.75. See more: Streams & Lambdas
Question 48 MEDIUM
Given: public class Demo implements AutoCloseable { public static void main(String[] args) { try (Demo d = new Demo()) { System.out.print("start "); throw new Exception(); } catch (Exception e) { System.out.print("catch "); } } @Override public void close() throws Exception { System.out.print("close "); throw new RuntimeException(); } } What is printed?
Inside the try block, "start " is printed and an Exception is thrown. Before control transfers to catch, close() is automatically called. close() prints "close " and throws a RuntimeException. The original Exception from the try block is the primary exception, and the RuntimeException from close() is suppressed. The catch block handles the original Exception and prints "catch ". Therefore, the output is: start close catch. See more: Exception Handling
Question 49 MEDIUM
Given: String block = """ X Y Z """; System.out.println(block.length()); What is the output?
A text block automatically includes newline characters at the end of each line, including the last line before the closing delimiter. The content is: "X " "Y " "Z " Each letter counts as 1 character and each newline counts as 1. So total length = 3 letters + 3 newline characters = 6. Therefore, the output is 6. See more: Data Types & Variables
Question 50 MEDIUM
Given: DoubleStream stream = DoubleStream.of(1.1, 2.2, 6.6, 7.7); Predicate<Double> p = d -> d > 5; System.out.println(stream.allMatch(p)); What is printed?
DoubleStream.allMatch() expects a DoublePredicate, not a Predicate<Double>. Primitive streams use specialized functional interfaces (DoublePredicate for DoubleStream). Since a Predicate<Double> is provided instead of DoublePredicate, the code does not compile. Therefore, the correct answer is: Compilation fails. See more: Streams & Lambdas
Question 51 MEDIUM
Given: var count = 1; do { System.out.print(count + " "); } while (count++ < 3); What is printed?
Initial count = 1. First iteration: prints 1. Condition checks 1 < 3 ->true, then count becomes 2. Second iteration: prints 2. Condition checks 2 < 3 ->true, then count becomes 3. Third iteration: prints 3. Condition checks 3 < 3 ->false, then count becomes 4. Loop ends. Therefore, the output is: 1 2 3. See more: Control Flow
Question 52 MEDIUM
Given: Map<String, Integer> map = Map.of("z", 3, "x", 1, "y", 2); TreeMap<String, Integer> tree = new TreeMap<>(map); System.out.println(tree); What is the output of the given code fragment?
TreeMap sorts entries by natural ordering of keys. Keys are "z", "x", and "y". Alphabetical order is: x, y, z. Therefore, the output is: {x=1, y=2, z=3}. See more: Collections
Question 53 MEDIUM
Given: void check(Object obj) { boolean enabled = false; assert enabled = true; assert enabled; System.out.println(obj.toString()); assert obj != null; } When does this method throw a NullPointerException?
The line assert enabled = true; assigns true to enabled when assertions are enabled. If assertions are disabled, both assert statements are ignored and enabled remains false. The call obj.toString() happens before the final assertion. If obj is null, obj.toString() throws NullPointerException regardless of assertion state. However, if assertions are enabled and obj is null, the final assert obj != null would fail first, throwing AssertionError before reaching any later code. Therefore, NullPointerException occurs only if assertions are disabled and obj is null. See more: Control Flow
Question 54 MEDIUM
What is the output of the following snippet? (Assume the file exists) Path path = Paths.get("/usr/local/bin/script.sh"); System.out.println(path.getName(0));
getName(0) returns the first name element of the path, excluding the root. For the path "/usr/local/bin/script.sh": Name elements are: usr, local, bin, script.sh. Index 0 corresponds to "usr". Therefore, the correct answer is: usr. See more: Java I/O API
Question 55 MEDIUM
Given: public class Palace { int rooms; int floors; void Palace() { // Line 1 this.rooms = 10; this.floors = 3; System.out.println("Palace has " + rooms + " rooms."); } public static void main(String[] args) { var p = new Palace(); // Line 2 } } What happens?
Line 1 declares a method named Palace with return type void. It is not a constructor because constructors do not have a return type. Therefore, the class has a default no-argument constructor generated by the compiler. When new Palace() is executed, the default constructor runs and does nothing. The method Palace() is never called. Therefore, nothing is printed. See more: OOP & Classes
Question 56 MEDIUM
Given: final Stream<String> lines = Files.readAllLines(Paths.get("data.csv")).stream(); lines.skip(2) .limit(2) .forEach(System.out::println); And the file data.csv contains: Header1 Header2 Row1 Row2 Row3 Row4 What is printed?
Files.readAllLines() returns a List of all lines in order. The lines are: Header1 (index 0) Header2 (index 1) Row1 (index 2) Row2 (index 3) Row3 (index 4) Row4 (index 5) skip(2) skips Header1 and Header2. Remaining: Row1, Row2, Row3, Row4. limit(2) keeps the first two of those: Row1 and Row2. Therefore, the output is: Row1 Row2. See more: Java I/O API
Question 57 MEDIUM
Consider the following methods to load an implementation of PaymentService using ServiceLoader. Which of the methods are correct? (Choose all that apply)
Select all that apply
ServiceLoader.load(Service.class) returns a ServiceLoader. You can obtain an implementation using iterator().next(). Since Java 9, ServiceLoader also provides findFirst() which returns an Optional. There is no method named getService() or services().getFirstInstance(). Therefore, the correct answers are options A and B. See more: Modules & Packaging
Question 58 MEDIUM
Given: CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>(); list.add(1); list.add(2); list.add(3); // Writer thread new Thread(() -> { list.add(4); System.out.println("Added 4"); }).start(); // Reader thread new Thread(() -> { for (Integer i : list) { System.out.println("Read: " + i); } }).start(); What happens?
CopyOnWriteArrayList creates a snapshot of the array at the time iteration begins. The reader thread iterates over a snapshot, so modifications made by the writer thread during iteration are not reflected in that iteration. No ConcurrentModificationException is thrown. Therefore, original elements are printed, but changes during iteration may not be visible. See more: Concurrency
Question 59 MEDIUM
Which of the following is NOT a correct way to write a string to a file?
FileOutputStream.write() expects a byte[] or int, not a String. The statement out.write("Hello") does not compile because "Hello" is a String. All other options correctly write a string to a file. Therefore, option C is not correct. See more: Java I/O API
Question 60 MEDIUM
Given: int x = 4; int y = 4; int post = x++ + 5; int pre = ++y + 5; System.out.println("post: " + post + ", pre: " + pre + ", final x: " + x + ", final y: " + y); What is printed?
x++ returns 4, then x becomes 5. So post = 4 + 5 = 9. ++y increments y first (to 5), then returns 5. So pre = 5 + 5 = 10. Final values: x = 5, y = 5. Therefore, the correct output is: post: 9, pre: 10, final x: 5, final y: 5. See more: Data Types & Variables
Question 61 MEDIUM
Given: var num = 0; do { System.out.print(num + " "); } while (++num < 3); What is printed?
Initial num = 0. First iteration: prints 0. Condition checks ++num (num becomes 1), 1 < 3 ->true. Second iteration: prints 1. Condition checks ++num (num becomes 2), 2 < 3 ->true. Third iteration: prints 2. Condition checks ++num (num becomes 3), 3 < 3 ->false. Loop ends. Therefore, the output is: 0 1 2. See more: Control Flow
Question 62 MEDIUM
Given: var brands = new String[]{"Gucci", "Prada", "Armani"}; var i = 0; do { System.out.print(brands[i] + " "); } while (i++ > 0); What is printed?
Initial i = 0. First iteration: prints brands[0] ->"Gucci". Condition checks i++ > 0. Since i++ returns 0, the condition is 0 > 0 ->false. After evaluation, i becomes 1. The loop stops after the first iteration. Therefore, the output is: Gucci. See more: Control Flow
Question 63 MEDIUM
Given: String block = """ A B C """; System.out.println(block.length()); What is the output?
Text block content includes: "A\t " ->'A' (1) + tab (1) + newline (1) "B " ->'B' (1) + newline (1) "C " ->'C' (1) + newline (1) Total characters: A (1) Tab (1) Newline (1) B (1) Newline (1) C (1) Newline (1) Total = 7 characters. However, the initial newline after the opening delimiter is also included in the text block. That adds 1 more newline. Total length = 8. Therefore, the correct answer is 8. See more: Data Types & Variables
Question 64 MEDIUM
Which of the following local variable declarations using var are invalid? (Choose four.)
Select all that apply
var requires an initializer and can only declare one variable at a time. Valid: - var a = 10; (type inferred as int) - var arr = new int[3]; (type inferred as int[]) Invalid: - var b = 1, c = 2; (cannot declare multiple variables with var) - var d; (initializer required) - var e = {1, 2, 3}; (array initializer without new is not allowed) - var f = null; (type cannot be inferred from null) Therefore, the correct answers are B, D, E, and F. See more: Data Types & Variables
Question 65 MEDIUM
Given: import java.time.LocalDate; public class Service { public static void main(String[] args) { Service s = new Service(); String a = s.process(); LocalDate d = s.process(); System.out.println(a + " " + d); } public String process() { return "done"; } public LocalDate process() { return LocalDate.now(); } } What happens?
Java does not allow method overloading based only on return type. Both process() methods have the same name and parameter list (no parameters), differing only by return type. This causes a compilation error. Therefore, the correct answer is: Compilation fails. See more: OOP & Classes
Question 66 MEDIUM
Which of the following functional interfaces does NOT exist in java.util.function?
java.util.function provides primitive specializations such as IntSupplier, LongSupplier, and DoubleSupplier, as well as the generic Supplier<T>. There is no CharSupplier functional interface in the standard API. Therefore, the correct answer is CharSupplier. See more: Streams & Lambdas

Take Practice Test 2 →


Popular Posts