Latest Java Loops MCQs

1 min read

Iteration structures in Java allow developers to execute code blocks repeatedly based on dynamic boolean conditions, eliminating code duplication and automating repetitive tasks. Standard loops such as the counter-controlled for loop, pre-test while loop, and post-test do-while loop handle varied execution workflows, while the modern enhanced for-each loop streamlines traversal over arrays and collections. Mastering loop control statements like break, continue, and labeled forms, alongside understanding variable scoping within loop headers, is essential for writing efficient runtime code and succeeding in technical programming exams.

1. Which of the following is the fundamental building block of Object-Oriented Programming in Java?

a) Method
b) Class
c) Package
d) Interface
Correct Answer: b) Class
Explanation:
A class serves as a blueprint or template from which individual objects are created, encapsulating data and behavior.

2. What is the primary purpose of encapsulation in Java?

a) To allow multiple inheritance
b) To hide internal object state and restrict direct access using access modifiers
c) To improve execution speed of compiled bytecode
d) To eliminate the need for constructors
Correct Answer: b) To hide internal object state and restrict direct access using access modifiers
Explanation:
Encapsulation binds data and methods together while protecting the internal state from unauthorized external modification.

3. Which access modifier restricts visibility strictly to the class in which the member is defined?

a) public
b) protected
c) private
d) default (package-private)
Correct Answer: c) private
Explanation:
The private access modifier ensures that members are accessible only within the declaring class itself.

4. What is method overloading in Java?

a) Defining multiple methods with the same name in the same class with different parameter lists
b) Redefining a superclass method in a subclass with identical signature
c) Calling a method recursively without a base case
d) Overriding a static method in a child class
Correct Answer: a) Defining multiple methods with the same name in the same class with different parameter lists
Explanation:
Method overloading is a compile-time (static) polymorphism mechanism where methods share a name but differ in parameters.

5. Which of the following describes method overriding?

a) Having multiple methods with different return types in the same class
b) Providing a specific implementation in a subclass for a method already defined in its superclass
c) Invoking a private method from an external package
d) Declaring multiple constructors in a single class
Correct Answer: b) Providing a specific implementation in a subclass for a method already defined in its superclass
Explanation:
Method overriding is a run-time (dynamic) polymorphism feature where a subclass provides its own version of an inherited method.

6. Can an abstract class in Java be instantiated directly using the new keyword?

a) Yes, always
b) No, abstract classes cannot be instantiated directly
c) Only if it contains at least one concrete method
d) Only inside static main methods
Correct Answer: b) No, abstract classes cannot be instantiated directly
Explanation:
Abstract classes serve as templates and cannot be instantiated directly; they must be extended by subclasses.

7. What is the key difference between an abstract class and an interface in modern Java?

a) Interfaces cannot contain any methods at all.
b) Abstract classes can have instance variables and constructors, whereas traditional interfaces cannot have instance state.
c) An abstract class can be implemented multiple times by a single class.
d) Interfaces are instantiated using the new keyword.
Correct Answer: b) Abstract classes can have instance variables and constructors, whereas traditional interfaces cannot have instance state.
Explanation:
Abstract classes support constructors, state, and non-final fields, while interfaces define contracts (though default methods are allowed).

8. Which keyword is used by a Java class to inherit from a superclass?

a) implements
b) extends
c) inherits
d) subclass
Correct Answer: b) extends
Explanation:
The extends keyword is used in class declarations to establish inheritance relationships between a subclass and a superclass.

9. What is multiple inheritance of state, and why is it not supported for classes in Java?

a) Inheriting from multiple classes; avoided to prevent the Diamond Problem and ambiguity.
b) Inheriting from multiple interfaces; avoided due to memory limits.
c) Implementing multiple abstract methods; avoided due to syntax errors.
d) Using multiple threads; avoided due to synchronization overhead.
Correct Answer: a) Inheriting from multiple classes; avoided to prevent the Diamond Problem and ambiguity.
Explanation:
Java prohibits class-based multiple inheritance to eliminate ambiguity and complexity associated with the Diamond Problem.

10. Which keyword is used by a class to adopt an interface contract?

a) extends
b) implements
c) using
d) adopt
Correct Answer: b) implements
Explanation:
Classes use the implements keyword to commit to fulfilling all abstract method contracts declared within an interface.

11. What is polymorphism in Object-Oriented Programming?

a) The ability of an object to take on many forms or be referenced via superclass types
b) The practice of making all class variables private
c) The compilation of Java code into native machine instructions
d) The automatic garbage collection of unreferenced objects
Correct Answer: a) The ability of an object to take on many forms or be referenced via superclass types
Explanation:
Polymorphism allows a single interface or superclass reference to point to distinct subclass implementations at runtime.

12. What is the purpose of a constructor in a Java class?

a) To destroy objects when garbage collection runs
b) To initialize newly created objects and set initial state
c) To define package visibility rules
d) To override superclass methods
Correct Answer: b) To initialize newly created objects and set initial state
Explanation:
A constructor is a special method invoked automatically upon object instantiation to initialize fields and state.

13. What happens if a Java class does not explicitly define any constructor?

a) A compile-time error occurs.
b) The compiler automatically supplies a default no-argument constructor.
c) The class cannot be instantiated.
d) Fields remain uninitialized with random memory values.
Correct Answer: b) The compiler automatically supplies a default no-argument constructor.
Explanation:
If no constructors are provided, Java automatically provides a public default no-arg constructor.

14. Can constructors be overridden in Java subclasses?

a) Yes, always
b) No, constructors cannot be overridden because they are not inherited
c) Only if declared as public
d) Only in abstract classes
Correct Answer: b) No, constructors cannot be overridden because they are not inherited
Explanation:
Constructors are not inherited by subclasses, meaning they cannot be overridden, though they can be overloaded or chained using super().

15. What is the function of the super keyword in Java?

a) To reference the immediate superclass instance, invoke superclass constructors, or hidden methods
b) To create a new thread in the JVM
c) To make a variable globally accessible
d) To terminate the program execution
Correct Answer: a) To reference the immediate superclass instance, invoke superclass constructors, or hidden methods
Explanation:
The super keyword provides communication and linkage between a subclass and its direct parent superclass.

16. What is the function of the this keyword in Java?

a) To refer to the current object instance within which a method or constructor is running
b) To refer to the parent superclass instance
c) To import packages into a source file
d) To declare constant variables
Correct Answer: a) To refer to the current object instance within which a method or constructor is running
Explanation:
The this keyword serves as a reference to the current object, resolving shadowing between instance fields and parameters.

17. What is dynamic method dispatch in Java?

a) Resolving overridden method calls at runtime based on the actual object type rather than reference type
b) Loading classes dynamically via reflection
c) Executing static methods concurrently across threads
d) Allocating heap memory dynamically
Correct Answer: a) Resolving overridden method calls at runtime based on the actual object type rather than reference type
Explanation:
Dynamic method dispatch is the mechanism enabling runtime polymorphism when a superclass reference invokes an overridden method.

18. Which access modifier allows members to be accessed within the same class, same package, and subclasses in other packages?

a) private
b) default
c) protected
d) public
Correct Answer: c) protected
Explanation:
The protected modifier extends package-private visibility to include subclasses residing outside the package.

19. What is the output restriction when overriding a method regarding access modifiers?

a) The overriding method can reduce visibility.
b) The overriding method cannot reduce the accessibility (must be same or more accessible).
c) The overriding method must always be private.
d) Access modifiers do not matter during method overriding.
Correct Answer: b) The overriding method cannot reduce the accessibility (must be same or more accessible).
Explanation:
Java rules state that an overriding method cannot restrict visibility more than the superclass method it overrides.

20. What is an immutable class in Java?

a) A class whose object state cannot be modified after creation.
b) A class that cannot be extended via inheritance.
c) A class with only static methods.
d) A class that implements AutoCloseable.
Correct Answer: a) A class whose object state cannot be modified after creation.
Explanation:
An immutable class (like String) has all final fields and no setter methods, ensuring its state remains constant.

21. Which keyword is used to prevent a class from being inherited (subclassed)?

a) static
b) final
c) abstract
d) sealed
Correct Answer: b) final
Explanation:
Declaring a class as final prevents any other class from extending it.

22. What happens when a method is declared as final in a superclass?

a) It cannot be overridden by subclasses.
b) It can only be called from static contexts.
c) It executes twice as fast.
d) It becomes abstract.
Correct Answer: a) It cannot be overridden by subclasses.
Explanation:
The final modifier on a method locks its implementation, preventing subclasses from overriding it.

23. What is the purpose of the static keyword when applied to a variable?

a) It creates a class-level variable shared across all instances rather than separate instance copies.
b) It makes the variable immutable.
c) It restricts variable access to private scope.
d) It stores the variable on the call stack.
Correct Answer: a) It creates a class-level variable shared across all instances rather than separate instance copies.
Explanation:
Static variables belong to the class itself rather than any specific object instance.

24. Can a static method in Java directly access non-static (instance) variables or methods without an object reference?

a) Yes, always
b) No, because static context has no implicit this reference
c) Only if declared in an abstract class
d) Only inside constructors
Correct Answer: b) No, because static context has no implicit this reference
Explanation:
Static methods exist independently of object instances, so they cannot directly access instance state without an object reference.

25. What is an interface default method introduced in Java 8?

a) A method in an interface with a body, allowing backward-compatible API evolution.
b) A method that is automatically private.
c) A method that must be overridden by every implementing class.
d) A constructor inside an interface.
Correct Answer: a) A method in an interface with a body, allowing backward-compatible API evolution.
Explanation:
Default methods allow developers to add new methods to interfaces without breaking existing implementations.

26. Can an interface contain static methods in Java 8 and later?

a) No, static methods are restricted to classes.
b) Yes, interfaces can declare public static helper methods.
c) Only if marked as abstract.
d) Only in inner interfaces.
Correct Answer: b) Yes, interfaces can declare public static helper methods.
Explanation:
Java 8 enabled static methods in interfaces to house utility methods related to the interface domain.

27. What is composition in Object-Oriented Programming?

a) A 'has-a' relationship where a class contains references to objects of other classes as member fields.
b) A 'is-a' relationship established via inheritance.
c) The conversion of primitive types to wrapper objects.
d) The process of compiling Java source code.
Correct Answer: a) A 'has-a' relationship where a class contains references to objects of other classes as member fields.
Explanation:
Composition models complex objects by combining simpler objects through instance variables ('has-a').

28. What is the primary difference between aggregation and composition?

a) Aggregation implies a weak 'has-a' relationship where child objects can exist independently; composition implies a strong ownership where child lifecycle depends on the parent.
b) Aggregation uses inheritance, while composition uses interfaces.
c) Composition is unidirectional, while aggregation is bidirectional.
d) There is no functional difference in Java.
Correct Answer: a) Aggregation implies a weak 'has-a' relationship where child objects can exist independently; composition implies a strong ownership where child lifecycle depends on the parent.
Explanation:
Composition represents strict ownership (part-of), whereas aggregation represents looser association.

29. What is an anonymous inner class in Java?

a) An unnamed local inner class defined and instantiated simultaneously in a single expression.
b) A class without any methods.
c) A class that cannot be garbage collected.
d) A class defined inside a package header.
Correct Answer: a) An unnamed local inner class defined and instantiated simultaneously in a single expression.
Explanation:
Anonymous inner classes provide a concise way to extend classes or implement interfaces on the fly.

30. What is a nested static class in Java?

a) A static class defined inside another class that does not require an enclosing instance to be instantiated.
b) A class that cannot have static members.
c) An interface implemented by static methods.
d) A top-level class with private scope.
Correct Answer: a) A static class defined inside another class that does not require an enclosing instance to be instantiated.
Explanation:
A static nested class is associated with its outer class but behaves like a top-level class regarding object creation.

31. What is the role of an inner class (non-static nested class)?

a) It has access to all members (including private) of its enclosing outer instance.
b) It must be instantiated without an outer object reference.
c) It cannot contain instance variables.
d) It replaces inheritance entirely.
Correct Answer: a) It has access to all members (including private) of its enclosing outer instance.
Explanation:
Non-static inner classes maintain an implicit reference to the enclosing outer class instance, accessing its members directly.

32. What is object cloning in Java?

a) Creating an exact copy of an existing object instance.
b) Serializing an object to a database.
c) Casting a subclass reference to a superclass.
d) Comparing two objects for equality.
Correct Answer: a) Creating an exact copy of an existing object instance.
Explanation:
Cloning duplicates an object, which can be shallow or deep depending on how reference fields are handled.

33. What is the difference between a shallow copy and a deep copy?

a) A shallow copy duplicates object references, whereas a deep copy recursively clones referenced objects to create independent copies.
b) Shallow copy is performed on heap, deep copy on stack.
c) Shallow copy creates immutable objects, deep copy creates mutable objects.
d) There is no difference.
Correct Answer: a) A shallow copy duplicates object references, whereas a deep copy recursively clones referenced objects to create independent copies.
Explanation:
Shallow copies share inner object references with the original, while deep copies ensure complete independence.

34. Which method is defined in java.lang.Object to compare two object instances for logical equality?

a) isEqual(Object o)
b) equals(Object obj)
c) compare(Object o)
d) match(Object o)
Correct Answer: b) equals(Object obj)
Explanation:
The equals method compares object contents for logical equality, whereas '==' compares memory address references.

35. What is the contract between equals() and hashCode() in Java?

a) If two objects are equal according to equals(), they must produce the exact same integer hashCode().
b) If two objects have the same hashCode(), they must be equal.
c) They are independent and have no relationship.
d) hashCode() must return a unique memory address.
Correct Answer: a) If two objects are equal according to equals(), they must produce the exact same integer hashCode().
Explanation:
Violating the equals-hashCode contract breaks hash-based collections like HashMap and HashSet.

36. What does the toString() method in java.lang.Object return by default?

a) Class name followed by '@' and the unsigned hexadecimal representation of the hash code.
b) Null pointer exception
c) An empty string
d) Memory offset address in bytes
Correct Answer: a) Class name followed by '@' and the unsigned hexadecimal representation of the hash code.
Explanation:
By default, toString() outputs format like 'ClassName@1a2b3c', which is typically overridden for meaningful representation.

37. What is downcasting in Java object-oriented programming?

a) Casting a superclass reference down to a subclass reference type.
b) Converting a subclass reference to a superclass type.
c) Converting a primitive integer to a long.
d) Unboxing wrapper objects.
Correct Answer: a) Casting a superclass reference down to a subclass reference type.
Explanation:
Downcasting explicitly converts a superclass reference back to a subclass type, requiring a valid runtime type to avoid ClassCastException.

38. What is upcasting in Java?

a) Casting a subclass reference to a superclass type.
b) Casting a superclass reference to a subclass type.
c) Converting primitive values to strings.
d) Allocating objects on the stack.
Correct Answer: a) Casting a subclass reference to a superclass type.
Explanation:
Upcasting is implicit and treats a subclass object as its superclass type, underpinning polymorphism.

39. Which operator is used in Java to test whether an object is an instance of a specific class or implements an interface?

a) typeof
b) instanceof
c) isInstance
d) check
Correct Answer: b) instanceof
Explanation:
The instanceof operator checks runtime object types safely before performing explicit downcasting.

40. What is an immutable object in Java?

a) An object whose state cannot be changed after it is constructed.
b) An object stored in read-only ROM memory.
c) An object that cannot be garbage collected.
d) An object with zero methods.
Correct Answer: a) An object whose state cannot be changed after it is constructed.
Explanation:
Immutable objects are thread-safe and secure because their internal state remains constant post-initialization.

41. Which of the following is a classic example of an immutable class in the standard Java library?

a) java.lang.StringBuilder
b) java.util.ArrayList
c) java.lang.String
d) java.util.Date
Correct Answer: c) java.lang.String
Explanation:
String instances are immutable; any modification operation returns a newly created String object.

42. What is the purpose of the transient keyword in Java object serialization?

a) To prevent specific fields from being serialized when an object is written to a stream.
b) To make fields temporary and volatile across threads.
c) To encrypt field values.
d) To speed up method execution.
Correct Answer: a) To prevent specific fields from being serialized when an object is written to a stream.
Explanation:
Transient fields are ignored during object serialization, useful for sensitive data or non-serializable references.

43. What is the purpose of the volatile keyword in Java concurrency?

a) To ensure visibility of changes to variables across threads by bypassing CPU cache.
b) To make variables constant.
c) To synchronize entire code blocks.
d) To make objects immutable.
Correct Answer: a) To ensure visibility of changes to variables across threads by bypassing CPU cache.
Explanation:
volatile guarantees that reads and writes go straight to main memory, preventing thread caching issues.

44. What is method hiding in Java?

a) When a subclass defines a static method with the same signature as a static method in its superclass.
b) When a private method is inherited.
c) When an abstract method lacks a body.
d) When overloading methods with different return types.
Correct Answer: a) When a subclass defines a static method with the same signature as a static method in its superclass.
Explanation:
Static methods are hidden rather than overridden, meaning resolution is based on reference type rather than runtime object type.

45. Can an abstract class implement an interface without providing bodies for all interface abstract methods?

a) Yes, the abstract class can leave them abstract for its concrete subclasses to implement.
b) No, abstract classes must implement all interface methods immediately.
c) Only if marked as final.
d) Only in Java 17 and above.
Correct Answer: a) Yes, the abstract class can leave them abstract for its concrete subclasses to implement.
Explanation:
Abstract classes can defer interface method implementation to their concrete subclasses.

46. What is a marker interface in Java?

a) An empty interface with no methods or fields used to signal metadata to the JVM or frameworks (e.g., Serializable).
b) An interface that marks errors in code.
c) An interface used for graphic rendering.
d) An interface with only default methods.
Correct Answer: a) An empty interface with no methods or fields used to signal metadata to the JVM or frameworks (e.g., Serializable).
Explanation:
Marker interfaces tag classes with specific capabilities recognized by serialization or runtime frameworks.

47. What is a functional interface in Java?

a) An interface containing exactly one abstract method, eligible for lambda expression assignment.
b) An interface with multiple static helper methods.
c) An interface used exclusively for math calculations.
d) An interface that cannot be implemented.
Correct Answer: a) An interface containing exactly one abstract method, eligible for lambda expression assignment.
Explanation:
Functional interfaces (annotated with @FunctionalInterface) form the basis of Java's lambda and stream architecture.

48. Which annotation is used to explicitly mark a functional interface?

a) @FunctionalInterface
b) @Interface
c) @LambdaTarget
d) @SingleMethod
Correct Answer: a) @FunctionalInterface
Explanation:
The @FunctionalInterface annotation triggers a compile-time check ensuring the interface has strictly one abstract method.

49. What is a covariant return type in Java method overriding?

a) A subclass overriding method returning a narrower (subtype) type than the superclass method's return type.
b) Returning primitive types instead of objects.
c) Returning multiple values from a method.
d) Returning void from an abstract method.
Correct Answer: a) A subclass overriding method returning a narrower (subtype) type than the superclass method's return type.
Explanation:
Covariant return types allow an overriding method to return a subclass of the superclass method's return type.

50. What is constructor chaining in Java?

a) Calling one constructor from another within the same class using this() or from a superclass using super().
b) Creating long chains of object inheritance.
c) Linking multiple interfaces together.
d) Executing static blocks sequentially.
Correct Answer: a) Calling one constructor from another within the same class using this() or from a superclass using super().
Explanation:
Constructor chaining avoids code duplication by allowing constructors to invoke other constructors during object creation.

51. What is the strict rule regarding the placement of this() or super() inside a constructor?

a) They must be the very first statement in the constructor body.
b) They can be placed anywhere inside the constructor.
c) They must be placed at the end of the constructor.
d) They are optional and can be placed inside try-catch blocks.
Correct Answer: a) They must be the very first statement in the constructor body.
Explanation:
Java mandates that this() or super() must be the first executable statement in any constructor.

52. Can a constructor be marked as private?

a) Yes, commonly used in Singleton design patterns and utility classes to prevent direct instantiation.
b) No, constructors must always be public.
c) Only in abstract classes.
d) Only when implementing interfaces.
Correct Answer: a) Yes, commonly used in Singleton design patterns and utility classes to prevent direct instantiation.
Explanation:
Private constructors restrict object creation to within the class itself, foundational for patterns like Singleton.

53. What is the Singleton Design Pattern?

a) A design pattern that restricts class instantiation to a single instance and provides a global access point.
b) A pattern for creating multiple threads.
c) A pattern for connecting to relational databases.
d) A pattern for handling GUI events.
Correct Answer: a) A design pattern that restricts class instantiation to a single instance and provides a global access point.
Explanation:
Singleton ensures only one object of the class exists throughout the JVM lifecycle.

54. What is the Factory Design Pattern?

a) A creational pattern that provides an interface for creating objects without specifying their exact concrete classes.
b) A pattern for destroying objects efficiently.
c) A pattern for locking database tables.
d) A pattern for sorting collections.
Correct Answer: a) A creational pattern that provides an interface for creating objects without specifying their exact concrete classes.
Explanation:
Factory pattern encapsulates object creation logic, decoupling client code from concrete implementations.

55. What is the Builder Design Pattern?

a) A creational pattern designed to construct complex objects step-by-step with readable fluent API chaining.
b) A pattern for building graphical user interfaces.
c) A pattern for compiling Java code.
d) A pattern for multithreaded synchronization.
Correct Answer: a) A creational pattern designed to construct complex objects step-by-step with readable fluent API chaining.
Explanation:
Builder pattern simplifies creating complex objects with numerous optional parameters without overloaded constructors.

56. What is loose coupling in Object-Oriented Design?

a) A design approach where classes are independent, interacting through well-defined interfaces with minimal dependencies.
b) A technique where all classes share a single global state.
c) Avoiding the use of interfaces entirely.
d) Using public fields across all packages.
Correct Answer: a) A design approach where classes are independent, interacting through well-defined interfaces with minimal dependencies.
Explanation:
Loose coupling enhances maintainability, testability, and modularity in software architecture.

57. What is high cohesion?

a) A design principle where a class or module has a single, well-focused responsibility with closely related behaviors.
b) Packing all program logic into a single massive class.
c) Using tight inheritance hierarchies.
d) Maximizing global variable sharing.
Correct Answer: a) A design principle where a class or module has a single, well-focused responsibility with closely related behaviors.
Explanation:
High cohesion ensures modules are self-contained and focused on performing one clear task.

58. What is the Liskov Substitution Principle (LSP) in SOLID design?

a) Objects of a superclass should be replaceable with objects of its subclasses without breaking application correctness.
b) Subclasses must implement all superclass methods as abstract.
c) Classes should have multiple responsibilities.
d) Interfaces should be as large as possible.
Correct Answer: a) Objects of a superclass should be replaceable with objects of its subclasses without breaking application correctness.
Explanation:
LSP ensures inheritance hierarchies are designed correctly so child classes honor parent contracts.

59. What is the Open-Closed Principle (OCP)?

a) Software entities should be open for extension but closed for modification.
b) Classes must remain open to public access and closed to private modifications.
c) Methods should be open to overriding and closed to overloading.
d) Packages must be open for deletion.
Correct Answer: a) Software entities should be open for extension but closed for modification.
Explanation:
OCP advocates adding new functionality through inheritance or composition rather than altering existing tested code.

60. What is the Dependency Inversion Principle (DIP)?

a) High-level modules should not depend on low-level modules; both should depend on abstractions.
b) Low-level modules must inherit directly from high-level modules.
c) Dependencies should be hardcoded inside constructors.
d) Avoid using interfaces in large systems.
Correct Answer: a) High-level modules should not depend on low-level modules; both should depend on abstractions.
Explanation:
DIP promotes decoupling via interfaces and abstract classes, facilitating dependency injection.

61. What is an abstract method in Java?

a) A method declared without a body (terminated with a semicolon) inside an abstract class or interface.
b) A method that executes asynchronously.
c) A method with private visibility.
d) A method that returns null.
Correct Answer: a) A method declared without a body (terminated with a semicolon) inside an abstract class or interface.
Explanation:
Abstract methods establish mandatory implementation contracts for concrete subclasses.

62. Can an abstract class contain concrete (implemented) methods?

a) Yes, abstract classes can mix abstract and fully implemented concrete methods.
b) No, all methods in an abstract class must be abstract.
c) Only if marked as static.
d) Only in Java 8 and above.
Correct Answer: a) Yes, abstract classes can mix abstract and fully implemented concrete methods.
Explanation:
Abstract classes can provide shared utility code in concrete methods while forcing subclasses to override abstract ones.

63. What happens if a concrete subclass fails to implement even one abstract method inherited from its abstract superclass?

a) The subclass itself must also be declared abstract; otherwise, it causes a compile-time error.
b) The compiler automatically generates an empty body for the method.
c) A runtime exception is thrown during instantiation.
d) The method defaults to returning null.
Correct Answer: a) The subclass itself must also be declared abstract; otherwise, it causes a compile-time error.
Explanation:
Concrete classes must provide implementations for all inherited abstract methods.

64. What is the purpose of the instanceof operator combined with pattern matching in modern Java?

a) To check object type and automatically cast and bind it to a variable in a single concise expression.
b) To serialize objects faster.
c) To compare two hash codes.
d) To replace try-catch blocks.
Correct Answer: a) To check object type and automatically cast and bind it to a variable in a single concise expression.
Explanation:
Pattern matching for instanceof (standardized in recent Java versions) eliminates boilerplate explicit type casting.

65. What is a record class introduced in Java 14/16?

a) A concise nominal carrier class for immutable data, automatically generating constructors, equals, hashCode, and getters.
b) A class used to record audio and video streams.
c) A mutable data structure for databases.
d) An interface for logging transactions.
Correct Answer: a) A concise nominal carrier class for immutable data, automatically generating constructors, equals, hashCode, and getters.
Explanation:
Records simplify creating immutable data transfer objects (DTOs) with minimal boilerplate code.

66. Can a record class extend another class in Java?

a) No, records implicitly extend java.lang.Record and cannot extend other classes (though they can implement interfaces).
b) Yes, records support full class inheritance.
c) Only if marked as abstract.
d) Only when implementing Serializable.
Correct Answer: a) No, records implicitly extend java.lang.Record and cannot extend other classes (though they can implement interfaces).
Explanation:
Records have restrictions on inheritance to guarantee their role as immutable data carriers.

67. What is a sealed class in Java?

a) A class that restricts which other classes can extend or implement it using permitted subclasses.
b) A final class that cannot be accessed across packages.
c) A private class inside a package.
d) A class sealed against garbage collection.
Correct Answer: a) A class that restricts which other classes can extend or implement it using permitted subclasses.
Explanation:
Sealed classes give developers fine-grained control over inheritance hierarchies.

68. Which keyword is used in conjunction with sealed classes to specify authorized subclasses?

a) permits
b) allows
c) authorized
d) supports
Correct Answer: a) permits
Explanation:
The permits clause defines the exact set of subclasses allowed to extend a sealed class.

69. What must permitted subclasses of a sealed class be declared as?

a) Either final, non-sealed, or sealed themselves.
b) Always abstract.
c) Always private inner classes.
d) Always interfaces.
Correct Answer: a) Either final, non-sealed, or sealed themselves.
Explanation:
Permit rules require subclasses to explicitly state their inheritance intention regarding the sealed hierarchy.

70. What is the difference between object-oriented programming and procedural programming?

a) OOP organizes software around objects combining data and behavior, whereas procedural programming focuses on functions and linear procedures acting on data.
b) Procedural programming supports inheritance while OOP does not.
c) OOP only runs on virtual machines, while procedural code runs natively.
d) There is no fundamental difference.
Correct Answer: a) OOP organizes software around objects combining data and behavior, whereas procedural programming focuses on functions and linear procedures acting on data.
Explanation:
OOP models real-world entities as objects encapsulating state and logic, contrasting with procedural step-by-step procedures.

71. What is data abstraction?

a) Hiding complex implementation details and exposing only essential features and behavior to the user.
b) Encrypting database passwords.
c) Converting objects into byte streams.
d) Removing duplicate code via loops.
Correct Answer: a) Hiding complex implementation details and exposing only essential features and behavior to the user.
Explanation:
Abstraction simplifies interaction with complex systems by exposing high-level interfaces.

72. How is abstraction primarily achieved in Java?

a) Through abstract classes and interfaces.
b) Through private variables and getters.
c) Through static methods and final fields.
d) Through method overloading.
Correct Answer: a) Through abstract classes and interfaces.
Explanation:
Abstract classes and interfaces define contracts and hide underlying implementation details.

73. Can an interface extend another interface in Java?

a) Yes, an interface can extend multiple interfaces using the extends keyword.
b) No, interfaces cannot inherit from other interfaces.
c) Only if implementing a class.
d) Only using the implements keyword.
Correct Answer: a) Yes, an interface can extend multiple interfaces using the extends keyword.
Explanation:
Interfaces support multiple inheritance of behavior by extending multiple parent interfaces.

74. What is the access level of fields declared inside an interface?

a) Public, static, and final by default.
b) Private and mutable by default.
c) Protected and transient.
d) Package-private instance variables.
Correct Answer: a: Public, static, and final by default.
Explanation:
Interface fields are implicitly public static final constants.

75. What happens if a class implements two interfaces that both contain a default method with the exact same signature?

a) A compile-time error occurs unless the implementing class explicitly overrides and resolves the conflict.
b) Java randomly picks one default method.
c) Both methods execute concurrently.
d) The program throws a ClassCastException.
Correct Answer: a) A compile-time error occurs unless the implementing class explicitly overrides and resolves the conflict.
Explanation:
Diamond ambiguity with default methods requires the implementing class to explicitly provide its own override (e.g., Super.super.method()).

76. What is the purpose of the instanceof check in polymorphism?

a) To safely verify an object's runtime type before downcasting to avoid ClassCastException.
b) To create new object instances.
c) To check if a method is static.
d) To compare two strings.
Correct Answer: a) To safely verify an object's runtime type before downcasting to avoid ClassCastException.
Explanation:
instanceof ensures safe type conversions in polymorphic hierarchies.

77. What is delegation in object-oriented design?

a) A design mechanism where an object handles a request by handing it off to a helper or delegate object.
b) Passing method arguments by reference.
c) Inheriting private fields from a superclass.
d) Converting checked exceptions to unchecked.
Correct Answer: a) A design mechanism where an object handles a request by handing it off to a helper or delegate object.
Explanation:
Delegation is an alternative to inheritance where responsibility is forwarded to a collaborator object ('delegation over inheritance').

78. What is a wrapper class in Java?

a) A class that encapsulates a primitive data type into an object (e.g., Integer for int).
b) A class that wraps around database connections.
c) A class used to handle GUI window frames.
d) A class that catches exceptions.
Correct Answer: a) A class that encapsulates a primitive data type into an object (e.g., Integer for int).
Explanation:
Wrapper classes allow primitives to be used in collections and generic programming structures.

79. What is autoboxing in Java?

a) The automatic conversion of primitive types to their corresponding wrapper object types by the compiler.
b) The automatic serialization of objects to files.
c) The packaging of source code into JAR files.
d) The automatic creation of thread pools.
Correct Answer: a) The automatic conversion of primitive types to their corresponding wrapper object types by the compiler.
Explanation:
Autoboxing seamlessly converts primitives like int to Integer when assigned to object references.

80. What is unboxing in Java?

a) The automatic conversion of wrapper object types back into their corresponding primitive types.
b) Extracting files from a ZIP archive.
c) Deserializing objects from a byte stream.
d) Casting a subclass to a superclass.
Correct Answer: a) The automatic conversion of wrapper object types back into their corresponding primitive types.
Explanation:
Unboxing automatically extracts primitive values from wrapper objects during mathematical or assignment operations.

81. Can primitive types be used directly as type arguments in Java generics (e.g., List)?

a) No, generics require object reference types, so wrapper classes (e.g., List) must be used.
b) Yes, Java automatically converts primitives in generic collections.
c) Only in Java 17 and above.
d) Only for float and double types.
Correct Answer: a) No, generics require object reference types, so wrapper classes (e.g., List) must be used.
Explanation:
Generics rely on type erasure and reference types; primitives cannot be direct type parameters.

82. What is type erasure in Java generics?

a) The compiler process that removes generic type parameters during compilation, replacing them with Object or bounds for bytecode compatibility.
b) Erasing variables from memory during garbage collection.
c) Deleting unused classes from a package.
d) Clearing collection elements at runtime.
Correct Answer: a) The compiler process that removes generic type parameters during compilation, replacing them with Object or bounds for bytecode compatibility.
Explanation:
Type erasure ensures backward compatibility with pre-generics Java bytecode.

83. What is method hiding vs method overriding?

a) Overriding applies to instance methods (resolved at runtime via dynamic dispatch); hiding applies to static methods (resolved at compile-time via reference type).
b) Method hiding applies to private methods, overriding to public methods.
c) They are identical concepts.
d) Method hiding occurs in interfaces, overriding in abstract classes.
Correct Answer: a) Overriding applies to instance methods (resolved at runtime via dynamic dispatch); hiding applies to static methods (resolved at compile-time via reference type).
Explanation:
Static methods are hidden, whereas instance methods are overridden.

84. What is the significance of the Object class in Java?

a) It is the root superclass of every class in Java; all classes inherit its methods like toString(), equals(), and hashCode().
b) It is an interface implemented by all threads.
c) It manages garbage collection thresholds.
d) It provides mathematical constants.
Correct Answer: a) It is the root superclass of every class in Java; all classes inherit its methods like toString(), equals(), and hashCode().
Explanation:
Every class implicitly or explicitly inherits from java.lang.Object.

85. What is the purpose of the finalize() method in java.lang.Object (deprecated in modern Java)?

a) To perform cleanup actions before an object is garbage collected.
b) To finalize method overriding rules.
c) To close database connections safely.
d) To force immediate garbage collection.
Correct Answer: a) To perform cleanup actions before an object is garbage collected.
Explanation:
finalize() was intended for cleanup before garbage collection, but is deprecated due to unpredictability and performance issues.

86. What is object composition preferred over inheritance in many design scenarios?

a) Composition offers greater flexibility, avoids fragile base class problems, and allows dynamic behavior changes at runtime.
b) Composition executes twice as fast as inheritance.
c) Inheritance cannot access private fields.
d) Inheritance requires more memory.
Correct Answer: a) Composition offers greater flexibility, avoids fragile base class problems, and allows dynamic behavior changes at runtime.
Explanation:
Principle of 'favor composition over inheritance' helps prevent rigid hierarchies and tight coupling.

87. What is a copy constructor in Java?

a) A constructor that accepts an instance of the same class and initializes a new object as a copy of it.
b) A constructor that duplicates bytecode.
c) A method that clones arrays.
d) A constructor generated by default.
Correct Answer: a) A constructor that accepts an instance of the same class and initializes a new object as a copy of it.
Explanation:
Copy constructors provide a clean way to instantiate new objects with duplicated state values.

88. Can a class be both final and abstract in Java?

a) No, because final prevents inheritance while abstract requires inheritance.
b) Yes, for utility classes.
c) Only in interfaces.
d) Only when using sealed classes.
Correct Answer: a) No, because final prevents inheritance while abstract requires inheritance.
Explanation:
Final and abstract are mutually exclusive modifiers; combining them causes a compile-time error.

89. What is the purpose of access modifiers in encapsulation?

a) To enforce information hiding and control where classes, methods, and variables can be accessed.
b) To encrypt source code files.
c) To determine thread priority.
d) To optimize garbage collection.
Correct Answer: a) To enforce information hiding and control where classes, methods, and variables can be accessed.
Explanation:
Access modifiers (public, protected, private, default) enforce the boundary of encapsulation.

90. What is a callback in Object-Oriented Programming?

a) Passing an executable reference of a method or object to another code component so it can be invoked later upon an event.
b) Returning a value from a recursive method.
c) Calling a superclass constructor.
d) Re-throwing an exception.
Correct Answer: a) Passing an executable reference of a method or object to another code component so it can be invoked later upon an event.
Explanation:
Callbacks (often implemented via interfaces or lambdas) enable asynchronous event handling and decoupled notification.

91. What is the difference between a class invariant and a method precondition?

a) A class invariant is a condition that must always hold true for a valid object state; a precondition is a condition that must be true when a method is invoked.
b) Invariants apply only to static fields, preconditions to instance methods.
c) There is no distinction.
d) Preconditions are checked by garbage collector.
Correct Answer: a) A class invariant is a condition that must always hold true for a valid object state; a precondition is a condition that must be true when a method is invoked.
Explanation:
Design by contract uses invariants and preconditions to define robust object boundaries and method rules.

92. Can static methods be overridden in Java?

a) No, static methods are hidden, not overridden, because dispatch is determined at compile-time by reference type.
b) Yes, if marked as final.
c) Only in abstract classes.
d) Yes, using dynamic method dispatch.
Correct Answer: a) No, static methods are hidden, not overridden, because dispatch is determined at compile-time by reference type.
Explanation:
Static binding prevents polymorphism on static methods.

93. What is the main advantage of programming to an interface rather than an implementation?

a) It promotes flexibility, allows substitution of concrete implementations, and decouples client code from specific logic.
b) It reduces execution speed.
c) It eliminates the need for constructors.
d) It allows multiple inheritance of state.
Correct Answer: a) It promotes flexibility, allows substitution of concrete implementations, and decouples client code from specific logic.
Explanation:
Programming to interfaces is a core tenet of robust object-oriented architectural design.

94. What is object state?

a) The current values of an object's instance variables at any given moment.
b) The compiled bytecode of the class.
c) The memory address where the object resides.
d) The list of implemented interfaces.
Correct Answer: a) The current values of an object's instance variables at any given moment.
Explanation:
State represents data stored within fields, distinguishing one object instance from another.

95. What is object behavior?

a) The actions and operations an object can perform, defined by its methods.
b) The way the garbage collector manages the object.
c) The exception handling mechanism.
d) The compilation process.
Correct Answer: a) The actions and operations an object can perform, defined by its methods.
Explanation:
Behavior defines what an object can do, encapsulating logic alongside its state.
← Previous: Latest Java Generics MCQs
Next →: Latest Java OOP MCQs
JavaScript Prototypes & Inheritance MCQs for Developer Interviews

JavaScript Prototypes & Inheritance MCQs for Developer Interviews

JavaScript implements inheritance exclusively through a prototype-based model rather than traditional class-based mechanics found in languages like Java or C++.…

By MCQs Generator
Python OOP MCQs

Python OOP MCQs

Object-Oriented Programming (OOP) in Python is a programming paradigm that uses classes and objects to model real world entities, promoting…

By MCQs Generator
Java Multithreading & Concurrency MCQs

Java Multithreading & Concurrency MCQs

Java multithreading and concurrency are core pillars for building high-performance, responsive applications that execute multiple tasks simultaneously. Utilizing the java.util.concurrent…

By MCQs Generator