Courseiva

CCNA Utilizing Java Object-Oriented Approach Questions

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

1
MCQhard

Refer to the exhibit. What is the result of compiling and running the Test class?

A.Runtime exception because drive() is not accessible.
B.Prints "Car engine started" followed by "Car is moving".
C.Compilation error because Car does not implement all abstract methods.
D.Compilation error at line 9 because Vehicle does not have a drive() method.
AnswerD

The reference type is Vehicle, which does not define drive().

Why this answer

The reference type of the variable `v` is `Vehicle`, and the `Vehicle` interface does not declare a `drive()` method. Since the compiler checks the reference type for method availability, calling `v.drive()` results in a compilation error, even though the actual object is a `Car` that has a `drive()` method.

Exam trap

Oracle often tests the distinction between compile-time reference type checking and runtime polymorphism, trapping candidates who assume that the actual object's methods are always accessible through any reference variable.

How to eliminate wrong answers

Option A is wrong because the error occurs at compile time, not runtime; the accessibility of `drive()` is irrelevant since the compiler cannot find the method on the `Vehicle` reference type. Option B is wrong because the code never compiles, so no output is produced. Option C is wrong because `Car` does implement all abstract methods from `Vehicle` (if any), but the issue is that `drive()` is not defined in `Vehicle` at all, not that it is abstract.

2
MCQmedium

Refer to the exhibit. What is the result of compiling and running the Main class?

A.Runtime exception because makeSound() is not accessible.
B.Compilation error because Dog does not override makeSound().
C.Compilation error at line 8 because makeSound() has protected access.
D.Prints "Some sound".
AnswerC

The protected method makeSound() is not accessible from a different package unless through inheritance. Main is not a subclass of Animal.

Why this answer

The `makeSound()` method in the `Animal` class has `protected` access, and the `Dog` class is in a different package. In Java, a `protected` member is accessible only within the same package or through inheritance in a subclass, but only if the access is via a reference of the subclass type. In the `Main` class, the reference is of type `Animal` (line 8), not `Dog`, so the compiler cannot access the `protected` method from a different package, resulting in a compilation error.

Exam trap

Oracle often tests the subtle rule that `protected` access from a different package requires the reference type to be the subclass itself, not the superclass, leading candidates to mistakenly think inheritance alone is sufficient.

How to eliminate wrong answers

Option A is wrong because the issue is a compile-time error, not a runtime exception; `protected` access is checked by the compiler. Option B is wrong because `Dog` does not need to override `makeSound()` to compile; it inherits the method, but the error occurs in `Main` when trying to call it via an `Animal` reference. Option D is wrong because the code does not compile, so no output is produced.

3
MCQmedium

Refer to the exhibit. What is the output?

A.Class implementation
B.Runtime exception due to conflicting methods.
C.Compilation error because show() is default in interface and cannot be overridden.
D.Interface default
AnswerA

The overridden method in MyClass is called, not the default method from the interface.

Why this answer

When a class implements an interface that provides a default method, the class can override that default method with its own implementation. In this case, the class provides a concrete implementation of the `show()` method, which takes precedence over the interface's default method. Therefore, the output is 'Class implementation'.

Exam trap

The trap here is that candidates may think default methods in interfaces cannot be overridden, confusing them with static methods or final methods, or they may incorrectly assume that a conflict between a default method and a class method causes a runtime exception.

How to eliminate wrong answers

Option B is wrong because there is no conflict between the interface's default method and the class's overriding method; the class's method simply overrides the default, so no runtime exception occurs. Option C is wrong because a default method in an interface can be overridden by a class; the `default` keyword only provides a default implementation, not a final one, so overriding is allowed. Option D is wrong because the class's own implementation of `show()` is invoked, not the interface's default method, due to the rules of method overriding in Java.

4
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.

5
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
1Step 1
2Step 2
3Step 3
4Step 4

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().

6
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

The correct matches are Predicate -> boolean test(T), Consumer -> void accept(T), Supplier -> T get(). Common confusions involve swapping method signatures between interfaces.

7
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

A record in Java implicitly provides a canonical constructor that accepts all the components declared in the record header and initializes them. This constructor is generated by the compiler unless a custom canonical constructor is explicitly defined, ensuring that all component fields are set upon instantiation.

Exam trap

The trap here is that candidates often confuse records with regular classes and assume they can be abstract, extend other classes, or add extra instance fields, but the Java language explicitly restricts records to be final, to extend only java.lang.Record, and to have all instance fields derived from the component list.

8
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

Refactors Logger to be an interface and uses dependency injection, allowing clients to pass any implementation. This adheres to the Open/Closed Principle because new destinations can be added by creating new classes implementing Logger without modifying existing code. Option C (using an enum with abstract methods) violates OCP because adding a new destination requires modifying the enum.

Option A (keeping static methods and adding new ones) also requires modification of the Logger class. Option D (abstract class with subclasses and factory) still requires modifying the factory when adding new destinations, reducing flexibility.

9
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

In a sealed class hierarchy, the `permits` clause must list all direct subclasses. If `Triangle` extends `Shape` but is not listed in the `permits` clause of `Shape`, the compiler will report an error. The sealed class mechanism enforces that only explicitly permitted subclasses may extend the sealed class.

Exam trap

The trap here is that candidates often overlook the requirement that every direct subclass of a sealed class must be explicitly listed in the `permits` clause, assuming that simply extending the sealed class is sufficient.

How to eliminate wrong answers

Option B is wrong because `Circle` does not need to be declared `final`; it can be `sealed`, `non-sealed`, or `final`, but the error here is unrelated to `Circle`'s declaration. Option C is wrong because `Shape` is already declared `sealed`, which implicitly makes it abstract, so no explicit `abstract` modifier is required. Option D is wrong because the code does not compile due to the missing `Triangle` in the `permits` clause.

10
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.

11
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

Correct. The `non-sealed` modifier allows further subclassing, which is a valid implementation of a permitted subclass of a sealed class.

Why this answer

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`.

12
MCQhard

Refer to the exhibit. What is the output?

A.10 20 30
B.30 20 10
C.20 30 10
D.30 10 20
AnswerB

Why this answer

The code uses a Deque (ArrayDeque) and calls push() to add elements, which adds them to the front of the deque (LIFO order). The for-each loop iterates from the head (first) to the tail (last), so it prints 30, 20, 10. Option B is correct because push() behaves like a stack, and iteration follows the deque's head-to-tail order.

Exam trap

The trap here is that candidates confuse push() with add() (which adds to the tail) and assume the iteration order matches insertion order, rather than recognizing that push() places elements at the front for LIFO access.

How to eliminate wrong answers

Option A is wrong because it assumes the elements are printed in the order they were added (FIFO), but push() adds to the front, not the end. Option C is wrong because it suggests a mixed order that does not correspond to either LIFO or FIFO behavior; it might arise from misunderstanding that push() adds to the tail. Option D is wrong because it reverses the iteration order, as if the for-each loop traversed from tail to head, which it does not.

13
MCQmedium

Given the exhibit, which statement about calling this method is true?

A.It must be called using the `new` keyword.
B.It can only be called from a static context, not from an instance.
C.It can be called as `ClassName.getEmpName(101)`.
D.It cannot be used because it contains a loop.
AnswerC

Correct. Static methods are called on the class, e.g., `ClassName.methodName()`.

Why this answer

A static method can be called directly on the class without creating an instance. The method `getEmpName` is static and returns a value, so it can be invoked as `ClassName.getEmpName(101)`. Instance methods require an object reference, and non-static methods cannot be called in a static context without an instance.

Exam trap

Java often tests the misconception that any method that performs I/O or database operations cannot be called directly, but the restriction is about modifying state (side effects) in contexts like lambdas, not about reading data. Here, the key is that the method is static, not that it contains a SELECT statement.

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.

14
MCQhard

Refer to the exhibit. What is the output?

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

Why this answer

The code uses `equals()` on two `String` objects with the same content ("Test"), which returns `true`. The second `println` uses `==` to compare the same two `String` references; since both reference the same string literal from the string pool, `==` also returns `true`. Thus both lines print `true`.

Exam trap

Oracle certification questions often test the distinction between `equals()` (content comparison) and `==` (reference comparison) with string literals, trapping candidates who assume `==` always returns `false` for distinct variables without considering string interning.

How to eliminate wrong answers

Option A is wrong because the code compiles without error — both `equals()` and `==` are valid operators for `String` objects. Option C is wrong because `==` on two identical string literals returns `true`, not `false`, due to string interning. Option D is wrong because `equals()` on two strings with identical content returns `true`, not `false`.

15
MCQmedium

Refer to the exhibit. Given the following code: ```java 1: sealed interface Shape permits Circle { } ... 10: class Circle implements Shape { } ``` 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

Why this answer

In Java 17, when a sealed interface (like `Shape`) declares a `permits` clause listing permitted subclasses (e.g., `Circle`), each permitted subclass must explicitly declare itself as `sealed`, `non-sealed`, or `final`. If the `Circle` class is defined as `class Circle implements Shape` without any of these modifiers, compilation fails at line 10 where that class is defined. The error is that the class is not allowed to extend/implement the sealed interface unless it has the required modifier.

Exam trap

Candidates often overlook the mandatory modifier (`sealed`, `non-sealed`, or `final`) on each permitted subclass of a sealed type. Even if the class is logically final (e.g., all methods are final or the class is implicitly final), the Java compiler requires an explicit keyword.

How to eliminate wrong answers

Option A is wrong because a permitted subclass does not need to have its own `permits` clause — only a sealed class/interface needs `permits`. Option C is wrong because the code never compiles, so no runtime exception occurs. Option D is wrong because the code fails to compile due to the missing required modifier on the permitted subclass.

16
MCQhard

Refer to the exhibit. What is the result?

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

Why this answer

The code compiles and runs without error. The object referenced by a1 is a Dog instance. The code first calls the bark() method, which prints 'Bark' (defined in Dog).

Then it calls the play() method, which is not overridden in Dog, so it invokes the inherited play() method from Animal, printing 'Playing'. Therefore, the output is 'Bark' followed by 'Playing', which matches option B.

Exam trap

The trap here is that candidates may think the `play()` method must be overridden in `Dog` to be called, or that the output would be only 'Bark' because they overlook the inherited method call, leading them to choose option D.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; there is no syntax error or missing method issue. Option C is wrong because no runtime exception occurs; the `bark()` method is available on the `Dog` object, and the cast is not needed since the reference type is already `Dog`. Option D is wrong because it omits the 'Playing' output; the `play()` method is inherited and called before `bark()`, so both lines are printed.

17
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

Why this answer

The provided Singleton implementation uses double-checked locking without declaring the instance variable as volatile. Without volatile, the JVM may reorder instructions such that a thread reads a non-null reference to a partially constructed object, leading to a race condition. This is a classic pitfall in Java concurrency.

Exam trap

Oracle often tests the misconception that volatile is unnecessary in double-checked locking. Without volatile, instruction reordering can expose a partially constructed object, even with synchronized blocks.

How to eliminate wrong answers

Option A is wrong because the `volatile` keyword is necessary to ensure visibility of the instance across threads and to prevent the instruction reordering that can occur in double-checked locking. Option C is wrong because the implementation is not fully thread-safe due to the potential for instruction reordering, which can expose a partially constructed object to other threads. Option D is wrong because the constructor must be private to enforce the singleton pattern; a public constructor would allow multiple instances to be created, breaking the singleton guarantee.

18
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

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.

19
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

`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.

20
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.

21
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.

22
MCQhard

Refer to the exhibit. What is the most direct way to fix the compilation error without changing the access modifier of the field?

A.Change line 14 to System.out.println(emp.getName());
B.Move the main method to another class in the same package.
C.Import the class in the same file and create a subclass.
D.Change line 14 to System.out.println(emp.name); and make the field protected.
AnswerA

Using the public getter method getName() accesses the private field correctly.

Why this answer

The compilation error is caused by attempting to access a private field `name` directly via `emp.name` from a different class. The most direct fix without changing the access modifier is to use the public getter method `getName()`, which provides controlled access to the private field. This adheres to encapsulation principles and resolves the visibility issue.

Exam trap

Oracle often tests the misconception that moving code to the same package or using inheritance can bypass `private` access, but the trap here is that `private` members are strictly class-local and cannot be accessed from any other class, regardless of package or subclass relationship, unless a public accessor method is used.

How to eliminate wrong answers

Option B is wrong because moving the `main` method to another class in the same package does not change the fact that the private field `name` is still inaccessible from outside its own class; private members are not visible to any other class, even within the same package. Option C is wrong because importing the class and creating a subclass does not grant access to a private field; private members are not inherited and cannot be accessed by subclasses. Option D is wrong because it suggests changing the access modifier to `protected` (which is not allowed per the question's constraint) and still uses direct field access `emp.name`, which would only work if the field were `public` or if accessed within the same package or via inheritance; the option incorrectly implies that `protected` alone would fix the issue from a different class without subclassing.

23
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

This statement is true because a sealed class restricts which classes may extend it by using the `permits` clause to list the allowed subclasses.

Why this answer

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.

24
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.

25
MCQhard

What is a key difference between a class and an interface in Java?

A.A class cannot be used in inheritance.
B.A class can contain instance variables, while an interface cannot.
C.An interface is automatically updated when the implementing class changes.
D.An interface can be instantiated directly.
AnswerB

Correct. A class can contain instance variables, while an interface cannot.

Why this answer

Classes can have instance variables (state), while interfaces cannot (they only declare method signatures and constants). This is a fundamental Java OOP concept.

Exam trap

Candidates might think that interfaces can have instance variables in Java 8+ with default methods, but interfaces still cannot have instance variables.

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.

26
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.

27
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

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.

28
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

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.

29
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

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.

30
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

The Sub class overrides the print() method from Super and does not call super.print(). Therefore, when Sub's print() is executed, it only prints "World" without printing "Hello". The output is simply "World".

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.

31
MCQhard

Refer to the exhibit. What is the result?

A.Prints 10
B.Runtime exception because Inner class is not static.
C.Compilation error because x is private.
D.Prints 0 because x is not initialized in Inner.
AnswerA

Inner class can access private members of the outer class.

Why this answer

The code accesses the private field `x` of the `Outer` class from within the `Inner` class, which is a member inner class. In Java, a non-static inner class has access to all members (including private fields) of its enclosing outer class. The `Inner` class's `printX()` method directly accesses `Outer.this.x`, which is initialized to 10 in the `Outer` constructor, so it prints 10.

Exam trap

The trap here is that candidates mistakenly think private members are inaccessible to inner classes, or that the inner class must be static to access outer class fields, but Java's member inner classes have full access to all members of the enclosing class, including private ones.

How to eliminate wrong answers

Option B is wrong because the `Inner` class does not need to be static to access the outer class's private field; a non-static inner class has implicit access to the outer class's private members. Option C is wrong because `x` being private does not cause a compilation error; private members are accessible within the same top-level class, and the inner class is part of the outer class. Option D is wrong because `x` is initialized to 10 in the `Outer` constructor before `printX()` is called, so it is not uninitialized.

Ready to test yourself?

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