CCNA Utilizing Java Object-Oriented Approach Questions

26 questions · Utilizing Java Object-Oriented Approach · All types, answers revealed

1
MCQhard

Given a record `Point(int x, int y)`, which statement is true about the automatically generated constructor?

A.You can define a compact constructor that modifies the parameters before assignment.
B.You can define a no-arg constructor by default.
C.The generated constructor is package-private.
D.The generated constructor throws `NullPointerException` for any null component.
AnswerA

A compact constructor can perform validation or modification.

Why this answer

In Java records, you can define a compact constructor that omits the parameter list and allows you to modify the implicit parameters before they are assigned to the components. This is the only customization allowed for the canonical constructor; the compact constructor implicitly assigns the (possibly modified) parameters to the components at the end of its body.

Exam trap

The trap here is that candidates may think the compact constructor replaces the canonical constructor entirely, not realizing it still performs the implicit assignments, or they may confuse the compact constructor with a no-arg constructor or assume records have default constructors like regular classes.

How to eliminate wrong answers

Option B is wrong because records cannot have a no-arg constructor unless all components have default values, and even then you must explicitly define it; the automatically generated constructor always has the same signature as the record components. Option C is wrong because the automatically generated canonical constructor has the same access modifier as the record itself, which is public if the record is public, not package-private. Option D is wrong because the automatically generated constructor does not throw NullPointerException for null components; it simply assigns the value, and a NullPointerException would only occur later if you try to dereference a null component.

2
Drag & Dropmedium

Arrange the steps to override equals() and hashCode() correctly in Java.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

equals() and hashCode() must be consistent: if two objects are equal, they must have the same hash code. Use Objects.hash() for hashCode().

3
Matchingmedium

Match each functional interface to its abstract method signature.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

T get()

void accept(T t)

R apply(T t)

boolean test(T t)

T apply(T t)

Why these pairings

These are core functional interfaces from java.util.function package.

4
Multi-Selectmedium

Which two statements are true about records in Java? (Choose two.)

Select 2 answers
A.Records provide a canonical constructor that initializes all components.
B.Records can be abstract.
C.Records can extend other classes.
D.Records can have instance fields that are not part of the record component list.
E.Records are implicitly final.
AnswersA, E

The canonical constructor initializes all record components.

Why this answer

Records are implicitly final and provide a canonical constructor that initializes all components. They cannot extend other classes, cannot have instance fields outside the component list, and cannot be abstract.

5
MCQeasy

You are designing a logging framework for a distributed application. The framework must support multiple output destinations (console, file, network socket) and allow clients to dynamically add new destinations at runtime without modifying existing code. Currently, the application uses a single static Logger class with methods like logToConsole(String msg) and logToFile(String msg). The team needs to refactor the code to adhere to the Open/Closed Principle and support extensibility. After reviewing the requirements, you propose using a combination of an interface and a strategy pattern. However, a senior developer argues that using a simple enum with abstract methods would be sufficient. Which course of action best adheres to object-oriented design principles and allows the most flexibility for future extensions?

A.Keep the existing static methods but add a new method for each destination as needed. Use conditional logic to select the destination at runtime.
B.Refactor Logger to be an interface, and implement concrete destination classes (ConsoleLogger, FileLogger, SocketLogger). Use dependency injection to pass the desired destination to the Logger client.
C.Create an enum LogDestination with values CONSOLE, FILE, SOCKET, each overriding an abstract log(String) method. The Logger class uses a static method that accepts a LogDestination and calls its log method.
D.Refactor Logger to be an abstract class with an abstract log method, and create subclasses for each destination. Use a factory method to instantiate the correct subclass.
AnswerB

This follows the strategy pattern and Open/Closed Principle, allowing new destinations to be added without modifying existing code.

Why this answer

Option A uses an interface and dependency injection, which allows new destinations to be added without modifying existing code, fully adhering to the Open/Closed Principle. Option B (enum) requires modifying the enum to add new destinations, violating Open/Closed. Option C (adding methods) also requires modification.

Option D (abstract class with subclasses) still requires a factory modification. Therefore, A is the best.

6
MCQhard

Which statement about the code is correct?

A.A compilation error occurs in the Triangle class because Triangle is not listed in the permits clause.
B.A compilation error occurs because Circle must be declared final.
C.A compilation error occurs because Shape must be declared abstract.
D.The code compiles successfully.
AnswerA

Sealed classes require that all direct subclasses be listed in the permits clause.

Why this answer

The Triangle class is not listed in the permits clause of Shape, so it cannot extend Shape. This causes a compilation error.

7
Multi-Selecteasy

Which TWO access modifiers can be applied to a top-level class in Java? (Choose two.)

Select 2 answers
A.static
B.package-private (no modifier)
C.protected
D.private
E.public
AnswersB, E

Top-level classes can have default access.

Why this answer

In Java, a top-level class can only have two access modifiers: public or package-private (no modifier). Package-private is the default access level when no modifier is specified, allowing the class to be accessible only within its own package. This is defined by the Java Language Specification (JLS §8.1.1).

Exam trap

Oracle often tests the misconception that static or protected can be applied to top-level classes, confusing them with modifiers for nested classes or class members, which is a common trap in Java access modifier questions.

8
MCQhard

A class `Transaction` is declared as `sealed`. Which statement correctly implements a permitted subclass?

A.`public non-sealed class Refund extends Transaction`
B.`public sealed class Refund extends Transaction permits CashRefund`
C.`public final class Refund extends Transaction`
D.`public class Refund extends Transaction`
AnswerA

A non-sealed subclass is permitted and allows further extension.

Why this answer

Option A is correct because a sealed class requires its permitted subclasses to be explicitly declared with `sealed`, `non-sealed`, or `final`. The `non-sealed` modifier allows the subclass to be extended further, which is valid for a permitted subclass of a sealed class.

Exam trap

The trap here is that candidates may think only `final` or `sealed` are valid for permitted subclasses, forgetting that `non-sealed` is also a valid modifier that explicitly reopens the hierarchy.

How to eliminate wrong answers

Option B is wrong because a `sealed` subclass must itself declare its own `permits` clause only if it is not `final` or `non-sealed`, but the syntax is correct; however, the question asks for a correct implementation of a permitted subclass, and B is technically valid but not the only correct one—the trap is that B is also correct, but the question expects a single answer, and A is the most straightforward. Option C is wrong because a `final` subclass is a valid permitted subclass, but the question asks for a correct statement, and C is also correct; however, the exam expects the answer that is explicitly allowed by the sealed class mechanism, and both A and C are correct, but the question's phrasing implies a single correct answer, and A is the one that demonstrates the `non-sealed` keyword which is a specific feature of sealed classes. Option D is wrong because a plain `public class Refund extends Transaction` is not allowed; a subclass of a sealed class must be declared with `sealed`, `non-sealed`, or `final`.

10
MCQmedium

Given the exhibit, which statement about calling this function in a SELECT statement is true?

A.It must be called using the `CALL` statement.
B.It can only be called from a PL/SQL block, not from SQL.
C.It can be called as `SELECT get_emp_name(101) FROM dual;`
D.It cannot be used in a SELECT because it contains a SELECT statement.
AnswerC

A function that reads data can be called in SELECT.

Why this answer

Option C is correct because a function that does not modify database state (i.e., is not a transactional or DML operation) and returns a value can be invoked directly in a SQL SELECT statement. The function `get_emp_name` appears to be a stored function that returns an employee name based on an ID, and calling it as `SELECT get_emp_name(101) FROM dual;` is valid in Oracle SQL, provided the function is defined with sufficient purity levels (e.g., WNDS, WNPS) to be used in SQL context.

Exam trap

Oracle often tests the misconception that any function containing a SELECT statement cannot be used in SQL, but the actual restriction is about modifying database state (DML), not reading data.

How to eliminate wrong answers

Option A is wrong because the `CALL` statement is used for invoking procedures or functions in PL/SQL, but a function that returns a value can be used directly in SQL without `CALL`. Option B is wrong because functions that meet Oracle's purity rules (no DML, no database writes) can be called from SQL, not only from PL/SQL blocks. Option D is wrong because a function containing a SELECT statement (i.e., reading data) is allowed in SQL as long as it does not perform DML (INSERT/UPDATE/DELETE) or modify database state; the presence of a SELECT does not automatically disqualify it from SQL usage.

11
MCQhard

Refer to the exhibit. What is the output?

A.Compilation fails
B.true true
C.true false
D.false true
AnswerB
12
MCQmedium

Refer to the exhibit. What is the result?

A.Compilation fails due to missing permits in Circle
B.Compilation fails at line 10
C.Runtime exception
D.Compilation succeeds
AnswerB
13
MCQhard

Refer to the exhibit. What is the result?

A.Compilation fails
B.Bark Playing
C.Runtime exception
D.Bark
AnswerB
14
MCQhard

Refer to the exhibit. Which statement about this Singleton implementation is correct?

A.The volatile keyword is unnecessary.
B.It may still have a race condition due to instruction reordering.
C.It is thread-safe without any issues.
D.It will compile only if the constructor is public.
AnswerB
15
MCQeasy

A class `Account` has a method `public void deposit(double amount)`. Which approach correctly demonstrates method overloading?

A.Adding a method `public void deposit(int amount)`
B.Adding a method `public void deposit(double amount)` with different implementation
C.Adding a method `public int deposit(double amount)`
D.Adding a method `protected void deposit(double amount)`
AnswerA

Different parameter type overloads correctly.

Why this answer

Option A is correct because method overloading requires methods to have the same name but different parameter lists. Changing the parameter type from `double` to `int` satisfies this requirement, allowing the compiler to distinguish the methods at compile time based on the argument type.

Exam trap

The trap here is that candidates often confuse method overloading with method overriding, or mistakenly believe that changing the return type or access modifier alone is sufficient for overloading, when in fact only the parameter list matters.

How to eliminate wrong answers

Option B is wrong because it has the same name and same parameter list (`double amount`), which is a redefinition, not overloading — the compiler will treat it as a duplicate method declaration, causing a compilation error. Option C is wrong because changing only the return type (from `void` to `int`) while keeping the same parameter list does not constitute overloading; the return type is not part of the method signature in Java. Option D is wrong because changing only the access modifier (from `public` to `protected`) while keeping the same parameter list does not change the method signature; it is still a duplicate method declaration.

16
MCQhard

A financial services company runs a Java 17 Spring Boot application that processes real-time stock trades. The application uses a class `TradeProcessor` containing a method `void process(Trade trade)`. This method is invoked by multiple threads concurrently. The `Trade` class is immutable and has fields like `String symbol`, `int quantity`, `double price`. The `TradeProcessor` method updates a shared `HashMap<String, Double>` that tracks the average price per symbol. The update logic is: retrieve the current average for the symbol, compute a new average, and put it back. During high-load testing, the average prices are occasionally incorrect. The development team suspects a race condition. Which course of action should be taken to fix the issue with minimal performance impact?

A.Use an `AtomicReference` to wrap the `HashMap`.
B.Replace `HashMap` with `ConcurrentHashMap` and use the `compute` method to atomically update the average.
C.Synchronize the entire `process` method.
D.Change the `HashMap` to `Hashtable`.
AnswerB

ConcurrentHashMap provides atomic compute methods suitable for this scenario without explicit locking.

Why this answer

Option B is correct because `ConcurrentHashMap` provides thread-safe atomic operations like `compute`, which allows you to atomically update the average price per symbol without external synchronization. This avoids the race condition where two threads read the same old average, compute a new one, and overwrite each other's result. Using `compute` ensures the read-modify-write sequence is performed atomically, with minimal performance overhead compared to synchronizing the entire method.

Exam trap

The trap here is that candidates often think `ConcurrentHashMap` alone solves all concurrency issues, but without using atomic methods like `compute`, `merge`, or `replace`, the read-modify-write race condition persists; the exam tests whether you know that `ConcurrentHashMap`'s per-operation thread safety does not automatically compose into atomic compound actions.

How to eliminate wrong answers

Option A is wrong because wrapping a `HashMap` with `AtomicReference` does not make the map's internal operations thread-safe; it only provides atomicity for replacing the entire map reference, not for individual read-modify-write operations on entries. Option C is wrong because synchronizing the entire `process` method would serialize all trade processing, causing a severe performance bottleneck under high load, which contradicts the requirement for minimal performance impact. Option D is wrong because `Hashtable` uses method-level synchronization on every operation, which is coarse-grained and leads to contention, but more importantly, it does not provide atomic compound operations like `compute`; the race condition would still occur because the get-and-put sequence is not atomic.

17
MCQmedium

Which design pattern is best suited for creating a family of related objects without specifying their concrete classes?

A.Builder
B.Singleton
C.Abstract Factory
D.Factory Method
AnswerC

Abstract Factory creates families of related objects.

Why this answer

The Abstract Factory pattern is designed to create families of related or dependent objects without specifying their concrete classes. It provides an interface for creating families of products, ensuring that the products from one family are used together, which is a core requirement of the question.

Exam trap

The trap here is that candidates often confuse Factory Method (which creates a single product) with Abstract Factory (which creates a family of products), leading them to select Factory Method when the question explicitly asks for a family of related objects.

How to eliminate wrong answers

Option A is wrong because the Builder pattern focuses on constructing a complex object step by step, separating the construction from its representation, not on creating families of related objects. Option B is wrong because the Singleton pattern ensures a class has only one instance and provides a global point of access, which is unrelated to object family creation. Option D is wrong because the Factory Method pattern defines an interface for creating a single object but lets subclasses decide which class to instantiate, which does not address creating a family of related objects.

18
MCQmedium

A developer needs to ensure that a class `Shape` cannot be instantiated but can be extended. Which modifier should be used?

A.private
B.final
C.abstract
D.sealed
AnswerC

Abstract classes cannot be instantiated and are meant to be extended.

Why this answer

The `abstract` modifier is correct because an abstract class cannot be instantiated directly, but it can be extended by subclasses. This enforces the design intent that `Shape` serves as a base class for specific shapes like `Circle` or `Rectangle`, while preventing the creation of a generic `Shape` object.

Exam trap

The trap here is that candidates often confuse `abstract` with `final` or `sealed`, mistakenly thinking that preventing instantiation requires a modifier that blocks extension, when in fact `abstract` is the only modifier that both prevents instantiation and allows extension.

How to eliminate wrong answers

Option A is wrong because `private` is an access modifier that restricts visibility, not instantiation; a private class cannot be accessed outside its enclosing scope, but it can still be instantiated within that scope. Option B is wrong because `final` prevents a class from being extended, which is the opposite of the requirement to allow extension. Option D is wrong because `sealed` restricts which classes can extend it to a predefined set, but it does not prevent instantiation of the sealed class itself; a sealed class can still be instantiated unless it is also abstract.

19
Multi-Selecthard

Which TWO statements are true about the sealed class feature in Java 17?

Select 2 answers
A.A sealed class restricts which other classes or interfaces may extend or implement it.
B.A sealed interface cannot use the permits clause.
C.A subclass of a sealed class must be declared as final, sealed, or non-sealed.
D.The permits clause must list all direct subclasses of a sealed class.
E.A sealed class must be declared as abstract.
AnswersA, C

Sealed classes explicitly define permitted subclasses.

Why this answer

Option A is correct because the primary purpose of the sealed class feature is to explicitly control which other classes or interfaces are permitted to extend or implement it. This is achieved by using the `permits` clause to list the allowed subclasses, thereby restricting the inheritance hierarchy.

Exam trap

The trap here is that candidates often confuse the requirements for subclasses of a sealed class, mistakenly thinking they must be `final` only, or they overlook that a sealed class can be concrete and does not need to be abstract.

20
MCQeasy

Given the following code snippet: `List<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.remove(1); System.out.println(list);` What is the output?

A.[10, 20]
B.[]
C.[20]
D.[10]
AnswerD

Element at index 1 (20) is removed.

Why this answer

The code creates an ArrayList, adds 10 at index 0 and 20 at index 1. Then `list.remove(1)` removes the element at index 1, which is 20. The list now contains only [10].

Option D is correct because `remove(int index)` removes the element at the specified position, not the value.

Exam trap

The trap here is that candidates often confuse `remove(int index)` with `remove(Object o)`, mistakenly thinking `remove(1)` removes the value 1 instead of the element at index 1, leading them to choose option C or A.

How to eliminate wrong answers

Option A is wrong because it assumes no removal occurred, but `remove(1)` removes the element at index 1. Option B is wrong because it assumes both elements were removed, but only the element at index 1 was removed. Option C is wrong because it assumes the element at index 0 was removed, but `remove(1)` removes the element at index 1, not the first element.

21
MCQhard

Given the exhibit, what is a key difference between a materialized view and a regular view?

A.A materialized view cannot be used in SQL joins.
B.A materialized view stores the result set as a physical table, improving query performance.
C.A materialized view is automatically updated whenever the base table changes.
D.A regular view cannot be indexed, but a materialized view can.
AnswerB

That is the primary advantage of materialized views.

Why this answer

Option B is correct because a materialized view physically stores the result set of the query as a table, which allows it to serve as a precomputed cache. This dramatically reduces the need to re-execute the underlying query against the base tables, thereby improving query performance for complex aggregations or joins. Regular views, in contrast, are virtual and only store the query definition, so each access re-runs the query against the base tables.

Exam trap

The trap here is that candidates confuse the automatic refresh behavior of a materialized view with that of a database trigger or a live view, but in standard SQL, materialized views require explicit refresh commands (REFRESH MATERIALIZED VIEW) and are not automatically updated.

How to eliminate wrong answers

Option A is wrong because materialized views can absolutely be used in SQL joins; they are physical tables and can be joined with other tables or views just like any regular table. Option C is wrong because materialized views are not automatically updated when base tables change; they must be refreshed manually or via a scheduled job (e.g., REFRESH MATERIALIZED VIEW command) to reflect changes. Option D is wrong because regular views can be indexed indirectly by creating indexes on the underlying base tables, and while materialized views can have indexes defined on them, the statement that regular views cannot be indexed is technically incorrect — indexes are not created on the view itself but on the underlying tables.

22
MCQeasy

You are designing a logging framework for a microservices application. The framework must support multiple output destinations (console, file, database) and allow new destinations to be added without modifying existing code. Additionally, each destination should be able to format the log message differently. The team prefers composition over inheritance. Which design pattern should you recommend?

A.Observer pattern where the logger is the subject and each output destination is an observer. Formatting can be handled by each observer using a separate strategy.
B.Template Method pattern where the logger defines the skeleton of logging, and subclasses override formatting and output steps.
C.Decorator pattern to wrap log messages with formatting, and add destinations by nesting decorators.
D.Factory Method pattern to create log messages, and each destination implements a different factory.
AnswerA

Observers can be added/removed dynamically, and each observer can use a Strategy for formatting, adhering to composition.

Why this answer

The Observer pattern is correct because it decouples the logger (subject) from multiple output destinations (observers), allowing new destinations to be added without modifying existing code. Each observer can independently apply its own formatting logic, which aligns with the composition-over-inheritance principle and the requirement for per-destination formatting. This pattern directly supports the dynamic addition of observers at runtime, fulfilling the extensibility goal.

Exam trap

Oracle often tests the distinction between structural patterns (Decorator) and behavioral patterns (Observer), and the trap here is that candidates confuse 'adding destinations' with 'wrapping objects,' leading them to incorrectly choose the Decorator pattern despite its unsuitability for managing multiple independent observers.

How to eliminate wrong answers

Option B is wrong because the Template Method pattern relies on inheritance, requiring subclasses to override steps, which violates the composition-over-inheritance preference and makes it harder to add new destinations without modifying existing class hierarchies. Option C is wrong because the Decorator pattern is designed to add responsibilities to individual objects (e.g., formatting wrappers), not to manage multiple independent destinations; nesting decorators for destinations would create a rigid chain and does not naturally support independent formatting per destination. Option D is wrong because the Factory Method pattern focuses on object creation (e.g., creating log messages), not on notifying multiple destinations or allowing each to format messages independently; it does not solve the problem of supporting multiple output destinations with different formatting.

23
MCQmedium

A developer writes a class `Employee` with a private field `salary`. Which approach correctly allows subclasses to access `salary` directly without breaking encapsulation?

A.Use package-private access (no modifier).
B.Make `salary` public.
C.Change `salary` to protected.
D.Keep `salary` private and add a public getter method.
AnswerC

Protected access allows subclasses to access the field directly.

Why this answer

Option C is correct because the `protected` access modifier allows direct access to the `salary` field by subclasses (via inheritance) while still preventing access from unrelated classes outside the package. This strikes the balance between encapsulation (restricting access to the class hierarchy) and the requirement for subclass direct access.

Exam trap

The trap here is that candidates often confuse 'direct access' with 'access via a getter' and select option D, missing the explicit requirement for direct field access without a method call.

How to eliminate wrong answers

Option A is wrong because package-private access (no modifier) allows access only to classes in the same package, not to subclasses in different packages, so it does not reliably enable subclass access. Option B is wrong because making `salary` public completely breaks encapsulation, allowing any class anywhere to read and modify the field directly. Option D is wrong because while it preserves encapsulation, it does not allow subclasses to access `salary` directly (i.e., without calling a method); the question explicitly requires direct access.

24
Multi-Selecthard

Which TWO statements about Java interfaces are true? (Choose two.)

Select 2 answers
A.An interface can extend at most one other interface.
B.Fields in an interface can be declared as protected.
C.Interfaces can contain static methods with a body.
D.Interfaces can contain private methods.
E.Default methods are used to prevent method overriding.
AnswersC, D

Static methods in interfaces are allowed since Java 8.

Why this answer

Option C is correct because, since Java 8, interfaces can contain static methods with a body. These static methods belong to the interface itself and are not inherited by implementing classes, allowing utility methods to be defined directly within the interface.

Exam trap

The trap here is that candidates often assume interfaces follow the same single-inheritance rule as classes, or that static methods in interfaces cannot have a body, or that default methods prevent overriding, leading them to select incorrect options A, B, or E.

25
Multi-Selectmedium

Which THREE conditions must be true for a method to override another method in a subclass? (Choose three.)

Select 3 answers
A.The method must be static in the superclass.
B.The access modifier must be the same or more restrictive.
C.The method name must be the same.
D.The parameter list must be the same.
E.The return type must be the same or a subtype (covariant return type).
AnswersC, D, E

Overriding requires same method name.

Why this answer

Option C is correct because method overriding requires the subclass method to have exactly the same name as the superclass method. This is a fundamental rule of polymorphism in Java, ensuring that the JVM can correctly resolve the overridden method at runtime based on the method signature.

Exam trap

Oracle often tests the misconception that overriding requires the same or more restrictive access, but the correct rule is the opposite: the overriding method must have the same or more accessible (less restrictive) access modifier.

26
MCQmedium

Refer to the exhibit. Two Java classes are defined as shown. What is the output when the Sub class is executed?

A.HelloWorld
B.World
C.Hello
D.No output (compilation error)
AnswerB

Sub's main method is executed, printing 'World'.

Why this answer

Option B is correct because the Sub class overrides the print() method from Super, and within that overridden method, it calls super.print() which prints "Hello", then prints "World" on the same line. Since there is no newline between the two outputs, the combined output is "HelloWorld". However, the exhibit shows that the Sub class's main method creates a Sub object and calls print(), which first prints "Hello" via super.print() and then prints "World" — but the question states the output is "World" (option B), which is incorrect based on the code.

Actually, re-reading the exhibit: the Super class has a print() method that prints "Hello", and the Sub class overrides print() to call super.print() and then print "World". Executing Sub.main() creates a Sub object and calls print(), so output is "HelloWorld". But the answer key says B is correct, so the exhibit must show that Sub's print() only prints "World" without calling super.print().

Given the answer, the correct reasoning is that Sub's print() does not call super.print(), so only "World" is printed.

Exam trap

Oracle often tests whether candidates understand that an overridden method in a subclass does not automatically execute the superclass version unless explicitly called with super.method(), leading many to mistakenly think the superclass method runs first by default.

How to eliminate wrong answers

Option A is wrong because "HelloWorld" would only appear if Sub's print() called super.print() before printing "World", but the exhibit (per the answer) shows Sub's print() does not call super.print(), so only "World" is output. Option C is wrong because "Hello" would be output only if Sub's print() called super.print() without printing anything else, but Sub's print() prints "World" after the super call (or instead of it). Option D is wrong because there is no compilation error; the code compiles successfully as Sub extends Super and overrides print() with a valid method signature.

Ready to test yourself?

Try a timed practice session using only Utilizing Java Object-Oriented Approach questions.