CCNA Java Oop Questions

61 questions · Java Oop topic · All types, answers revealed

1
MCQeasy

Refer to the exhibit. What is the likely cause?

A.The package is missing
B.The variable 'value' is not declared
C.The class name is misspelled
D.The variable 'value' is out of scope
E.The variable 'value' is declared but not initialized
AnswerB

The error indicates that the symbol 'value' cannot be found, meaning it is not declared in the class.

Why this answer

Option B is correct because the error message indicates that the variable 'value' has not been declared before use. In Java, every variable must be declared with a type and name before it can be referenced. The compiler cannot find a declaration for 'value' in the current scope, so it reports a 'cannot find symbol' error, which is the typical symptom of an undeclared variable.

Exam trap

Oracle often tests the difference between 'undeclared', 'out of scope', and 'uninitialized' by presenting an error message that could be interpreted in multiple ways, and the trap is that candidates confuse 'undeclared' with 'out of scope' because both produce a 'cannot find symbol' error, but only the former means the variable was never declared at all.

How to eliminate wrong answers

Option A is wrong because a missing package would cause a compilation error related to the package declaration or import, not a 'cannot find symbol' error for a local variable. Option C is wrong because a misspelled class name would produce a different error, such as 'cannot find symbol' for the class itself, not for a variable named 'value'. Option D is wrong because if 'value' were out of scope, the error would still be 'cannot find symbol', but the question's exhibit shows no declaration at all, making 'undeclared' the precise cause rather than scope.

Option E is wrong because a declared but uninitialized variable would compile (with a warning about potential use before initialization) but would not cause a 'cannot find symbol' error; the compiler would recognize the variable's declaration.

2
MCQmedium

A development team is building a library management system. The system has classes 'LibraryItem', 'Book', and 'DVD'. LibraryItem has a method 'getTitle()' that returns the title. Book and DVD extend LibraryItem. The team wants to ensure that when a LibraryItem is borrowed, a message specific to its type is displayed. They have a 'Borrower' class with a method 'borrow(LibraryItem item)', which currently calls 'item.getTitle()' and prints the title. Now they need to display 'Book borrowed' or 'DVD borrowed' based on the actual item type. They want to avoid using 'instanceof' checks in the 'borrow' method to keep it open for new item types. Which design should they use?

A.Add a String field 'type' to LibraryItem and set it in each subclass constructor. In borrow(), check the field.
B.Use a switch statement on the class name in borrow().
C.Define an abstract method 'getBorrowMessage()' in LibraryItem, and implement it in Book and DVD. Call that method in borrow().
D.Override the 'borrow' method in each subclass and call a different method.
AnswerC

Polymorphism allows new subclasses to define their own message without changing borrow().

Why this answer

Option C is correct because it applies the Open/Closed Principle: LibraryItem defines an abstract getBorrowMessage() method, and each subclass provides its own implementation. The borrow() method calls this polymorphic method without needing instanceof or type checks, so adding new item types (e.g., Magazine) only requires implementing getBorrowMessage() in the new subclass without modifying existing code.

Exam trap

Oracle often tests the Open/Closed Principle by presenting options that appear to work (like a type field or switch on class name) but violate extensibility, tempting candidates to choose a quick fix instead of the polymorphic solution.

How to eliminate wrong answers

Option A is wrong because adding a String field 'type' still requires conditional logic (e.g., if-else or switch) in borrow() to check the field, which violates the goal of avoiding type-specific checks and is not extensible for new types. Option B is wrong because using a switch on the class name is essentially a manual type check that must be updated for every new subclass, breaking the Open/Closed Principle and duplicating logic. Option D is wrong because overriding the borrow() method in each subclass would require the Borrower class to know the concrete type at compile time (e.g., borrower.borrow(book) vs borrower.borrow(dvd)), which defeats the purpose of a polymorphic parameter and couples the caller to specific types.

3
Multi-Selecteasy

Which THREE are fundamental principles of Object-Oriented Programming? (Choose three.)

Select 3 answers
A.Compilation
B.Encapsulation
C.Modularization
D.Inheritance
E.Polymorphism
AnswersB, D, E

Encapsulation bundles data and methods, and hides internal state.

Why this answer

Options A, B, and C are correct. Encapsulation, inheritance, and polymorphism are core OOP principles. Option D is wrong because compilation is a language process, not an OOP principle.

Option E is wrong because modularization is a design concept, not a foundational OOP principle.

4
MCQhard

Refer to the exhibit. What is the output?

A.Bark\n (then throws ClassCastException)
B.Animal sound\n (then throws ClassCastException)
C.Bark\nFetching
D.Animal sound\nFetching
AnswerC

B is correct: polymorphism calls Dog's sound() and cast allows fetch().

Why this answer

Option B is correct: The object is a Dog, so sound() prints "Bark". The cast to Dog is valid, so fetch() prints "Fetching". Option A would occur if sound() were not overridden.

Option C and D are incorrect because no exception is thrown.

5
MCQeasy

A class 'Animal' has a method 'makeSound()'. Subclasses 'Dog' and 'Cat' override it. When calling makeSound() on an Animal reference that actually holds a Dog object, the Dog's version is executed. This is an example of:

A.Static binding
B.Encapsulation
C.Dynamic binding
D.Method overloading
AnswerC

Method call is determined at runtime based on the object's class.

Why this answer

Option A is correct because dynamic binding (runtime polymorphism) resolves method calls based on actual object type. Option B is wrong because static binding happens at compile-time. Option C is wrong because overloading is compile-time.

Option D is wrong because encapsulation does not relate to method dispatch.

6
Multi-Selecthard

A developer wants to achieve loose coupling between components. Which two practices support loose coupling? (Choose two.)

Select 2 answers
A.Using inheritance to share implementation
B.Using private fields with public getters
C.Using interfaces to define contracts
D.Using composition over inheritance
E.Using static methods extensively
AnswersC, D

Correct. Interfaces allow components to interact without knowing concrete classes.

Why this answer

Loose coupling is promoted by coding to interfaces and favoring composition over inheritance, as both reduce dependency on concrete implementations.

7
Multi-Selectmedium

Which THREE are benefits of using inheritance?

Select 3 answers
A.Code reuse
B.Improved security
C.Enables polymorphism
D.Establishes an is-a relationship
E.Reduces memory usage
AnswersA, C, D

Subclasses reuse superclass code.

Why this answer

Option A is correct because inheritance allows a subclass to reuse fields and methods from a superclass without rewriting them. This directly reduces code duplication and promotes maintainability in Java.

Exam trap

Oracle often tests the misconception that inheritance improves security or reduces memory usage, when in fact it primarily enables code reuse, polymorphism, and the is-a relationship.

8
MCQhard

A banking application has a base class 'Account' with a method 'withdraw()' marked as final. A subclass 'SavingsAccount' tries to override 'withdraw()'. What is the outcome?

A.Compilation error because final methods cannot be overridden
B.The override works only if SavingsAccount is in the same package
C.The override succeeds, final is ignored in subclasses
D.Runtime error when the method is called
AnswerA

Correct. final methods cannot be overridden; attempting to do so causes a compile-time error.

Why this answer

A final method cannot be overridden in a subclass. Attempting to do so results in a compilation error.

9
MCQmedium

A company's HR system uses an Employee class with sensitive salary information. The team wants to allow other classes to read the salary but not modify it. Which approach best preserves encapsulation?

A.Declare the salary field as public
B.Provide a public getSalary() getter method and keep salary private
C.Create a private method that returns salary only when called from within the same package
D.Provide a public setSalary() setter method and keep salary private
AnswerB

Correct. Private field with public getter provides controlled read access.

Why this answer

Encapsulation is achieved by keeping fields private and providing public getters. A getter allows read-only access without exposing the internal representation.

10
Multi-Selecteasy

Which two of the following are fundamental principles of Object-Oriented Programming? (Choose two.)

Select 2 answers
A.Iteration
B.Compilation
C.Synchronization
D.Encapsulation
E.Polymorphism
AnswersD, E

Correct. Encapsulation bundles data and methods and restricts direct access.

Why this answer

The four main OOP principles are encapsulation, inheritance, polymorphism, and abstraction.

11
MCQmedium

In a Java application, a class 'OrderProcessor' contains a method that processes orders. The method currently handles multiple responsibilities: validating order data, calculating totals, updating inventory, and sending notifications. The team wants to refactor this method to follow the Single Responsibility Principle. Which action should they take?

A.Use a single utility method that uses if-else for each case
B.Override the method in subclasses for each responsibility
C.Merge all responsibilities into a superclass
D.Create separate classes or methods for each responsibility and compose them in OrderProcessor
AnswerD

Each class/method has one reason to change, following SRP.

Why this answer

Option A is correct because separating each responsibility into its own class or method and composing them in OrderProcessor adheres to SRP. Option B is wrong because merging into a superclass does not separate responsibilities. Option C is wrong because a single utility method with if-else still violates SRP.

Option D is wrong because overriding in subclasses does not separate concerns within the same method.

12
Matchingmedium

Match each Java exception class to its category.

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

Concepts
Matches

Runtime exception (unchecked)

Checked exception

Runtime exception (unchecked)

Checked exception

Runtime exception (unchecked)

Why these pairings

Checked exceptions must be handled; unchecked exceptions are runtime.

13
Drag & Dropmedium

Arrange the steps to implement an interface in a Java class in the correct order.

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

Steps
Order

Why this order

First define the interface, then create a class that implements it, implement all abstract methods, add extra methods, and then use the class.

14
MCQhard

What is the result of: new Document().print();

A.Printable
B.Runtime exception
C.Compilation fails
D.Showable
AnswerC

Document must override print() to resolve conflict.

Why this answer

The code fails to compile because the class `Document` does not have a `print()` method defined. In Java, you can only invoke methods that are declared in the class or inherited from its superclass. Since no such method exists, the compiler issues an error.

Exam trap

Oracle often tests the distinction between compilation errors and runtime exceptions, tricking candidates into thinking a missing method will cause a runtime error rather than a compile-time failure.

How to eliminate wrong answers

Option A is wrong because `Printable` is not printed; the code never compiles, so no output is produced. Option B is wrong because a runtime exception cannot occur if the code does not compile; compilation must succeed first. Option D is wrong because `Showable` is not printed and the code does not compile.

15
MCQeasy

A junior developer writes a method that attempts to modify a String: public void update() { String s = "Hello"; s.concat(" World"); System.out.println(s); } What will be printed when update() is called?

A.Hello World
B.Hello World (no space)
C.Compilation error
D.Hello
AnswerD

Correct. Strings are immutable; concat() does not modify the original string.

Why this answer

Strings are immutable in Java. The concat() method returns a new String but the original object remains unchanged because the result is not assigned.

16
Multi-Selectmedium

Which TWO statements are true about the 'super' keyword in Java?

Select 2 answers
A.It can be used to access private methods of the superclass.
B.It can be used to access private fields of the superclass.
C.It can be used to call a superclass method that has been overridden.
D.It can be used to invoke a superclass constructor.
E.It can be used to invoke a static method of the superclass.
AnswersC, D

C is correct: super.method() calls the overridden superclass method.

Why this answer

Option A is correct because super() invokes the superclass constructor. Option C is correct because super.method() calls an overridden superclass method. Option B is wrong because super cannot access private fields.

Option D is wrong because super cannot invoke static methods directly. Option E is wrong because super cannot access private methods.

17
MCQeasy

A class that does not define any constructor has:

A.A private constructor
B.A public constructor with arguments
C.It cannot be instantiated
D.A default no-argument constructor
E.No constructor
AnswerD

Java automatically provides a default no-arg constructor with the same access as the class.

Why this answer

Java automatically provides a default no-arg constructor with the same access as the class.

18
MCQeasy

What is the output of: System.out.println(new Manager("Alice", 5).getName());

A.Runtime exception
B.Compilation fails
C.Alice
D.null
AnswerC

Correct; name is set via super constructor.

Why this answer

Option C is correct because the code creates a new Manager object with the name "Alice" and a level of 5, then calls getName() on it. Assuming Manager extends a class (likely Employee) that has a constructor setting the name field via super(name), getName() returns the stored name "Alice". The code compiles and runs without exception, printing "Alice".

Exam trap

Oracle often tests whether candidates understand that a subclass constructor can pass arguments to a superclass constructor, and that inherited methods like getName() work correctly without additional overrides, causing some to mistakenly think the code fails or returns null.

How to eliminate wrong answers

Option A is wrong because no runtime exception occurs; the object is properly constructed and getName() simply returns the name field. Option B is wrong because the code compiles successfully; there is no syntax error or missing method, as getName() is presumably inherited or defined in Manager or its superclass. Option D is wrong because the name field is explicitly set to "Alice" in the constructor call, so getName() does not return null.

19
MCQmedium

Refer to the exhibit. What is the output when the following code is executed? Vehicle v = new Car(); v.accelerate(); System.out.println(v.speed);

A.10
B.0
C.Compilation error
D.20
AnswerD

Correct. The Car's overridden method runs and sets speed to 20.

Why this answer

Polymorphism applies: the accelerate() method of the actual object (Car) is called, which adds 20 to speed. The protected field speed is accessible because Car extends Vehicle.

20
MCQhard

Which of the following best demonstrates polymorphism in Java?

A.Overloading a method with different parameter lists
B.Using an interface reference to call a method on an implementing object
C.Using static methods
D.Overriding a method in a subclass
E.Using final methods
AnswerB

Polymorphism allows one interface to be used for different implementations, as when an interface reference invokes the appropriate method at runtime.

Why this answer

Polymorphism in Java allows an object to take multiple forms, typically achieved through inheritance and interfaces. Option B demonstrates this by using an interface reference to invoke a method on an implementing object, where the actual method executed is determined at runtime based on the object's class, not the reference type.

Exam trap

Oracle often tests the distinction between compile-time polymorphism (overloading) and runtime polymorphism (overriding with interface/superclass references), so candidates mistakenly choose overloading or overriding alone without the reference context.

How to eliminate wrong answers

Option A is wrong because method overloading is compile-time polymorphism (static binding), not runtime polymorphism; it resolves method calls based on parameter lists at compile time. Option C is wrong because static methods belong to the class, not instances, and cannot be overridden, thus they do not exhibit polymorphic behavior. Option D is wrong because method overriding alone is not the best demonstration; it is a mechanism that enables polymorphism, but the question asks for the best demonstration, which requires using a superclass or interface reference to call overridden methods.

Option E is wrong because final methods cannot be overridden, which prevents polymorphic behavior entirely.

21
MCQhard

Given: abstract class Shape { abstract void draw(); } class Circle extends Shape { void draw() {} } Which is true?

A.Shape cannot have a constructor
B.Circle must override draw()
C.Shape s = new Shape(); is valid
D.draw() must be public in Circle
AnswerB

Circle provides implementation; it compiles fine.

Why this answer

Option B is correct because Circle is a concrete class that extends the abstract class Shape, which declares the abstract method draw(). A concrete subclass of an abstract class must provide an implementation for all inherited abstract methods, unless the subclass is also declared abstract. Circle provides an implementation of draw() with an empty body, which satisfies the override requirement.

Exam trap

The trap here is that candidates often think abstract classes cannot have constructors (option A) or that overriding methods must always be public (option D), but the Java specification allows constructors in abstract classes and only requires the overriding method to have at least the same access level as the abstract method.

How to eliminate wrong answers

Option A is wrong because abstract classes can have constructors, even though they cannot be instantiated directly; constructors are invoked via super() in subclasses. Option C is wrong because Shape is abstract and cannot be instantiated; the line 'new Shape()' would cause a compilation error. Option D is wrong because the overriding method draw() in Circle can have default (package-private) access, as the original abstract method in Shape has default access; the access level of the overriding method must be at least as accessible as the original, but it does not have to be public.

22
MCQhard

A Java class named 'Helper' is defined in package 'utils'. Another class in a different package tries to access a public method of Helper but receives a compilation error. The Helper class is declared as 'class Helper' (without public modifier). What is the likely issue?

A.The method is declared as final
B.The method is not static
C.The class is abstract
D.The class has package-private access
AnswerD

Default access (no modifier) makes the class accessible only within its package.

Why this answer

Option B is correct because a class with no access modifier (default) has package-private visibility, so it cannot be accessed from outside its package. Option A is wrong because the method being static is irrelevant to access. Option C is wrong because final does not affect access.

Option D is wrong because abstract does not restrict access.

23
MCQmedium

A company is developing a configuration manager that must be shared across all components to ensure consistent settings. The manager should prevent direct instantiation and provide a single access point. Which design pattern and implementation should be used?

A.Prototype pattern with cloning
B.Builder pattern with a static inner class
C.Factory pattern with a public constructor
D.Singleton pattern with a private constructor and a static getInstance() method
AnswerD

Correct. Singleton ensures a single instance and provides global access.

Why this answer

The Singleton pattern ensures a class has only one instance and provides a global point of access. A private constructor prevents direct instantiation, and a static getInstance() method provides controlled access.

24
Multi-Selectmedium

Which TWO of the following are valid benefits of using inheritance in Java? (Choose two.)

Select 2 answers
A.Increases coupling between classes
B.Allows polymorphic behavior
C.Promotes code reuse
D.Enforces encapsulation
E.Simplifies debugging
AnswersB, C

Inheritance supports method overriding and runtime polymorphism.

Why this answer

Options A and C are correct. Inheritance promotes code reuse by allowing subclasses to inherit fields and methods from superclasses. It also enables polymorphic behavior through method overriding.

Option B is wrong because inheritance increases coupling, not a benefit. Option D is wrong because inheritance can complicate debugging. Option E is wrong because encapsulation is enforced by access modifiers, not inheritance.

25
MCQhard

Consider the following interface: public interface Drawable { void draw(); } A developer implements Drawable in class Circle. Which statement about the implementation is correct?

A.The draw method must be declared public
B.Both A and D
C.The class must be abstract if it does not provide body for draw
D.The draw method can have a body in the interface
E.The draw method must be declared final
AnswerB

Both A and D are correct. Interface methods are implicitly public, so implementing class must use public. If not implementing, class must be abstract.

Why this answer

Interface methods are implicitly public, so implementing class must use public; if not implementing, class must be abstract.

26
MCQmedium

A logging utility class keeps track of the number of log entries using a static integer variable. The class is instantiated multiple times in the application. How does the count variable behave?

A.Each instance has its own copy of count
B.All instances share the same count variable
C.count is reset each time a new instance is created
D.count cannot be accessed from static methods
AnswerB

Correct. A static variable is shared across all instances.

Why this answer

Static variables are shared among all instances of a class. There is only one copy of the variable, regardless of the number of instances.

27
MCQeasy

In a banking application, a class 'Account' has a private field 'balance'. Which is the best way to allow subclasses to read but not directly modify 'balance'?

A.Make balance public
B.Provide a public getBalance() method
C.Use a static variable
D.Make balance protected
AnswerB

Getter provides read-only access; keep field private.

Why this answer

Option B is correct because it follows the encapsulation principle of object-oriented programming. By providing a public getBalance() method, subclasses can read the balance value without having direct access to the private field, thus preventing unintended modification. This is the standard Java pattern for controlled access to private instance variables.

Exam trap

Oracle often tests the misconception that protected access is sufficient for read-only access, but protected actually allows both reading and writing by subclasses, failing the 'not directly modify' requirement.

How to eliminate wrong answers

Option A is wrong because making balance public violates encapsulation, allowing any class (including subclasses) to directly modify the field without restriction. Option C is wrong because a static variable is shared across all instances of the class, which is inappropriate for an instance-specific balance and does not solve the read-only requirement. Option D is wrong because making balance protected allows subclasses to directly read and modify the field, which does not prevent modification as required.

28
MCQhard

A team is developing a large-scale e-commerce platform using Java. They have a class hierarchy: Product (abstract), Electronics, Clothing, Food. Each product has a discount method that applies different logic. The team notices that whenever a new product type is added, they must modify the existing discount calculation logic in multiple places, leading to high maintenance costs. They want to refactor to follow the Open/Closed Principle. Which approach should they take?

A.Define an interface Discountable with a method calculateDiscount() and have each product class implement it
B.Create a single discount method in Product that uses if-else checks on type
C.Remove the discount method and handle it externally using reflection
D.Use a switch statement in a utility class to handle all product types
AnswerA

This follows OCP: new products implement the interface, no existing code changes.

Why this answer

Option A is correct because defining an interface Discountable with a calculateDiscount() method and having each product class implement it allows adding new product types without modifying existing code. Option B is wrong because it violates OCP by requiring changes to a switch statement. Option C is wrong because it also requires modification when new types are added.

Option D is wrong because it uses reflection unnecessarily and still requires changes to map types.

29
Multi-Selecthard

Which THREE statements are true about interfaces in Java? (Choose three.)

Select 3 answers
A.An interface can be instantiated directly
B.An interface can extend multiple interfaces
C.An interface can contain static methods
D.An interface can contain default methods
E.An interface can have private fields
AnswersB, C, D

Interfaces support multiple inheritance of type.

Why this answer

Options A, B, and D are correct. Interfaces can extend multiple interfaces using the extends keyword. Since Java 8, interfaces can contain static methods (with body) and default methods.

Option C is wrong because interfaces cannot be instantiated directly. Option E is wrong because interface fields are implicitly public static final; private fields are not allowed (private methods are allowed since Java 9, but not fields).

30
MCQhard

A calculator class has two overloaded methods: add(int a, int b) and add(double a, double b). A call to add(3, 4) will invoke which method?

A.add(double, double)
B.add(int, int)
C.Runtime decision based on actual parameters
D.Compilation error: ambiguous
AnswerB

Correct. The arguments are int literals, so the int version is invoked.

Why this answer

Overloaded method resolution is based on compile-time types. The literal 3 and 4 are ints, so the int version is the most specific match and is called.

31
MCQmedium

A class has a method that is marked as protected. Which statement is true about its accessibility?

A.Only in subclasses
B.Only within the same package
C.Everywhere
D.Only within the same class
E.Within the same package and subclasses
AnswerE

Protected access allows access within the same package and by subclasses even in different packages.

Why this answer

In Java, the protected access modifier allows access within the same package and by subclasses (even if they are in different packages). Option E correctly states this combination, which is the precise definition of protected access as specified in the Java Language Specification (JLS §6.6.2).

Exam trap

The trap here is that candidates often confuse protected with package-private (default) access, forgetting that protected also grants access to subclasses in other packages, or they incorrectly think protected is as restrictive as private.

How to eliminate wrong answers

Option A is wrong because protected access is not limited only to subclasses; it also permits access from classes in the same package. Option B is wrong because protected access extends beyond the same package to subclasses in other packages. Option C is wrong because protected access is not universal; it excludes unrelated classes in different packages.

Option D is wrong because protected access is broader than only within the same class; that is the scope of private access.

32
MCQeasy

A company develops a payroll system in Java with a hierarchy: Employee, Manager (extends Employee), and Director (extends Manager). Each class overrides a method getDetails() that returns a string with employee information. Employee's getDetails() returns name and ID. Manager's getDetails() adds department. Director's getDetails() adds division. The system uses a single method printDetails(Employee e) that calls e.getDetails(). After a recent deployment, the system prints only the name and ID for all employees, even for managers and directors. The code review reveals that Employee's getDetails() is declared with default (package-private) access, while the overridden versions in Manager and Director are public. The printDetails method and the Manager/Director classes are in different packages. What is the most likely cause and the correct solution?

A.Change the access modifier of getDetails() in Employee to public (or protected).
B.Modify printDetails() to accept Manager or Director objects instead of Employee.
C.Add @Override annotation to the overridden methods in Manager and Director.
D.Declare getDetails() in Employee as final to ensure consistent behavior.
AnswerA

A is correct: default access prevents overriding from different packages; changing to public enables proper polymorphism.

Why this answer

Option A is correct. In Java, a default-access method is not visible to subclasses in different packages, so Manager and Director cannot override it; their getDetails() methods are new methods, not overriding Employee's. Making Employee's getDetails() public (or protected) allows proper overriding and polymorphic behavior.

Option B is wrong because it bypasses polymorphism. Option C is wrong because @Override only helps catch errors, but the access issue remains. Option D is wrong because making the method final would prevent overriding entirely.

33
MCQmedium

A developer writes: Object obj = new String("Hello"); System.out.println(obj.length()); What will be the output?

A.null
B.Runtime exception
C.5
D.Compilation error
E.0
AnswerD

Correct. The code does not compile because Object class does not have length() method.

Why this answer

The code fails to compile because the reference variable 'obj' is of type Object, which does not have a length() method. The length() method is defined in the String class, not in Object. Since the compiler checks the declared type (Object) for method availability, it does not find length() and produces a compilation error.

Exam trap

Oracle often tests the distinction between compile-time type and runtime type, trapping candidates who assume that because the object is a String, the length() method is automatically available on any reference to it.

How to eliminate wrong answers

Option A is wrong because null is not printed; the code never executes due to a compilation error. Option B is wrong because a runtime exception would only occur if the code compiled and then failed at runtime, but here the compiler rejects the code. Option C is wrong because 5 would be the output if obj were declared as String, but the declared type is Object, so length() is not accessible.

Option E is wrong because 0 would be the length of an empty string, but the code does not compile to produce any output.

34
Multi-Selecteasy

Which TWO access modifiers allow access from a subclass in a different package?

Select 2 answers
A.private
B.static
C.default (no modifier)
D.protected
E.public
AnswersD, E

Protected members are accessible in subclasses even if they are in different packages.

Why this answer

Option D (protected) is correct because the protected access modifier allows access to members of a superclass by subclasses in different packages, provided the subclass inherits from the superclass. Option E (public) is also correct because public members are accessible from any class, regardless of package or inheritance.

Exam trap

Oracle often tests the distinction between access modifiers and non-access modifiers, so candidates may mistakenly select 'static' as an access modifier because it is commonly used with methods and fields.

35
MCQeasy

A developer wants to ensure that a class cannot be subclassed. Which keyword should be used?

A.final
B.protected
C.private
D.abstract
E.static
AnswerA

A class declared as final cannot be subclassed.

Why this answer

The `final` keyword prevents a class from being subclassed. When a class is declared `final`, the compiler enforces that no other class can extend it, ensuring its implementation cannot be overridden or inherited. This is the correct mechanism in Java to prevent subclassing.

Exam trap

Oracle often tests the `final` keyword in the context of inheritance, and the trap here is that candidates confuse `final` with `abstract` (which forces subclassing) or `private` (which is about access, not inheritance prevention), leading them to pick the wrong option.

How to eliminate wrong answers

Option B is wrong because `protected` controls access to members (fields, methods) from subclasses and the same package, but does not prevent a class from being subclassed. Option C is wrong because `private` restricts access to within the class itself, but a class cannot be declared `private` at the top level (only inner classes can be private), and even then it does not prevent subclassing of the outer class. Option D is wrong because `abstract` explicitly requires a class to be subclassed to be instantiated, which is the opposite of preventing subclassing.

Option E is wrong because `static` is used for class-level members (methods, fields, inner classes) and cannot be applied to a top-level class; it has no effect on subclassing prevention.

36
MCQmedium

Refer to the exhibit. What is the output?

A.null
B.Vehicle
C.Compilation error
D.Car
E.Runtime error
AnswerB

In Java, fields are not polymorphic; the reference type determines which field is accessed. v is of type Vehicle, so v.type refers to Vehicle's type field.

Why this answer

In Java, fields are not polymorphic; the reference type determines which field is accessed. v is of type Vehicle, so v.type refers to Vehicle's type field.

37
MCQmedium

A team is designing a system where a 'Report' class can be generated in different formats (PDF, Excel, HTML). They want to avoid modifying the Report class when adding new formats. Which OOP principle or pattern should they use?

A.Method Overloading
B.Composition
C.Inheritance
D.Singleton
AnswerB

Composing Report with a formatter interface allows adding formats without modifying Report.

Why this answer

Option A is correct because composition (or Strategy pattern) allows the Report class to delegate format generation to separate objects, enabling easy extension. Option B is wrong because inheritance would create a rigid hierarchy. Option C is wrong because Singleton ensures a single instance, not flexibility.

Option D is wrong because method overloading is compile-time and not suitable for adding new formats dynamically.

38
MCQhard

Which statement about abstract classes and interfaces is true in Java?

A.Both B and D
B.An interface can have instance variables
C.An abstract class can be instantiated
D.An interface can have constructor
E.An abstract class can have concrete methods
AnswerE

Correct. Abstract classes can have both abstract and concrete methods.

Why this answer

Option E is correct because an abstract class in Java can contain concrete (non-abstract) methods with full implementations, which subclasses can inherit or override. This is a key distinction from interfaces (prior to Java 8), which could only declare abstract methods. Abstract classes cannot be instantiated directly, but they provide a partial implementation that concrete subclasses complete.

Exam trap

The trap here is that candidates often confuse the capabilities of abstract classes and interfaces, mistakenly thinking abstract classes cannot have concrete methods or that interfaces can have constructors, leading them to select options like A, B, or D.

How to eliminate wrong answers

Option A is wrong because it claims both B and D are true, but B and D are false. Option B is wrong because interfaces cannot have instance variables; they can only have constants (public static final fields). Option C is wrong because abstract classes cannot be instantiated directly; they must be subclassed and the subclass instantiated.

Option D is wrong because interfaces cannot have constructors; they are not instantiable and constructors are only for classes.

39
Multi-Selectmedium

Which THREE are true about Java constructors?

Select 3 answers
A.A constructor cannot have a return type
B.A constructor can be marked final
C.A constructor can be abstract
D.A constructor can be overloaded
E.A constructor can be private
AnswersA, D, E

Constructors do not have a return type, not even void.

Why this answer

Option A is correct because constructors in Java do not have a return type, not even void. If you attempt to add a return type to a constructor, the compiler treats it as a regular method, not a constructor, which can lead to unexpected behavior. This is a fundamental rule of Java syntax.

Exam trap

The trap here is that candidates may confuse constructors with regular methods and think that final or abstract modifiers apply, but Java explicitly forbids these on constructors because they are not inherited or overridden.

40
MCQmedium

A developer is working on a Java application that processes sensor data. The code uses a class 'SensorDataProcessor' which directly instantiates specific sensor classes like 'TemperatureSensor' and 'PressureSensor' inside its methods. The team wants to make the system extensible to support new sensor types without modifying the processor class. Which design change best achieves this?

A.Make SensorDataProcessor abstract and subclass it for each sensor
B.Use a static factory method in SensorDataProcessor to create sensors
C.Create a separate configuration file listing sensors and use reflection to instantiate them
D.Define a Sensor interface and use dependency injection to pass sensor objects to the processor
AnswerD

Dependency injection allows the processor to work with any Sensor implementation.

Why this answer

Option B is correct because defining a Sensor interface and using dependency injection (e.g., passing sensor objects via constructor or setter) decouples the processor from concrete sensor classes. Option A is wrong because creating subclasses for each sensor would still require modifying the processor if new sensor types are added. Option C is wrong because a static factory still couples the processor to the factory.

Option D is wrong because reflection is complex and not the best practice for this scenario.

41
MCQeasy

A junior developer created a class 'BankAccount' with public fields for balance and account number. After deployment, users are able to set negative balances, causing issues. Which OOP principle should have been applied to prevent this?

A.Inheritance
B.Encapsulation
C.Abstraction
D.Polymorphism
AnswerB

Encapsulation allows controlled access through methods with validation.

Why this answer

Option C is correct because encapsulation would make the balance field private and provide a setter method that validates the value. Option A is wrong because polymorphism deals with method behavior, not data hiding. Option B is wrong because inheritance is about reusing code, not securing data.

Option D is wrong because abstraction is about hiding complexity, not validation.

42
MCQeasy

Refer to the exhibit. Why does the code fail to compile?

A.Animal must be declared as interface
B.The main method is in the wrong class
C.The sound() method is not defined
D.Cannot instantiate an abstract class
AnswerD

Correct. Abstract classes cannot be instantiated directly.

Why this answer

Abstract classes cannot be instantiated. The attempt to create a new Animal() causes a compile-time error because Animal is abstract.

43
MCQmedium

A developer writes a class 'Vehicle' with a method 'move()' that prints 'Vehicle moves'. A subclass 'Car' overrides 'move()' to print 'Car moves'. Given: Vehicle v = new Car(); v.move(); What is the output?

A.Vehicle moves
B.Runtime exception
C.Compilation fails
D.Car moves
AnswerD

Correct due to polymorphism; the overridden method in Car is called.

Why this answer

Option D is correct because Java uses dynamic method dispatch (runtime polymorphism). Even though the reference variable is of type 'Vehicle', the actual object is a 'Car' instance. At runtime, the JVM calls the overridden 'move()' method of the 'Car' class, printing 'Car moves'.

Exam trap

The trap here is that candidates mistakenly apply static binding (thinking the compiler uses the reference type 'Vehicle' to call 'move()'), ignoring Java's runtime polymorphism for overridden instance methods.

How to eliminate wrong answers

Option A is wrong because it assumes static binding (compile-time method resolution based on reference type), but Java resolves overridden instance methods at runtime based on the actual object type. Option B is wrong because no exception occurs; the code compiles and runs successfully. Option C is wrong because the code compiles without error: 'Car' extends 'Vehicle', 'move()' is properly overridden, and the assignment 'Vehicle v = new Car()' is valid upcasting.

44
MCQhard

Refer to the exhibit. What is the potential issue with this singleton implementation in a multithreaded environment?

A.The getInstance() method should be non-static
B.Compilation error because the constructor is private
C.Memory leak because instances are never garbage collected
D.Not thread-safe; two threads could simultaneously create different instances
AnswerD

Correct. The check-then-act sequence is not synchronized.

Why this answer

The if-check and instantiation are not atomic. Two threads could both see instance == null and create separate instances, violating the singleton guarantee.

45
MCQhard

A Java application uses an interface 'Drawable' with a default method 'draw()'. A class 'Circle' implements Drawable but does not override draw(). Another class 'Square' implements Drawable and overrides draw(). Which statement is true about calling draw() on instances of Circle and Square?

A.Circle will use the default, Square will use its own
B.Square will use the default, Circle will cause a compilation error
C.Both will use the default implementation
D.Both will cause a compilation error
AnswerA

If a class does not override a default method, it inherits the default.

Why this answer

Option B is correct because classes inherit default interface methods; Circle inherits the default, Square overrides it. Option A is wrong because Square uses its own version. Option C is wrong because Circle does not cause an error.

Option D is wrong because both compile successfully.

46
Multi-Selecthard

Which TWO statements about interfaces in Java are true?

Select 2 answers
A.An interface can have instance variables
B.An interface can implement another interface
C.An interface can extend another interface
D.An interface can have final methods
E.An interface can have default methods with a body
AnswersC, E

Interfaces can extend other interfaces.

Why this answer

Interfaces can extend other interfaces and can have default methods with a body.

47
MCQhard

A class 'Base' has a method 'public void display() throws IOException'. Subclass 'Derived' overrides display(). Which exception specifications are allowed in the overriding method?

A.public void display() throws SQLException
B.public void display() throws FileNotFoundException
C.public void display() throws Exception
D.public void display() throws Throwable
AnswerB

FileNotFoundException is a subclass of IOException, allowed.

Why this answer

In Java, an overriding method can throw the same exception, a subclass of the exception thrown by the parent method, or no exception at all. The parent method throws IOException, so the overriding method may throw FileNotFoundException (a subclass of IOException). This follows the rule that the overriding method cannot throw a broader checked exception than the overridden method.

Exam trap

Oracle often tests the misconception that an overriding method can throw any exception, but the key is that only the same exception or a subclass of the parent's exception is allowed for checked exceptions.

How to eliminate wrong answers

Option A is wrong because SQLException is not a subclass of IOException; it is a completely unrelated checked exception, and throwing it would violate the rule that an overriding method cannot throw a new or broader checked exception. Option C is wrong because Exception is a superclass of IOException, making it a broader checked exception, which is not allowed in an overriding method. Option D is wrong because Throwable is the root of the entire exception hierarchy and is broader than IOException, so it is not permitted.

48
Multi-Selecthard

Which TWO statements are true about interfaces in Java?

Select 2 answers
A.Interfaces can contain private methods.
B.Interfaces can be instantiated.
C.Interfaces can contain constructors.
D.All interface variables are implicitly public static final.
E.Interfaces cannot have default methods.
AnswersA, D

Since Java 9, interfaces can have private methods for code reuse.

Why this answer

Option A is correct because, since Java 9, interfaces can contain private methods to share common code between default methods or static methods within the interface, without exposing that logic to implementing classes. Option D is correct because all variables declared in an interface are implicitly public, static, and final, meaning they are constants that cannot be changed once assigned.

Exam trap

The trap here is that candidates often forget that interfaces can have private methods (Java 9+) and default methods (Java 8), and mistakenly think interfaces are purely abstract with only public abstract methods and constants.

49
MCQmedium

class Parent { void show() { System.out.print("Parent"); } } class Child extends Parent { void show() { System.out.print("Child"); } } public class Test { public static void main(String[] args) { Parent p = new Child(); p.show(); } } What is the output?

A.Compilation error
B.No output
C.Parent
D.Child
E.Runtime error
AnswerD

Correct. Although the reference is Parent, the object is Child, and show() is overridden, so Child's version is called.

Why this answer

Although the reference is Parent, the object is Child, and show() is overridden, so Child's version is called.

50
MCQmedium

A developer wants to prevent a method from being overridden. Which modifier should be used?

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

Final methods cannot be overridden.

Why this answer

The `final` modifier prevents a method from being overridden in a subclass. When a method is declared as `final`, any attempt to override it in a subclass results in a compile-time error, ensuring the method's implementation remains unchanged.

Exam trap

Oracle often tests the distinction between 'hiding' (for static methods) and 'overriding' (for instance methods), leading candidates to incorrectly choose `static` because they confuse hiding with preventing overriding.

How to eliminate wrong answers

Option A is wrong because `private` methods are not inherited and thus cannot be overridden, but the question asks for preventing overriding of a method that is accessible; `private` methods are hidden, not prevented from overriding. Option B is wrong because `abstract` methods must be overridden by a subclass to provide an implementation, which is the opposite of preventing overriding. Option D is wrong because `static` methods are hidden, not overridden; they belong to the class rather than instances, and a subclass can declare a method with the same signature without overriding the parent's static method.

51
MCQeasy

Which access modifier allows a member to be accessed only within the same class?

A.static
B.public
C.default (no modifier)
D.protected
E.private
AnswerE

Private members are accessible only within the same class.

Why this answer

Private members are accessible only within the same class.

52
MCQeasy

In a banking application, a class 'Account' has private field 'balance' and public methods 'getBalance()' and 'setBalance(double)'. This is an example of which OOP principle?

A.Abstraction
B.Inheritance
C.Polymorphism
D.Encapsulation
AnswerD

Encapsulation bundles data with methods and restricts direct access to fields.

Why this answer

Option D is correct because encapsulation hides internal data and provides controlled access via methods. Option A is wrong because there is no inheritance involved. Option B is wrong because polymorphism is not shown.

Option C is wrong because abstraction is about hiding complexity, not data protection.

53
MCQhard

Refer to the exhibit. What is the output?

A.Runtime error
B.No output
C.Compilation error
D.Photo
E.Document
AnswerD

The object is Photo, and print() is overridden, so dynamic binding calls Photo's print method.

Why this answer

The object is Photo, and print() is overridden, so dynamic binding calls Photo's print method.

54
MCQmedium

Refer to the exhibit. What is the problem with this class?

A.The constructor is missing a return type
B.The constructor parameter shadows the field, causing name to remain null
C.The getName method should be void
D.The field name is private and cannot be accessed within the class
AnswerB

The assignment should be 'this.name = name;' to assign to the field.

Why this answer

Option A is correct because the constructor parameter name shadows the field name, and the assignment 'name = name' assigns the parameter to itself, leaving the field null. Option B is wrong because the field is private and accessible within the class. Option C is wrong because constructors don't have return types.

Option D is wrong because the method returns a String correctly.

55
MCQeasy

Which is the correct way to call a superclass constructor from a subclass constructor?

A.super(); anywhere
B.super(); as first statement
C.super(); at the end
D.this.super();
AnswerB

Correct syntax and position.

Why this answer

In Java, a call to the superclass constructor using `super()` must be the first statement in a subclass constructor. This ensures that the superclass initialization completes before any subclass-specific code executes, maintaining the inheritance chain. Option B correctly identifies this requirement.

Exam trap

Oracle often tests the misconception that `super()` can be placed anywhere in the constructor body, leading candidates to choose option A, when in fact Java strictly requires it as the first statement.

How to eliminate wrong answers

Option A is wrong because `super()` cannot be placed anywhere; it must be the first statement, or the compiler will report an error. Option C is wrong because placing `super()` at the end would attempt to initialize the superclass after subclass code, violating Java's constructor chaining rules and causing a compilation failure. Option D is wrong because `this.super()` is invalid syntax; `super()` is a standalone keyword call, not a method on `this`.

56
MCQeasy

A developer writes a class 'Animal' with a method 'sound()'. The 'Cat' subclass overrides 'sound()'. If an Animal reference points to a Cat object, which method is called when sound() is invoked?

A.Runtime error
B.Cat's sound()
C.Animal's sound()
D.Compilation error
AnswerB

Correct. Java uses dynamic method dispatch for instance methods.

Why this answer

Polymorphism ensures that the overridden method in the actual object's class is called at runtime, even if the reference is of the superclass type.

57
MCQhard

A developer creates an interface 'Drawable' with a single abstract method 'draw()'. They then create a class 'Circle' that implements Drawable but forgets to provide the draw() method. Circle is not declared abstract. What will happen when compiling Circle?

A.Compilation fails because interfaces cannot be implemented without overriding all methods
B.Compilation succeeds, a default empty method is generated
C.Compilation fails because Circle must either implement draw() or be declared abstract
D.Compilation succeeds but a warning is issued
AnswerC

Correct. The class must either implement the abstract method or be declared abstract itself.

Why this answer

A class that implements an interface must provide implementations for all abstract methods, or it must be declared abstract. Without the implementation and without being abstract, the class does not compile.

58
MCQmedium

A developer wants to create a class that can be used to represent different types of vehicles (e.g., Car, Truck, Motorcycle) and each vehicle type should be able to start its own engine in a specific way. Which OOP concept should be used to allow the vehicle class to define a common interface while letting subclasses provide specific implementations?

A.Polymorphism
B.Inheritance
C.Encapsulation
D.Abstraction
AnswerA

Polymorphism allows a common interface to have different implementations, achieved via method overriding.

Why this answer

Polymorphism allows the Vehicle class to define a common method (e.g., startEngine()) that each subclass (Car, Truck, Motorcycle) overrides with its own specific implementation. When the method is called on a Vehicle reference, the JVM uses dynamic method dispatch at runtime to invoke the correct subclass version, enabling different engine-starting behaviors through a single interface.

Exam trap

Oracle often tests the distinction between abstraction (defining the interface) and polymorphism (using that interface to invoke different implementations at runtime), so candidates mistakenly choose abstraction when the question emphasizes 'specific implementations' and runtime behavior.

How to eliminate wrong answers

Option B (Inheritance) is wrong because inheritance alone only provides code reuse and a parent-child relationship; it does not inherently allow different subclass implementations to be invoked through a common interface at runtime. Option C (Encapsulation) is wrong because encapsulation focuses on hiding internal state via private fields and public accessors, not on defining a common interface with multiple implementations. Option D (Abstraction) is wrong because abstraction (e.g., abstract classes or interfaces) defines the contract but does not by itself enable runtime selection of specific implementations; that runtime behavior is polymorphism.

59
Multi-Selectmedium

Which three statements about constructors in Java are true? (Choose three.)

Select 3 answers
A.The default constructor has no parameters
B.Constructors can be abstract
C.Constructors cannot return a value
D.Constructors can be overloaded
E.Constructors can be final
AnswersA, C, D

Correct. If no constructor is defined, the compiler adds a no-argument constructor.

Why this answer

Constructors can be overloaded to provide different initialization options, they cannot return a value (not even void), and if no constructor is defined, the compiler provides a default no-arg constructor.

60
MCQeasy

A security-sensitive class should not be extended by any other class. Which modifier should be applied to the class declaration?

A.final
B.abstract
C.static
D.private
AnswerA

Correct. A final class cannot be extended.

Why this answer

The final modifier prevents a class from being subclassed, which is appropriate for security or design reasons.

61
MCQmedium

Which design principle is violated by making all fields public in a class?

A.Inheritance
B.Abstraction
C.Encapsulation
D.Polymorphism
AnswerC

Encapsulation hides internal data; public fields expose it.

Why this answer

Making all fields public violates the principle of encapsulation, which requires that an object's internal state be hidden from external access and only modifiable through controlled methods (getters/setters). In Java, public fields allow any class to directly read or modify the field, breaking data integrity and the ability to enforce invariants. Encapsulation is a core OOP concept that protects the internal representation of an object.

Exam trap

Oracle often tests the distinction between OOP principles by presenting a scenario that seems to involve inheritance or abstraction, but the core violation is always about data hiding and controlled access—candidates mistakenly choose 'abstraction' because they confuse hiding implementation details with hiding data fields.

How to eliminate wrong answers

Option A is wrong because inheritance is a mechanism for creating class hierarchies (using extends), not a design principle about field visibility; public fields do not prevent inheritance. Option B is wrong because abstraction focuses on hiding implementation details behind interfaces or abstract classes, not on field access control; public fields can still exist within an abstract design. Option D is wrong because polymorphism relies on method overriding and interface implementation, not on field access modifiers; public fields do not affect polymorphic behavior.

Ready to test yourself?

Try a timed practice session using only Java Oop questions.