What is the output? record R(int x) implements AutoCloseable { public void close() { System.out.print("close "); } } try (R r = new R(1)) { System.out.print("run "); } finally { System.out.print("finally "); }
-
A
-
B
-
C
-
D
Reveal answer details
Close answer details
Correct answerC
ExplanationThe try-with-resources block invokes AutoCloseable.close() after the try body completes but before finally. Output order: run close finally.
Given: java List<Long> cannesFestivalfeatureFilms = LongStream.range(1, 1945) .boxed() .toList(); try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { cannesFestivalfeatureFilms.stream() .limit(25) .forEach(film -> executor.submit(() -> { System.out.println(film); })); } What is printed?
-
A
Numbers from 1 to 25 sequentially
-
B
Numbers from 1 to 25 randomly
-
C
Numbers from 1 to 1945 randomly
-
D
An exception is thrown at runtime
-
E
Reveal answer details
Close answer details
Correct answerB
ExplanationUnderstanding LongStream.range(1, 1945).boxed().toList(); LongStream.range(1, 1945) generates a stream of numbers from 1 to 1944 . .boxed() converts the primitive long values to Long objects. .toList() (introduced in Java 16) creates an immutable list . Understanding Executors.newVirtualThreadPerTaskExecutor() Java 21 introduced virtual threads to improve concurrency. Executors.newVirtualThreadPerTaskExecutor()creates a new virtual thread per submitted task , allowing highly concurrent execution. Execution Behavior cannesFestivalfeatureFilms.stream().limit(25) # Limits the stream to the first 25 numbers (1 to 25). .forEach(film -> executor.submit(() -> System.out.println(film))) Each film is printed inside a virtual thread. Virtual threads execute asynchronously, meaning numbers arenot guaranteed to print sequentially . Output will contain numbers from 1 to 25, but their order is random due to concurrent execution. Possible Output (Random Order) python-repl The order may differ in each run due to concurrent execution. Thus, the correct answer is:"Numbers from 1 to 25 randomly." References: Java SE 21 - Virtual Threads Java SE 21 - Executors.newVirtualThreadPerTaskExecutor()
Given: java Object myVar = 0; String print = switch (myVar) { case int i -> "integer"; case long l -> "long"; case String s -> "string"; default -> ""; }; System.out.println(print); What is printed?
-
A
-
B
-
C
-
D
-
E
It throws an exception at runtime.
-
F
Reveal answer details
Close answer details
Correct answerF
ExplanationWhy does the compilation fail? The Java switch statement does not support primitive type pattern matching in switch expressions as of Java 21. The case pattern case int i -> "integer"; is invalid because pattern matching with primitive types (like int or long) is not yet supported in switch statements . The error occurs at case int i -> "integer";, leading to a compilation failure . Correcting the Code Since myVar is of type Object, autoboxing converts 0 into an Integer . To make the code compile, we should use Integer instead of int: java Object myVar = 0; String print = switch (myVar) { case Integer i -> "integer"; case Long l -> "long"; case String s -> "string"; default -> ""; }; System.out.println(print); Output: bash integer Thus, the correct answer is:Compilation fails. References: Java SE 21 - Pattern Matching for switch Java SE 21 - switch Expressions
Given: java var lyrics = """ Quand il me prend dans ses bras Qu'il me parle tout bas Je vois la vie en rose """; for ( int i = 0, int j = 3; i < j; i++ ) { System.out.println( lyrics.lines() .toList() .get( i ) ); } What is printed?
-
A
vbnet Quand il me prend dans ses bras Qu'il me parle tout bas Je vois la vie en rose
-
B
-
C
An exception is thrown at runtime.
-
D
Reveal answer details
Close answer details
Correct answerD
ExplanationError in for Loop Initialization The initialization part of a for loopcannot declare multiple variables with different types in a single statement . Error: java for (int i = 0, int j = 3; i < j; i++) { Fix:Declare variables separately: java for (int i = 0, j = 3; i < j; i++) { lyrics.lines() in Java 21 The lines() method of String returns a Stream<String> , splitting the string by line breaks. Calling .toList() on a stream converts it to a list . Valid Code After Fixing the Loop: java var lyrics = """ Quand il me prend dans ses bras Qu'il me parle tout bas Je vois la vie en rose """; for (int i = 0, j = 3; i < j; i++) { System.out.println(lyrics.lines() toList() get(i)); } Expected Output After Fixing: vbnet Quand il me prend dans ses bras Qu'il me parle tout bas Je vois la vie en rose Thus, the correct answer is:Compilation fails. References: Java SE 21 - String.lines() Java SE 21 - for Statement Rules
Which of the following statements are correct?
-
A
You can use 'private' access modifier with all kinds of classes
-
B
You can use 'protected' access modifier with all kinds of classes
-
C
You can use 'public' access modifier with all kinds of classes
-
D
You can use 'final' modifier with all kinds of classes
-
E
Reveal answer details
Close answer details
Correct answerE
Explanation1. private Access Modifier The private access modifier can only be used for inner classes (nested classes). Top-level classes cannot be private. Example of invalid use: java private class MyClass {} // Compilation error Example of valid use (for inner class): java class Outer { private class Inner {} } 2. protected Access Modifier Top-level classes cannot be protected. protectedonly applies to members (fields, methods, and constructors). Example of invalid use: java protected class MyClass {} // Compilation error Example of valid use (for methods/fields): java class Parent { protected void display() {} } 3. public Access Modifier A top-level class can be public , but only one public class per file is allowed . Example of valid use: java public class MyClass {} Example of invalid use: java public class A {} public class B {} // Compilation error: Only one public class per file 4. final Modifier final can be used with classes, but not all kinds of classes . Interfaces cannot be final, because they are meant to be implemented. Example of invalid use: java final interface MyInterface {} // Compilation error Thus, none of the statements are fully correct , making the correct answer: None References: Java SE 21 - Access Modifiers Java SE 21 - Class Modifiers
Given: java Deque<Integer> deque = new ArrayDeque<>(); deque.offer(1); deque.offer(2); var i1 = deque.peek(); var i2 = deque.poll(); var i3 = deque.peek(); System.out.println(i1 + " " + i2 + " " + i3); What is the output of the given code fragment?
-
A
-
B
-
C
-
D
-
E
-
F
-
G
-
H
-
I
Reveal answer details
Close answer details
Correct answerE
ExplanationIn this code, an ArrayDeque named deque is created, and the integers 1 and 2 are added to it using the offer method. The offer method inserts the specified element at the end of the deque. State of deque after offers:[1, 2] The peek method retrieves, but does not remove, the head of the deque, returning 1. Therefore, i1 is assigned the value 1. State of deque after peek:[1, 2] Value of i1:1 The poll method retrieves and removes the head of the deque, returning 1. Therefore, i2 is assigned the value 1. State of deque after poll:[2] Value of i2:1 Another peek operation retrieves the current head of the deque, which is now 2, without removing it. Therefore, i3 is assigned the value 2. State of deque after second peek:[2] Value of i3:2 The System.out.println statement then outputs the values of i1, i2, and i3, resulting in 1 1 2.
Given: java List<String> abc = List.of("a", "b", "c"); abc.stream() .forEach(x -> { x = x.toUpperCase(); }); abc.stream() .forEach(System.out::print); What is the output?
-
A
-
B
-
C
-
D
Reveal answer details
Close answer details
Correct answerA
ExplanationIn the provided code, a list abc is created containing the strings "a", "b", and "c". The first forEach operation attempts to convert each element to uppercase by assigning x = x.toUpperCase();. However, this assignment only changes the local variable x within the lambda expression and does not modify the elements in the original list abc. Strings in Java are immutable, meaning their values cannot be changed once created. Therefore, the original list remains unchanged. The second forEach operation iterates over the original list and prints each element. Since the list was not modified, the output will be the concatenation of the original elements: abc. To achieve the output ABC, you would need to collect the transformed elements into a new list, as shown below: java List<String> abc = List.of("a", "b", "c"); List<String> upperCaseAbc = abc.stream() map(String::toUpperCase) collect(Collectors.toList()); upperCaseAbc.forEach(System.out::print); In this corrected version, the map operation creates a new stream with the uppercase versions of the original elements, which are then collected into a new list upperCaseAbc. The forEach operation then prints ABC.
Which of the following java.io.Console methods does not exist?
-
A
-
B
-
C
-
D
readLine(String fmt, Object... args)
-
E
-
F
readPassword(String fmt, Object... args)
Reveal answer details
Close answer details
Correct answerA
Explanationjava.io.Console is used for interactive input from the console. Existing Methods in java.io.Console reader() # Returns a Reader object. readLine() # Reads a line of text from the console. readLine(String fmt, Object... args) # Reads a formatted line. readPassword() # Reads a password, returning a char[]. readPassword(String fmt, Object... args) # Reads a formatted password. read() Does Not Exist Console does not have a read() method . If character-by-character reading is required, use: java Console console = System.console(); Reader reader = console.reader(); int c = reader.read(); // Reads one character read() is available in Reader , but not in Console . Thus, the correct answer is:read() does not exist. References: Java SE 21 - Console API Java SE 21 - Reader API
Given: java var sList = new CopyOnWriteArrayList<Customer>(); Which of the following statements is correct?
-
A
The CopyOnWriteArrayList class is a thread-safe variant of ArrayList where all mutative operations are implemented by making a fresh copy of the underlying array.
-
B
The CopyOnWriteArrayList class is not thread-safe and does not prevent interference amongconcurrent threads.
-
C
The CopyOnWriteArrayList class's iterator reflects all additions, removals, or changes to the list since the iterator was created.
-
D
The CopyOnWriteArrayList class does not allow null elements.
-
E
Element-changing operations on iterators of CopyOnWriteArrayList, such as remove, set, and add, are supported and do not throw UnsupportedOperationException.
Reveal answer details
Close answer details
Correct answerA
ExplanationThe CopyOnWriteArrayList is a thread-safe variant of ArrayList in which all mutative operations (such as add, set, and remove) are implemented by creating a fresh copy of the underlying array. This design allows for safe iteration over the list without requiring external synchronization, as iterators operate over a snapshot of the array at the time the iterator was created. Consequently, modifications made to the list after the creation of an iterator are not reflected in that iterator. docs.oracle.com Evaluation of Options: Option A:Correct. This statement accurately describes the behavior of CopyOnWriteArrayList. Option B:Incorrect. CopyOnWriteArrayList is thread-safe and is designed to prevent interference among concurrent threads. Option C:Incorrect. Iterators of CopyOnWriteArrayList do not reflect additions, removals, or changes made to the list after the iterator was created; they operate on a snapshot of the list's state at the time of their creation. Option D:Incorrect. CopyOnWriteArrayList allows null elements. Option E:Incorrect. Element-changing operations on iterators, such as remove, set, and add, are not supported in CopyOnWriteArrayList and will throw UnsupportedOperationException.
Question 10
Single choice
What do the following print? java public class Main { int instanceVar = staticVar; static int staticVar = 666; public static void main(String args[]) { System.out.printf("%d %d", new Main().instanceVar, staticVar); } static { staticVar = 42; } }
-
A
-
B
-
C
-
D
Reveal answer details
Close answer details
Correct answerC
ExplanationIn this code, the class Main contains both an instance variable instanceVar and a static variable staticVar. The sequence of initialization and execution is as follows: Static Variable Initialization: staticVar is declared and initialized to 666. Static Block Execution: The static block executes, updating staticVar to 42. Instance Variable Initialization: When a new instance of Main is created, instanceVar is initialized to the current value of staticVar, which is 42. main Method Execution: The main method creates a new instance of Main and prints the values of instanceVar and staticVar. Therefore, the output of the program is 42 42.
Question 11
Single choice
Given: java public class Test { static int count; synchronized Test() { count++; } public static void main(String[] args) throws InterruptedException { Runnable task = Test::new; Thread t1 = new Thread(task); Thread t2 = new Thread(task); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(count); } } What is the given program's output?
-
A
-
B
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerE
ExplanationIn this code, the Test class has a static integer field count and a constructor that is declared with the synchronized modifier. In Java, the synchronized modifier can be applied to methods to control access to critical sections, but it cannot be applied directly to constructors. Attempting to declare a constructor as synchronized will result in a compilation error. Compilation Error Details: The Java Language Specification does not permit the use of the synchronized modifier on constructors. Therefore, the compiler will produce an error indicating that the synchronized modifier is not allowed in this context. Correct Usage: If you need to synchronize the initialization of instances, you can use a synchronized block within the constructor: java public class Test { static int count; Test() { synchronized (Test.class) { count++; } } public static void main(String[] args) throws InterruptedException { Runnable task = Test::new; Thread t1 = new Thread(task); Thread t2 = new Thread(task); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(count); } } In this corrected version, the synchronized block within the constructor ensures that the increment operation on count is thread-safe. Conclusion: The original program will fail to compile due to the illegal use of the synchronized modifier on the constructor. Therefore, the correct answer is E: Compilation fails.
Question 12
Single choice
Which of the following can be the body of a lambda expression?
-
A
-
B
An expression and a statement
-
C
-
D
-
E
Reveal answer details
Close answer details
Correct answerC
ExplanationIn Java, a lambda expression can have two forms for its body: Single Expression:A concise form where the body consists of a single expression. The result of this expression is implicitly returned. Example: java (a, b) -> a + b In this example, (a, b) are the parameters, and a + b is the single expression that adds them together. Statement Block:A more detailed form where the body consists of a block of statements enclosed in braces {}. Within this block, you can have multiple statements, and if a return value is expected, you must explicitly use the return statement. Example: java (a, b) -> { int sum = a + b; System.out.println("Sum is: " + sum); return sum; } In this example, the lambda body is a statement block that performs multiple actions: it calculates the sum, prints it, and then returns the sum. Given the options: A. Two statements:While a lambda body can contain multiple statements, they must be enclosed within a statement block {}. Simply having two statements without braces is not valid syntax for a lambda expression. B. An expression and a statement:Similar to option A, if a lambda body contains more than one element (be it expressions or statements), they need to be enclosed in a statement block. C. A statement block:This is correct. A lambda expression can have a body that is a statement block, allowing multiple statements enclosed in braces. D. None of the above:This is incorrect since option C is valid. E. Two expressions:As with options A and B, multiple expressions must be enclosed in a statement block to form a valid lambda body. Therefore, the correct answer is C: A statement block.
Question 13
Single choice
Given: java Map<String, Integer> map = Map.of("b", 1, "a", 3, "c", 2); TreeMap<String, Integer> treeMap = new TreeMap<>(map); System.out.println(treeMap); What is the output of the given code fragment?
-
A
-
B
-
C
-
D
-
E
-
F
-
G
Reveal answer details
Close answer details
Correct answerF
ExplanationIn this code, a Map named map is created using Map.of with the following key-value pairs: "b": 1 "a": 3 "c": 2 The Map.of method returns an immutable map containing these mappings. Next, a TreeMap named treeMap is instantiated by passing the map to its constructor: java TreeMap<String, Integer> treeMap = new TreeMap<>(map); The TreeMap constructor with a Map parameter creates a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys. In Java, the natural ordering for String keys is lexicographical order. Therefore, the TreeMap will store the entries in the following order: "a": 3 "b": 1 "c": 2 When System.out.println(treeMap); is executed, it outputs the TreeMap in its natural order, resulting in: r {a=3, b=1, c=2}Thus, the correct answer is option F: {a=3, b=1, c=2}.
Question 14
Single choice
Given: java public class SpecialAddition extends Addition implements Special { public static void main(String[] args) { System.out.println(new SpecialAddition().add()); } int add() { return --foo + bar--; } } class Addition { int foo = 1; } interface Special { int bar = 1; } What is printed?
-
A
-
B
-
C
-
D
It throws an exception at runtime.
-
E
Reveal answer details
Close answer details
Correct answerE
Explanation1. Why does the compilation fail? The interface Special contains bar as int bar = 1;. In Java, all interface fields are implicitly public, static, and final. This means that bar is a constant (final variable). The method add() contains bar--, which attempts to modify bar. Since bar is final, it cannot be modified, causing a compilation error . 2. Correcting the Code To make the code compile, bar must not be final. One way to fix this: java class SpecialImpl implements Special { int bar = 1; } Or modify the add() method: java int add() { return --foo + bar; // No modification of bar } Thus, the correct answer is:Compilation fails. References: Java SE 21 - Interfaces Java SE 21 - Final Variables
Question 15
Single choice
Given: java interface Calculable { long calculate(int i); } public class Test { public static void main(String[] args) { Calculable c1 = i -> i + 1; // Line 1 Calculable c2 = i -> Long.valueOf(i); // Line 2 Calculable c3 = i -> { throw new ArithmeticException(); }; // Line 3 } } Which lines fail to compile?
-
A
-
B
-
C
-
D
-
E
-
F
-
G
The program successfully compiles
Reveal answer details
Close answer details
Correct answerG
ExplanationIn this code, the Calculable interface defines a single abstract method calculate that takes an int parameter and returns a long. The main method contains three lambda expressions assigned to variables c1, c2, and c3 of type Calculable. Line 1:Calculable c1 = i -> i + 1; This lambda expression takes an integer i and returns the result of i + 1. Since the expression i + 1 results in an int, and Java allows implicit widening conversion from int to long, this line compiles successfully. Line 2:Calculable c2 = i -> Long.valueOf(i); Here, the lambda expression takes an integer i and returns the result of Long.valueOf(i). The Long.valueOf (int i) method returns a Long object. However, Java allows unboxing of the Long object to a long primitive type when necessary. Therefore, this line compiles successfully. Line 3:Calculable c3 = i -> { throw new ArithmeticException(); }; This lambda expression takes an integer i and throws an ArithmeticException. Since the method calculate has a return type of long, and throwing an exception is a valid way to exit the method without returning a value, this line compiles successfully. Since all three lines adhere to the method signature defined in the Calculable interface and there are no type mismatches or syntax errors, the program compiles successfully.
|