61 Practice Questions & Answers
Which of the following statements about sealed classes is correct?
-
A
Sealed classes are implicitly final and cannot have any subclasses.
-
B
Sealed classes can be extended by any class in the same package.
-
C
A sealed class uses the 'sealed' keyword and must specify permitted subclasses.
✓ Correct
-
D
The 'permits' clause is optional when declaring a sealed class.
Explanation
Sealed classes require explicit declaration with 'sealed' keyword and must list all permitted subclasses using the 'permits' clause. The permitted subclasses must be final, sealed, or non-sealed.
What is the purpose of the 'record' keyword introduced in Java 16?
-
A
To create immutable data carrier classes with automatically generated methods like equals(), hashCode(), and toString().
✓ Correct
-
B
To record method invocations for debugging purposes.
-
C
To define a database record mapping for ORM frameworks.
-
D
To create thread-safe collections that store historical data.
Explanation
Records are a special type of class designed to be transparent carriers of immutable data, automatically generating accessors, equals(), hashCode(), and toString() based on the declared fields.
When using pattern matching with instanceof, which statement correctly applies the pattern?
-
A
if (obj instanceof String str) { System.out.println(str.length()); } // str is available in the if block
✓ Correct
-
B
Pattern matching with instanceof requires explicit casting after the instanceof check.
-
C
The pattern variable is scoped to the entire method after the instanceof check.
-
D
if (obj instanceof String str) { System.out.println(str.length()); } // str is NOT available in the if block
Explanation
In pattern matching with instanceof (Java 16+), the pattern variable is automatically declared and available only within the scope where the type check is true, eliminating the need for explicit casting.
What does the 'yield' keyword do in switch expressions?
-
A
It pauses the execution of the switch expression to allow other threads to run.
-
B
It returns a value from a switch expression case or case group.
✓ Correct
-
C
It converts a switch expression to a traditional switch statement.
-
D
It declares a new variable scoped to the switch block.
Explanation
The 'yield' keyword is used in switch expressions (introduced in Java 14) to return a value from a case or case group, replacing the need for 'break' statements in traditional switches.
Which of the following correctly describes module system components in Java?
-
A
Modules are optional; applications function identically with or without module declarations.
-
B
All public classes in a module are automatically accessible to all other modules without explicit export statements.
-
C
The module system applies only to third-party libraries and not to application code.
-
D
A module requires explicit declaration in module-info.java and defines what packages it exports and what other modules it depends on.
✓ Correct
Explanation
Modules require a module-info.java file that explicitly declares module name, exported packages, and required dependencies, providing fine-grained control over encapsulation and visibility.
In a sealed class hierarchy, what is the compile-time effect if a permitted subclass is not marked as final, sealed, or non-sealed?
-
A
A compile error occurs because the subclass must explicitly specify one of these modifiers.
✓ Correct
-
B
The subclass implicitly becomes final.
-
C
The sealing is automatically lifted for that subclass and its descendants.
-
D
The code compiles successfully; the modifier is inferred automatically.
Explanation
Every permitted subclass of a sealed class must explicitly be declared as final, sealed, or non-sealed; the compiler requires one of these modifiers to be present.
What is the correct behavior of the 'var' keyword with local variable type inference?
-
A
'var' can only be used for local variables and must have an initializer to infer the type.
✓ Correct
-
B
'var' can be used for class fields, method parameters, and return types with automatic type detection.
-
C
'var' allows changing the type of a variable at runtime depending on the assigned value.
-
D
'var' is equivalent to using Object and relies on runtime type checking for operations.
Explanation
'var' (introduced in Java 10) is limited to local variables with an initializer; the compiler infers the static type at compile time, and the variable's type cannot change.
Which statement accurately describes text blocks in Java?
-
A
Text blocks cannot contain expressions and are limited to literal string content only.
-
B
Text blocks are syntactic sugar for String concatenation and require escape sequences for special characters.
-
C
Text blocks use triple quotes and preserve formatting including indentation and newlines as written.
✓ Correct
-
D
Text blocks must be on a single line and automatically escape all whitespace characters.
Explanation
Text blocks (Java 15+) are delimited by triple double quotes and preserve whitespace and newlines exactly as written, with automatic indent management to reduce unnecessary leading spaces.
When analyzing a module dependency graph, which scenario would prevent successful compilation?
-
A
A module is declared but no other module depends on it.
-
B
Module A exports package com.example, and another module tries to require the same package.
-
C
Module A requires Module B, and Module B requires Module A (circular dependency).
✓ Correct
-
D
Multiple modules export the same package name if they do not appear together in any module's requires clause.
Explanation
Circular module dependencies are not allowed in the Java module system; the dependency graph must be acyclic for the module system to function correctly.
What is the result of applying multiple pattern matching guards in a switch expression?
-
A
Guards can be combined with boolean operators to create complex matching conditions.
-
B
Only the first guard that evaluates to true is executed; subsequent patterns are not evaluated.
-
C
All guards are evaluated, and the first case with a true guard is executed.
✓ Correct
-
D
Pattern matching guards are not supported; all patterns must match without conditional logic.
Explanation
In switch expressions with pattern matching guards (Java 19+), each case is evaluated in order, and the first pattern whose guard evaluates to true is executed.
Which of the following correctly demonstrates a non-sealed class in a sealed class hierarchy?
-
A
public sealed class Parent { public static class Child extends Parent { } }
-
B
non-sealed cannot be used; all subclasses must be final or sealed.
-
C
public sealed class Parent permits Child { } public class Child extends Parent { }
-
D
public sealed class Parent permits Child { } public non-sealed class Child extends Parent { }
✓ Correct
Explanation
The 'non-sealed' modifier explicitly allows a permitted subclass to have further subclasses, effectively breaking the sealing chain at that level.
What is the scope and lifetime of a pattern variable introduced in a switch case?
-
A
Pattern variables are not type-safe and require explicit casting when used.
-
B
The pattern variable is scoped to the specific case block and inaccessible in other cases.
✓ Correct
-
C
The pattern variable persists after the switch statement ends.
-
D
The pattern variable is available throughout the entire switch statement.
Explanation
Pattern variables in switch cases are scoped to their specific case block; attempting to use them in other cases or outside the switch results in a compilation error.
In the context of Java modules, what does 'requires transitive' accomplish?
-
A
It marks a required module as optional; compilation succeeds even if the module is unavailable.
-
B
It creates a bidirectional dependency between two modules.
-
C
It allows the current module to implicitly depend on transitive dependencies of a required module.
-
D
It makes a required module's public API available to modules that depend on the current module.
✓ Correct
Explanation
'requires transitive' (or 'requires public' in older terminology) makes the transitively required module's exported packages available to any module that depends on the current module.
Which statement about record canonical constructors is accurate?
-
A
A record's canonical constructor must accept exactly one parameter for each record component in declaration order.
✓ Correct
-
B
The canonical constructor must explicitly assign parameters to the corresponding record fields using 'this.field = parameter'.
-
C
The canonical constructor is optional; if omitted, a default no-argument constructor is generated.
-
D
A record can define multiple canonical constructors with different parameter lists.
Explanation
The canonical constructor of a record must have parameters that match the record components in name and type; it is automatically generated if not explicitly defined.
What is the primary advantage of using sealed classes in API design?
-
A
Sealed classes allow library designers to control the inheritance hierarchy and make exhaustiveness guarantees in switch expressions over the permitted subtypes.
✓ Correct
-
B
Sealed classes eliminate the need for access modifiers and provide package-level encapsulation.
-
C
Sealed classes improve runtime performance by allowing JIT compilers to optimize virtual method calls.
-
D
Sealed classes automatically provide thread-safety for all subclass instances.
Explanation
Sealed classes enable library authors to define a closed set of permitted subtypes, which allows switch expressions to be exhaustive without a default case and prevents unexpected subclassing.
Which of the following is a valid module directive that affects module visibility?
-
A
All of the above are valid module directives affecting visibility.
✓ Correct
-
B
'exports' allows other modules to access public types in specified packages.
-
C
'provides' declares the module's implementation of a service interface for service providers.
-
D
'requires' declares dependencies and controls which types are visible within the module.
Explanation
'exports' controls outbound visibility, 'requires' controls inbound dependencies, and 'provides' declares service implementations; all three affect what is visible to other modules.
When defining a record with a component of type List, what is the recommended approach to maintain immutability?
-
A
Use a compact constructor to wrap the List in Collections.unmodifiableList() before assignment.
✓ Correct
-
B
Define a compact constructor that returns a deep copy of the List parameter.
-
C
Records cannot contain collection types due to immutability constraints.
-
D
Use the default accessor; mutable collections are acceptable in records.
Explanation
To maintain record immutability with mutable components like lists, use a compact constructor to wrap them in unmodifiable collections or create defensive copies.
What is the correct syntax for applying a pattern guard in a switch case?
-
A
case String s if (s.length() > 5) -> { System.out.println(s); }
-
B
case String s when s.length() > 5 -> { System.out.println(s); }
✓ Correct
-
C
case (String s) && s.length() > 5 -> { System.out.println(s); }
-
D
case String s, s.length() > 5 -> { System.out.println(s); }
Explanation
Pattern guards use the 'when' keyword followed by a boolean condition; the case only matches if both the pattern and the guard evaluate to true.
In a multi-module project, if Module A exports package 'com.example.api' and Module B requires Module A but tries to access package 'com.example.impl' (not exported), what happens?
-
A
The code compiles successfully; the package access is resolved at runtime.
-
B
A compilation error occurs because 'com.example.impl' is not exported by Module A.
✓ Correct
-
C
The code compiles successfully because both packages are in the same module.
-
D
A warning is issued, but compilation and execution proceed normally.
Explanation
The module system enforces strong encapsulation; attempting to access non-exported packages results in a compile-time error, preventing accidental violations of module boundaries.
What is the behavior of a record's generated equals() method?
-
A
It compares all record components using == for equality testing.
-
B
It delegates to a parent class equals() method regardless of record components.
-
C
It performs reference equality checking (same as the default Object.equals()).
-
D
It compares all record components using their equals() methods if available.
✓ Correct
Explanation
Records generate an equals() method that compares all components using their equals() methods, providing value-based equality semantics appropriate for immutable data carriers.
Which statement about service providers in the module system is correct?
-
A
A module declares service implementations using the 'provides' directive with interface and implementation class names.
✓ Correct
-
B
A module can use 'uses' directive to load service implementations but must know their concrete class names.
-
C
Service interfaces must be defined in the same module that provides their implementations.
-
D
Service providers are automatically discovered at compile time without explicit module declarations.
Explanation
'provides ServiceInterface with ImplementationClass' is the correct directive syntax; it declares that the module provides an implementation of a service interface for discovery by modules using 'uses'.
In pattern matching, what does a record pattern accomplish?
-
A
It validates that an object is an instance of a record class.
-
B
It creates a new record instance by matching against a template record.
-
C
It restricts pattern matching to record types only.
-
D
It allows decomposing a record instance into its components with automatic variable bindings.
✓ Correct
Explanation
Record patterns (Java 19+) enable deconstruction of record instances, automatically binding components to named variables in a single pattern match expression.
What is the effect of the 'transitive' modifier in a 'requires transitive' module directive?
-
A
It requires the module to be physically present at compile time but allows optional runtime presence.
-
B
It enables circular dependencies between modules by allowing bidirectional access.
-
C
It creates a transitive dependency that allows dependent modules to access the transitively required module's exports.
✓ Correct
-
D
It declares that the module's dependencies can change at runtime based on the execution environment.
Explanation
'requires transitive' makes the specified module's exports implicitly available to any module that depends on the current module, establishing transitive visibility in the dependency graph.
Which of the following about compact constructors in records is true?
-
A
A compact constructor must explicitly include a return statement.
-
B
A compact constructor can reassign its parameters to different values.
-
C
A compact constructor receives parameters as final variables with the same names as record components.
✓ Correct
-
D
Record components are assigned to their default values if a compact constructor is defined.
Explanation
A compact constructor is a shorthand syntax that automatically declares parameters matching record components as final variables; the component assignments happen implicitly at the end.
In sealed class design, what compile-time guarantee does the 'permits' clause provide?
-
A
It prevents reflection from discovering subclasses not listed in the permits clause.
-
B
It enables automatic type casting for all permitted subtypes.
-
C
It guarantees that only the listed classes can ever be instantiated in the application.
-
D
It allows the compiler to verify exhaustiveness in switch expressions covering all permitted types.
✓ Correct
Explanation
The 'permits' clause allows switch expressions to be exhaustive; the compiler can verify that all permitted subtypes are covered, eliminating the need for a default case.
Which of the following statements correctly describes the relationship between a superclass and a subclass in Java?
-
A
A superclass automatically inherits all members from its subclass.
-
B
A subclass can extend multiple superclasses using the extends keyword.
-
C
A subclass must implement all abstract methods from its superclass or declare itself as abstract.
-
D
A subclass inherits all public and protected members from its superclass and can override methods.
✓ Correct
Explanation
A subclass inherits public and protected members from its superclass and may override superclass methods. A class can only extend one superclass in Java (single inheritance).
In the context of sealed classes introduced in Java 15, what is the primary purpose of the 'permits' keyword?
-
A
It restricts which classes are allowed to extend or implement a sealed class or interface.
✓ Correct
-
B
It restricts the visibility of sealed class constructors to permitted subclasses only.
-
C
It permits the JVM to optimize method invocation through virtual method tables.
-
D
It grants permission to specific packages to access the sealed class members.
Explanation
The 'permits' keyword specifies exactly which classes are allowed to extend a sealed class or implement a sealed interface, enabling fine-grained control over the inheritance hierarchy.
Which method from the Stream API returns an Optional and is considered a terminal operation?
-
A
map()
-
B
flatMap()
-
C
findFirst()
✓ Correct
-
D
filter()
Explanation
findFirst() is a terminal operation that returns an Optional containing the first element of the stream, or an empty Optional if the stream is empty.
When using the var keyword for local variable type inference in Java 10+, which of the following is a limitation?
-
A
The var keyword requires an explicit initializer so the compiler can infer the type.
✓ Correct
-
B
Variables declared with var are automatically final and cannot be reassigned.
-
C
The var keyword cannot be used with diamond operator syntax when instantiating generic classes.
-
D
Variables declared with var can only be primitives, not reference types.
Explanation
When using var, an initializer must be present because the compiler infers the type from the right-hand side of the assignment. Without an initializer, type inference is impossible.
In Java, what is the effect of calling Thread.yield() on a running thread?
-
A
It pauses the thread indefinitely until notify() is called on the same object.
-
B
It immediately terminates the thread and releases all acquired locks and resources.
-
C
It suggests to the thread scheduler that the current thread is willing to release the CPU to other threads of the same or higher priority.
✓ Correct
-
D
It blocks the thread until all other threads in the application have completed their execution.
Explanation
Thread.yield() is a hint to the scheduler that the current thread is willing to relinquish the CPU. However, the scheduler may ignore this hint, and the behavior is not guaranteed.
Which of the following correctly demonstrates the use of method references with the Stream API?
-
A
stream.map(String::length) processes each element and returns the length of each string.
✓ Correct
-
B
stream.filter(System.out::println) filters elements that successfully print to the console.
-
C
stream.forEach(Object::toString) converts each element to a string and discards the result.
-
D
stream.reduce(Integer::sum) concatenates all integers into a single numeric result without a starting value.
Explanation
String::length is a valid method reference that extracts the length of each string in the stream. This is equivalent to lambda: s -> s.length().
When a checked exception is thrown in a method, what is the correct way to handle it according to Java's exception handling contract?
-
A
Declare the method return type as 'Exception' to satisfy the compiler's checked exception requirements.
-
B
Throw the exception up the call stack using the 'throws' keyword or catch it with a try-catch block.
✓ Correct
-
C
Allow the exception to propagate automatically without any declaration or handling mechanism.
-
D
Convert the checked exception into an unchecked exception using the UncheckedExceptionWrapper class.
Explanation
Checked exceptions must either be caught with a try-catch block or declared in the method signature using the 'throws' keyword. This is enforced at compile time.
What is the purpose of the @FunctionalInterface annotation in Java?
-
A
It enables the interface to be used with all three types of method references: static, instance, and constructor.
-
B
It optimizes the performance of interfaces by eliminating default method resolution overhead.
-
C
It marks a class that contains only final methods and cannot be overridden by subclasses.
-
D
It ensures at compile time that an interface has exactly one abstract method, making it suitable for lambda expressions.
✓ Correct
Explanation
The @FunctionalInterface annotation verifies that the interface has exactly one abstract method, which allows it to be used as a target for lambda expressions and method references.
In the context of Java modules (Project Jigsaw), what does the 'exports' directive in a module-info.java file accomplish?
-
A
It specifies which packages within the module are accessible to other modules that depend on it.
✓ Correct
-
B
It defines transitive dependencies that automatically propagate to all modules that depend on the exporting module.
-
C
It declares that the module requires specific services to be available at runtime through the service loader mechanism.
-
D
It compiles the module and makes it available for deployment in a JAR archive.
Explanation
The 'exports' directive makes specified packages public to other modules. Without an exports directive, packages are encapsulated and not accessible from outside the module.
Which statement accurately describes the behavior of the Enhanced For Loop (for-each) in Java?
-
A
It can only be used with arrays and does not work with collections that implement the Iterable interface.
-
B
It automatically creates a new array internally for each iteration, making it less efficient than traditional loops.
-
C
It requires explicit casting when iterating over elements from a collection of type Object.
-
D
It works with any object that implements the Iterable interface and internally uses an Iterator.
✓ Correct
Explanation
The enhanced for loop works with arrays and any class implementing Iterable. It uses an Iterator internally, providing a clean syntax for iteration over collections.
What is the primary difference between 'notify()' and 'notifyAll()' in the context of Java's wait-notify mechanism?
-
A
notifyAll() interrupts the execution of waiting threads, while notify() gracefully resumes them.
-
B
Only notifyAll() actually releases the lock held by a thread, while notify() keeps the lock acquired.
-
C
notify() can be called from any thread, but notifyAll() requires the calling thread to hold the object's lock.
-
D
notify() wakes up one random waiting thread, while notifyAll() wakes up all waiting threads competing for the same lock.
✓ Correct
Explanation
notify() arbitrarily wakes one waiting thread, while notifyAll() wakes all waiting threads. Both must be called while holding the object's lock.
In Java, which collection type is most appropriate for maintaining insertion order while providing O(1) average-case lookup by key?
-
A
TreeMap
-
B
ConcurrentHashMap
-
C
LinkedHashMap
✓ Correct
-
D
EnumMap
Explanation
LinkedHashMap maintains insertion order through a doubly-linked list while providing O(1) average-case lookup, combining benefits of HashMap and LinkedList.
When using try-with-resources statement in Java 7+, what must a class implement to be used in the try clause?
-
A
A static close() method annotated with @AutoClose to signal resource cleanup capabilities.
-
B
The Serializable interface to ensure resources can be safely closed across JVM instances.
-
C
The Closeable interface, which is a subtype of AutoCloseable with additional contract requirements.
-
D
The AutoCloseable interface with a close() method that will be automatically invoked.
✓ Correct
Explanation
Any class implementing AutoCloseable can be used in a try-with-resources statement. The close() method is automatically called at the end of the try block, even if exceptions occur.
Which of the following statements about Java's garbage collection is accurate?
-
A
Garbage collection pauses in applications using G1GC are entirely eliminated compared to other collectors.
-
B
Objects become eligible for garbage collection when there are no more strong references to them.
✓ Correct
-
C
Calling System.gc() guarantees immediate garbage collection and memory reclamation.
-
D
The finalize() method is guaranteed to execute before an object is removed from memory.
Explanation
Objects eligible for garbage collection have no strong references pointing to them. System.gc() is merely a suggestion, and finalize() is unreliable and deprecated.
In the context of Java records (Java 14+), which statement is correct?
-
A
Records automatically generate equals(), hashCode(), and toString() methods based on their components.
✓ Correct
-
B
Records can extend other classes and implement interfaces with no restrictions whatsoever.
-
C
All fields in a record are mutable and can be reassigned after instantiation through setter methods.
-
D
Records eliminate the need for constructor declarations and do not allow custom constructors to be defined.
Explanation
Records automatically generate equals(), hashCode(), toString(), and accessor methods for their components. Records are final, implicitly extend Record, and their fields are immutable.
What is the primary purpose of using the instanceof pattern matching operator introduced in Java 16+?
-
A
It allows checking an object's type and casting it in a single expression, eliminating redundant casting code.
✓ Correct
-
B
It enforces that an object must implement a particular interface or extend a specific superclass to proceed.
-
C
It verifies that an object is an instance of a specific class without performing any type casting operations.
-
D
It enables polymorphic behavior by automatically selecting the correct method overload based on runtime type.
Explanation
Pattern matching with instanceof allows type checking and casting in one step: if (obj instanceof String str) { ... uses str directly without separate casting.
Which of the following correctly describes the behavior of default methods in interfaces?
-
A
They are automatically inherited as static methods and cannot access instance variables of implementing classes.
-
B
They provide a default implementation that subclasses must override to customize behavior.
-
C
They can only be declared as public static final and must be invoked on the interface class itself.
-
D
They allow interfaces to provide concrete method implementations while maintaining backward compatibility with existing implementations.
✓ Correct
Explanation
Default methods in interfaces provide a concrete implementation that implementing classes inherit. They maintain backward compatibility when adding new methods to interfaces without breaking existing implementations.
In Java, what is the correct order of execution for the try, catch, and finally blocks?
-
A
If no exception occurs, the catch block is skipped entirely, but finally always executes regardless of whether an exception was thrown.
-
B
finally block is evaluated before the catch block to ensure resources are cleaned up immediately upon exception.
-
C
try block executes first; if an exception occurs, the catch block executes; finally block always executes last.
✓ Correct
-
D
The order depends on whether the exception is checked or unchecked; checked exceptions follow different execution paths than unchecked exceptions.
Explanation
The try block executes first. If an exception occurs and matches a catch block, that catch executes. The finally block always executes last, regardless of whether an exception was thrown or caught.
Which of the following best describes the purpose of the 'volatile' keyword when applied to a field in Java?
-
A
It ensures that reads and writes to the field are visible to all threads and prevents compiler optimizations that would cache the value in registers.
✓ Correct
-
B
It automatically synchronizes access to the field, providing mutual exclusion equivalent to using the synchronized keyword.
-
C
It indicates that the field's value may change unexpectedly and should be treated as immutable by the compiler.
-
D
It prevents garbage collection of objects referenced by the field.
Explanation
The volatile keyword ensures visibility of changes across threads and prevents caching optimizations, but does not provide atomicity or mutual exclusion like synchronized does.
When using Java's Stream API, what is the difference between intermediate and terminal operations?
-
A
Intermediate operations transform the stream without producing a final result, while terminal operations produce a result and close the stream.
✓ Correct
-
B
Intermediate operations require explicit memory allocation, while terminal operations use stack-based execution for efficiency.
-
C
Terminal operations are always executed before intermediate operations regardless of their order in the code.
-
D
Intermediate operations are executed immediately, while terminal operations are deferred until the stream is closed.
Explanation
Intermediate operations (map, filter) return a stream and enable chaining, while terminal operations (collect, forEach) consume the stream and return a final result, triggering execution.
In the context of Java generics, what is the purpose of wildcard type parameters with upper bounds (e.g., ? extends Number)?
-
A
They restrict method parameters to accept only subclasses of the specified bound, improving type safety.
-
B
They allow the compiler to generate multiple type-specific versions of generic classes at compile time.
-
C
They enable covariance by allowing a generic type parameter to accept a type or any of its subtypes.
✓ Correct
-
D
They prevent the use of raw types and ensure that all generic parameters are explicitly specified.
Explanation
Upper-bounded wildcards (? extends Type) enable covariance, allowing a method to accept arguments of the specified type or any subtype, while restricting write operations.
What does the 'super' keyword accomplish when used in the context of generic type parameters (e.g., ? super Number)?
-
A
It refers to the direct superclass of a generic type and enables method calls on the superclass.
-
B
It forces the compiler to check that all type parameters are properly inherited from the specified supertype.
-
C
It establishes a lower bound on the wildcard, enabling contravariance by accepting the specified type or any supertype.
✓ Correct
-
D
It allows generic classes to inherit behaviors from multiple superclasses without violating type safety rules.
Explanation
Lower-bounded wildcards (? super Type) establish contravariance, allowing a parameter to accept the specified type or any supertype, enabling writes while restricting reads.
In Java, which of the following statements about static methods is correct?
-
A
Static methods can be overridden in subclasses to provide polymorphic behavior similar to instance methods.
-
B
Static methods can only access other static members of the class and cannot reference instance variables or methods.
-
C
Static methods automatically become final and cannot be accessed from outside the class that declares them.
-
D
Static methods are bound at compile time and cannot be overridden; attempting to override them results in method hiding.
✓ Correct
Explanation
Static methods are resolved at compile time using the reference type, not the runtime type. When a subclass defines a static method with the same signature, it hides the superclass method rather than overriding it.
What is the primary advantage of using Spliterator over Iterator in Java's Stream API?
-
A
Spliterator automatically handles checked exceptions that Iterator cannot manage.
-
B
Spliterator reduces memory consumption by storing only the index of the next element to be processed.
-
C
Spliterator enables parallelization by allowing streams to be split into sub-streams for concurrent processing.
✓ Correct
-
D
Spliterator provides lazy evaluation of stream elements, computing values only when needed.
Explanation
Spliterator supports the split() method, enabling efficient parallel stream processing by dividing the source into independent sub-streams that can be processed concurrently.
In Java, what is the effect of declaring a method as synchronized at the method level versus using synchronized blocks within the method?
-
A
Method-level synchronization cannot be used with instance methods, only with static methods or constructors.
-
B
Method-level synchronization locks the entire method, while synchronized blocks provide finer-grained control by locking only specific code sections.
✓ Correct
-
C
Synchronized blocks are more performant because they lock fewer resources compared to method-level synchronization.
-
D
There is no functional difference; both approaches lock the same monitor and provide identical synchronization guarantees.
Explanation
Method-level synchronization locks the entire method execution, while synchronized blocks lock only the specified section, allowing unsynchronized code to execute, resulting in finer-grained control and better performance.
Which statement correctly describes how the Double-Checked Locking pattern relates to the volatile keyword in Java?
-
A
The volatile keyword ensures that changes to the instance variable are visible to all threads without requiring a second lock check.
-
B
The volatile keyword is unnecessary in double-checked locking because synchronized blocks provide all necessary memory visibility guarantees.
-
C
The volatile keyword allows double-checked locking to work with multiple instance variables simultaneously without performance penalties.
-
D
Double-checked locking without volatile on the instance variable can fail to ensure proper visibility due to compiler optimizations and CPU caching.
✓ Correct
Explanation
Without volatile, double-checked locking can fail because the first null check might see a partially constructed object due to instruction reordering. Using volatile prevents this by ensuring visibility of the complete initialization.
Which of the following statements about sealed classes in Java is correct?
-
A
Sealed classes are abstract by default and cannot be instantiated.
-
B
Sealed classes can be extended by any class that is in the same package.
-
C
The permits clause is optional; if omitted, all subclasses in the module are automatically permitted.
-
D
A sealed class must explicitly list the classes permitted to extend it using the permits keyword.
✓ Correct
Explanation
Sealed classes require explicit declaration of permitted subclasses using the 'permits' keyword. The permits clause is mandatory and specifies exactly which classes may extend the sealed class.
What is the output of the following code?
var list = List.of(1, 2, 3);
list.stream()
.peek(System.out::println)
.filter(x -> x > 1)
.forEach(System.out::print);
-
A
23
-
B
1\n2\n3\n23
✓ Correct
-
C
2\n3
-
D
1\n2\n3\n2 3
Explanation
The peek() operation is executed on all elements (1, 2, 3) printing each on a new line. Then filter reduces the stream to (2, 3), and forEach prints them without newlines.
Which interface should you implement to create a custom record component validator in Java records?
-
A
Serializable
-
B
You cannot validate records; they are immutable by design.
-
C
RecordValidator
-
D
You can use a compact constructor to validate record components.
✓ Correct
Explanation
Records support compact constructors that allow validation of components without explicitly listing parameters. A compact constructor automatically assigns validated values to the record fields.
What will be the result of executing the following code?
var optional = Optional.of("hello");
var result = optional
.map(String::toUpperCase)
.filter(s -> s.length() > 10)
.orElse("default");
-
A
default
✓ Correct
-
B
An exception is thrown because filter fails on an empty Optional.
-
C
HELLO
-
D
hello
Explanation
The map() converts "hello" to "HELLO", but filter(s -> s.length() > 10) fails because "HELLO" has length 5, resulting in an empty Optional. orElse() returns "default".
Which of the following best describes the purpose of the @FunctionalInterface annotation?
-
A
It marks an interface as suitable for use in the Stream API.
-
B
It automatically generates functional methods for the interface.
-
C
It enables lambda expressions to be used with annotated interfaces.
-
D
It is a compile-time check ensuring the interface has exactly one abstract method.
✓ Correct
Explanation
The @FunctionalInterface annotation is a compile-time check that verifies an interface has exactly one abstract method, enabling it to be used as a lambda target type. Without the annotation, lambda compatibility still works if the single abstract method rule is met.
In the context of the Module System, what is the primary purpose of the requires transitive directive in a module-info.java file?
-
A
It marks a dependency as optional and only loads it if needed.
-
B
It allows a module to re-export the public types of its dependencies.
✓ Correct
-
C
It declares a dependency that is private and internal to the module.
-
D
It enables reflection access to internal module classes.
Explanation
The 'requires transitive' directive indicates that any module depending on the current module also implicitly depends on the transitive dependency, effectively re-exporting it.
What is the output of the following code?
var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.putIfAbsent("a", 3);
System.out.println(map.get("a"));
-
A
null
-
B
An exception is thrown.
-
C
3
-
D
1
✓ Correct
Explanation
The putIfAbsent() method only inserts a value if the key is not already present. Since "a" exists with value 1, putIfAbsent() does not overwrite it, so get("a") returns 1.
Which of the following correctly describes the behavior of the var keyword with respect to null initialization?
-
A
var x = null; causes a compile error because the type cannot be inferred.
✓ Correct
-
B
var x = null; is valid and x has type null, a special Java type.
-
C
var x = null; is valid and x has type Object.
-
D
var x = null; is valid and x has type Void.
Explanation
The var keyword requires type inference from an initializer expression. A null literal provides no type information, so the compiler cannot infer the type and compilation fails.
When using the instanceof operator with pattern matching, what is guaranteed about the variable declared in the pattern?
-
A
The variable is in scope only within the if block.
-
B
The variable is guaranteed to hold a value of the specified type only in code paths where the instanceof check passed.
✓ Correct
-
C
The variable must be explicitly cast before use.
-
D
The variable shadows any outer variable with the same name permanently.
Explanation
Pattern matching with instanceof introduces a binding variable that is type-checked and only accessible in scopes where the pattern match succeeded, eliminating the need for explicit casting.
Which statement about the java.time API is correct?
-
A
Instant is a human-readable date-time and should be used in business logic.
-
B
LocalDate and LocalTime are mutable to allow direct field modifications.
-
C
LocalDateTime is timezone-aware and should be used for storing user event times.
-
D
ZonedDateTime represents an instant in time with timezone information and is immutable.
✓ Correct
Explanation
ZonedDateTime is immutable and represents a specific instant with timezone context. LocalDateTime lacks timezone info (use it for local times only), Instant is a machine timestamp, and java.time types are all immutable by design.