Java OOP Essentials: 136 MCQs with answers

All 136 multiple-choice questions from this kit, free and with no sign-up.

Warm-up · 63 questions

Q1. Which access modifier allows access only within the same class?

Beginner
A `protected` B `private` C `public` D package-private
Show answer & explanation

`private`

`private` is the most restrictive access level; it restricts access to the same class only.

Q2. What is the default access level in Java when no modifier is written?

Beginner
A `private` B package-private C `protected` D `public`
Show answer & explanation

package-private

If you don't write a modifier, the member is accessible to any class in the same package, which is called package-private (or default) access.

Q3. Which access modifier allows access within the same package and to subclasses in other packages?

Beginner
A package-private B `public` C `protected` D `private`
Show answer & explanation

`protected`

`protected` extends package-private access by also allowing subclasses (even in different packages) to access the member.

Q4. What is the main benefit of data hiding?

Beginner
A It makes fields public B It makes code longer C It allows any class to access fields D It prevents external code from setting invalid values
Show answer & explanation

It prevents external code from setting invalid values

Data hiding, by making fields private, prevents external code from directly setting invalid values, thus protecting the integrity of the object's state.

Q5. Which of the following is NOT a benefit of encapsulation?

Beginner
A Flexibility B Increased execution speed C Maintainability D Data hiding
Show answer & explanation

Increased execution speed

Encapsulation does not directly increase execution speed; its benefits are data hiding, maintainability, flexibility, and security.

Q6. A `protected` member is accessible to any class in the same package and to subclasses in other packages.

Beginner
A True B False
Show answer & explanation

True

This is the definition of `protected` access: it extends package-private access with subclass access across packages.

Q7. What is encapsulation in Java?

Beginner
Show answer & explanation

—

This is the core definition.

Q8. List the four access levels in Java from most restrictive to least restrictive.

Beginner
Show answer & explanation

—

This order is essential for understanding visibility.

Q9. What is the visibility of a `private` member?

Beginner
Show answer & explanation

—

No other class, not even subclasses, can access it directly.

Q10. What is the default access level in Java when no modifier is specified?

Beginner
Show answer & explanation

—

This is also called default access.

Q11. What is the visibility of a `protected` member?

Beginner
Show answer & explanation

—

Protected extends package-private with subclass access.

Q12. What is the visibility of a `public` member?

Beginner
Show answer & explanation

—

No restrictions.

Q13. What is a getter method?

Beginner
Show answer & explanation

—

Getters provide read access without exposing the field directly.

Q14. What is a setter method?

Beginner
Show answer & explanation

—

Setters allow controlled modification with validation.

Q15. Name two benefits of encapsulation.

Beginner
Show answer & explanation

—

These are the key benefits listed in the source.

Q16. What is a common pattern that uses encapsulation in Java?

Beginner
Show answer & explanation

—

JavaBeans are a classic example.

Q17. What is a class in Java?

Beginner
A A concrete instance of data B A blueprint for creating objects C A variable that stores a value D A method that performs an action
Show answer & explanation

A blueprint for creating objects

A class defines the structure (fields) and behavior (methods) that objects will have. It is not an instance itself; it's a template.

Q18. Which keyword is used to create an object in Java?

Beginner
A new B create C class D object
Show answer & explanation

new

The `new` keyword allocates memory and calls a constructor to initialize the object. Without it, no object is created.

Q19. What does a reference variable store?

Beginner
A The class name B A memory address of the object C The object's methods D The actual object data
Show answer & explanation

A memory address of the object

Reference variables hold a reference (memory address) to the object, not the object's data itself. This is key to understanding aliasing.

Q20. Which of the following correctly creates a new `Dog` object?

Beginner
A Dog d = create Dog(); B new Dog d; C Dog d = new Dog(); D Dog d = Dog();
Show answer & explanation

Dog d = new Dog();

The correct syntax is `Dog d = new Dog();`. The `new` keyword is required to instantiate the object.

Q21. Which of the following is a primitive type in Java?

Beginner
A Scanner B String C Car D int
Show answer & explanation

int

`int` is a primitive type that stores values directly. `String`, `Car`, and `Scanner` are reference types.

Q22. What does the dot operator (`.`) do in Java?

Beginner
A It compares two objects B It creates a new object C It declares a variable D It accesses fields and methods of an object
Show answer & explanation

It accesses fields and methods of an object

The dot operator is used to access an object's fields and methods, e.g., `myCar.color` or `myCar.accelerate()`.

Q23. If a class has no constructor defined, what happens?

Beginner
A The object is created without initialization B The class cannot be instantiated C A default constructor is provided D A compile-time error occurs
Show answer & explanation

A default constructor is provided

Java automatically provides a default constructor with no parameters if no constructor is defined, allowing object creation.

Q24. A reference variable stores the actual object data.

Beginner
A True B False
Show answer & explanation

False

A reference variable stores a memory address (reference) to the object, not the object's data itself. The actual data is stored in the heap.

Q25. Declaring a reference variable creates an object in memory.

Beginner
A True B False
Show answer & explanation

False

Declaring a reference variable only creates a variable that can hold a reference. The object is created only when you use the `new` keyword.

Q26. What is a class in Java?

Beginner
Show answer & explanation

—

This tests the fundamental definition of a class.

Q27. What does the `new` keyword do?

Beginner
Show answer & explanation

—

This tests understanding of object creation.

Q28. How do you access fields and methods of an object?

Beginner
Show answer & explanation

—

This tests basic object access syntax.

Q29. What is the default value of a reference variable that has not been assigned an object?

Beginner
Show answer & explanation

—

Reference variables are initialized to `null` by default.

Q30. What exception is thrown when you call a method on a `null` reference?

Beginner
Show answer & explanation

—

This tests knowledge of a common runtime error.

Q31. What is object state?

Beginner
Show answer & explanation

—

State is the data part of an object.

Q32. What is object behavior?

Beginner
Show answer & explanation

—

Behavior is the functionality part of an object.

Q33. If no constructor is defined in a class, what happens?

Beginner
Show answer & explanation

—

This tests knowledge of default constructors.

Q34. Do two objects of the same class share their instance fields?

Beginner
Show answer & explanation

—

This tests the concept of instance independence.

Q35. What is the result of `Car myCar;` without `new`?

Beginner
Show answer & explanation

—

This tests the difference between declaration and instantiation.

Q36. What is the purpose of the dot operator?

Beginner
Show answer & explanation

—

This tests basic syntax.

Q37. Which of the following best describes a static field?

Beginner
A A variable that is automatically final B A variable that can only be accessed within the class C A variable shared by all instances of the class D A variable that belongs to each object separately
Show answer & explanation

A variable shared by all instances of the class

A static field is a class variable; there is only one copy shared by all instances, unlike instance fields which are per-object.

Q38. Which of the following is a valid way to call a static method `foo()` of class `MyClass`?

Beginner
A `foo()` directly B `new MyClass().foo()` C `MyClass.new foo()` D `MyClass.foo()`
Show answer & explanation

`MyClass.foo()`

Static methods are called using the class name, e.g., `MyClass.foo()`. They can also be called via an object, but that's discouraged.

Q39. When is a static block executed?

Beginner
A Every time an object is created B When the class is first loaded C When the program terminates D When the first static method is called
Show answer & explanation

When the class is first loaded

A static block runs exactly once when the class is loaded into memory, before any instance creation or static method invocation.

Q40. Which of the following is a correct declaration of a static constant?

Beginner
A `public final int MAX = 10;` B `public static final int MAX = 10;` C `static final MAX = 10;` D `public static int MAX = 10;`
Show answer & explanation

`public static final int MAX = 10;`

A static constant uses both `static` (class-level) and `final` (unchangeable), with a type and value.

Q41. A static block executes every time a new object of the class is created.

Beginner
A True B False
Show answer & explanation

False

A static block runs only once, when the class is first loaded, not on each object creation.

Q42. What is the difference between a static field and an instance field?

Beginner
Show answer & explanation

—

This is the fundamental distinction between class-level and object-level data.

Q43. Why is the `main` method declared static?

Beginner
Show answer & explanation

—

The entry point of a Java program cannot rely on object creation.

Q44. What is a static block and when does it run?

Beginner
Show answer & explanation

—

It is used for complex static initialization.

Q45. Give an example of a static constant and explain why it is useful.

Beginner
Show answer & explanation

—

Static constants are a common pattern for fixed values.

Q46. Can a static method be called using an object reference? Is it recommended?

Beginner
Show answer & explanation

—

The recommended way is to use the class name.

Q47. What happens if you try to access an instance variable from a static method without an object reference?

Beginner
Show answer & explanation

—

The compiler knows there is no instance context.

Q48. What is the purpose of a static initializer block?

Beginner
Show answer & explanation

—

It runs once at class loading time.

Q49. Can a static method access another static method directly?

Beginner
Show answer & explanation

—

Static members can access each other directly.

Q50. What is the primary purpose of a constructor in Java?

Beginner
A To allocate memory for the object B To initialize a new object's state when it is created C To define the class's methods D To destroy objects when they are no longer needed
Show answer & explanation

To initialize a new object's state when it is created

A constructor is a special method that initializes a new object's state when it is created with `new`. It sets up the object's fields and enforces invariants, ensuring the object is in a valid state before use.

Q51. If a class defines no constructors, what does Java provide?

Beginner
A A default no-argument constructor B A private constructor C A parameterized constructor with all fields D No constructor at all
Show answer & explanation

A default no-argument constructor

If no constructor is defined, Java automatically provides a default no-argument constructor that sets fields to their default values (0, false, null).

Q52. What is the effect of defining any constructor in a class?

Beginner
A The default constructor disappears B The default constructor is still provided C The class cannot be instantiated D The class becomes abstract
Show answer & explanation

The default constructor disappears

Defining any constructor removes the default constructor. You must explicitly add a no-argument constructor if you need one.

Q53. Which of the following correctly describes a parameterized constructor?

Beginner
A It has no parameters and sets default values B It is automatically generated by the compiler C It accepts arguments to initialize an object with specific values D It can only be called once per object
Show answer & explanation

It accepts arguments to initialize an object with specific values

A parameterized constructor accepts arguments, allowing you to initialize an object with specific values at creation time, such as `new Student("Alice", 20)`.

Q54. What is constructor overloading?

Beginner
A Having a constructor that calls a method B Having multiple constructors with different parameter lists C Having a constructor with a return type D Having multiple constructors with the same parameter list
Show answer & explanation

Having multiple constructors with different parameter lists

Constructor overloading allows a class to have multiple constructors with different parameter lists, providing flexibility in how objects are created.

Q55. What does the `this` keyword refer to in a constructor?

Beginner
A The superclass B The current instance of the class C The class itself D The constructor's return value
Show answer & explanation

The current instance of the class

`this` refers to the current instance — the object on which the constructor or method is being called.

Q56. The default constructor is provided by the compiler only if the class has no other constructors.

Beginner
A True B False
Show answer & explanation

True

The compiler generates a default no-argument constructor only when no other constructor is defined. If you define any constructor, you must explicitly add a no-arg constructor if needed.

Q57. A constructor can be called using dot notation on an existing object.

Beginner
A True B False
Show answer & explanation

False

Constructors are called only with the `new` keyword. They cannot be invoked on an existing object using dot notation.

Q58. What is a constructor in Java?

Beginner
Show answer & explanation

—

This is the fundamental definition of a constructor.

Q59. What does the default constructor do?

Beginner
Show answer & explanation

—

The compiler provides it only if no other constructor is defined.

Q60. When does the default constructor disappear?

Beginner
Show answer & explanation

—

This is a common source of confusion.

Q61. What is a parameterized constructor?

Beginner
Show answer & explanation

—

It allows setting the initial state directly.

Q62. What is constructor overloading?

Beginner
Show answer & explanation

—

Each constructor must have a unique signature.

Q63. What does the `this` keyword refer to in a constructor?

Beginner
Show answer & explanation

—

It is used to disambiguate fields from parameters and to call other constructors.

Building up · 49 questions

Q64. What is the primary purpose of making fields private and providing public getters/setters?

Intermediate
A To make code run faster B To make fields visible to subclasses C To enforce encapsulation and control access D To allow direct field access from anywhere
Show answer & explanation

To enforce encapsulation and control access

Private fields with public getters/setters enforce encapsulation by hiding data and providing controlled access, allowing validation and preventing invalid states.

Q65. Consider a `BankAccount` class with a private `balance` field. Which method correctly enforces a rule that prevents negative balance?

Intermediate
A `public double getBalance() { return balance; }` B `public void withdraw(double amount) { if (amount > 0 && amount <= balance) balance -= amount; }` C `public void withdraw(double amount) { balance -= amount; }` D `public void setBalance(double b) { balance = b; }`
Show answer & explanation

`public void withdraw(double amount) { if (amount > 0 && amount <= balance) balance -= amount; }`

The correct withdraw method checks that the amount is positive and does not exceed the current balance, preventing the balance from going negative.

Q66. Why does encapsulation reduce coupling between classes?

Intermediate
A Because external code depends on the public interface, not internal details B Because all fields are public C Because classes become larger D Because classes cannot interact
Show answer & explanation

Because external code depends on the public interface, not internal details

Encapsulation hides internal implementation, so external code only depends on the stable public interface (getters/setters), reducing coupling and making refactoring easier.

Q67. Which of the following is a common mistake that breaks encapsulation?

Intermediate
A Providing public getters and setters B Making fields private C Making fields public to avoid writing getters/setters D Using `protected` for fields
Show answer & explanation

Making fields public to avoid writing getters/setters

Making fields public exposes them to direct modification, allowing invalid data and breaking encapsulation. The correct approach is to keep fields private and provide controlled access methods.

Q68. What is the principle of least privilege in the context of access modifiers?

Intermediate
A Use `protected` for all fields B Use the most restrictive access that works C Use `public` for everything D Use package-private for all methods
Show answer & explanation

Use the most restrictive access that works

The principle of least privilege suggests giving each member the minimum access needed, which often means using `private` for fields and only exposing what is necessary.

Q69. In the context of encapsulation, what does a setter method typically do besides updating the field?

Intermediate
A It makes the field public B It validates the input C It returns the field value D It deletes the field
Show answer & explanation

It validates the input

Setters often validate input before updating the field, ensuring the object remains in a valid state.

Q70. Why does encapsulation improve maintainability?

Intermediate
A It makes code longer B It prevents any changes C It isolates internal changes from external code D It makes all fields public
Show answer & explanation

It isolates internal changes from external code

Encapsulation hides internal implementation, so you can change how data is stored or validated without affecting code that uses the class, as long as the public interface stays stable.

Q71. Encapsulation is the same as data hiding.

Intermediate
A True B False
Show answer & explanation

False

Data hiding is a part of encapsulation, but encapsulation is broader—it also includes bundling data with methods and controlling access through an interface.

Q72. How do you enforce encapsulation for a field?

Intermediate
Show answer & explanation

—

This is the standard pattern.

Q73. What is the principle of least privilege in access control?

Intermediate
Show answer & explanation

—

This minimizes exposure and reduces risk.

Q74. What is the relationship between encapsulation and data hiding?

Intermediate
Show answer & explanation

—

Encapsulation includes data hiding but is not limited to it.

Q75. What happens if you make a field public?

Intermediate
Show answer & explanation

—

Public fields allow direct modification without validation.

Q76. Why does encapsulation improve maintainability?

Intermediate
Show answer & explanation

—

The public interface acts as a contract.

Q77. What happens when you assign `obj2 = obj1;` where both are reference variables of the same type?

Intermediate
A A compile-time error occurs B Both variables point to the same object C The object is copied to obj2 D obj2 becomes null
Show answer & explanation

Both variables point to the same object

Assignment copies the reference, not the object. Both variables now refer to the same object, so changes through one are visible through the other.

Q78. What is the primary difference between a class and an object?

Intermediate
A They are the same thing B An object is a blueprint; a class is an instance C A class is a blueprint; an object is an instance D A class holds data; an object holds methods
Show answer & explanation

A class is a blueprint; an object is an instance

A class defines the structure and behavior, while an object is a concrete instance created from that class using `new`.

Q79. What is the state of an object?

Intermediate
A The values of its fields at a given time B The class it belongs to C The memory address it occupies D The methods it can perform
Show answer & explanation

The values of its fields at a given time

State is the data stored in an object's fields. Methods define behavior, not state.

Q80. What happens if you call a method on a `null` reference?

Intermediate
A The method returns null B A compile-time error occurs C The program continues silently D A NullPointerException is thrown
Show answer & explanation

A NullPointerException is thrown

Calling a method on a `null` reference causes a `NullPointerException` at runtime, because there is no object to invoke the method on.

Q81. Which of the following correctly describes the behavior of an object?

Intermediate
A It is defined by its fields B It is defined by its memory address C It is defined by its methods D It is defined by its class name
Show answer & explanation

It is defined by its methods

Behavior is what an object can do, which is determined by its methods. Fields represent state, not behavior.

Q82. What is the purpose of a constructor?

Intermediate
A To initialize a new object B To declare fields C To destroy an object D To define methods
Show answer & explanation

To initialize a new object

A constructor is called when an object is created to initialize its fields and set up the object's initial state.

Q83. Which of the following statements about instance fields is true?

Intermediate
A Instance fields are static B Each object has its own copy of instance fields C All objects of a class share the same instance fields D Instance fields cannot be changed
Show answer & explanation

Each object has its own copy of instance fields

Each object has its own independent copy of instance fields, so changes to one object's fields do not affect another.

Q84. What is the difference between a primitive type and a reference type?

Intermediate
Show answer & explanation

—

This is a key distinction in Java's type system.

Q85. What happens when you assign one reference variable to another?

Intermediate
Show answer & explanation

—

This tests understanding of reference semantics.

Q86. What is a constructor?

Intermediate
Show answer & explanation

—

This tests understanding of constructors.

Q87. Why are classes considered reusable?

Intermediate
Show answer & explanation

—

This tests the benefit of classes.

Q88. Why can't a static method directly access an instance variable?

Intermediate
A Because static methods don't have a `this` reference B Because instance variables are private C Because static methods run before objects exist D Because instance variables are not initialized yet
Show answer & explanation

Because static methods don't have a `this` reference

Static methods are not associated with any object, so there is no `this` to refer to an instance. Accessing an instance variable without an object reference causes a compile-time error.

Q89. What happens if a subclass declares a static method with the same signature as a static method in its parent?

Intermediate
A The parent method is hidden B A compile-time error occurs C The subclass method is ignored D The parent method is overridden
Show answer & explanation

The parent method is hidden

Static methods are hidden, not overridden. The method invoked depends on the reference type, not the object type, unlike instance method overriding.

Q90. Consider the following code: ```java class A { static void display() { System.out.println("A"); } } class B extends A { static void display() { System.out.println("B"); } } public class Test { public static void main(String[] args) { A obj = new B(); obj.display(); } } ``` What is the output?

Intermediate
A Compilation error B A C B D Runtime error
Show answer & explanation

A

Since `display()` is static, it is hidden, not overridden. The reference type is `A`, so `A.display()` is called, printing "A".

Q91. Which of the following is an appropriate use of a static method?

Intermediate
A A method that prints the name of an employee B A method that calculates the area of a circle given its radius C A method that updates the balance of a bank account D A method that returns the color of a specific car object
Show answer & explanation

A method that calculates the area of a circle given its radius

Static methods are best for operations that don't depend on object state, like a pure calculation. The other options require instance data.

Q92. What is the main advantage of using static constants?

Intermediate
A They are automatically public B They allow method overriding C They save memory and improve readability D They can be changed at runtime
Show answer & explanation

They save memory and improve readability

Static constants have only one copy in memory, and naming them improves code clarity by replacing magic numbers.

Q93. Static methods can be overridden in subclasses.

Intermediate
A True B False
Show answer & explanation

False

Static methods are hidden, not overridden. The method called depends on the reference type, not the object type.

Q94. Can a static method access an instance variable? Explain.

Intermediate
Show answer & explanation

—

Without an object, there is no instance state to access.

Q95. What does it mean that static methods are 'hidden' rather than overridden?

Intermediate
Show answer & explanation

—

This is different from instance method overriding.

Q96. Why are utility methods like `Math.sqrt()` static?

Intermediate
Show answer & explanation

—

This makes them efficient and easy to use.

Q97. What is a common use of static fields for shared state?

Intermediate
Show answer & explanation

—

Static fields are ideal for class-level data.

Q98. Explain the difference between `static` and `final`.

Intermediate
Show answer & explanation

—

They are orthogonal concepts.

Q99. How does the JVM call the `main` method if no object exists?

Intermediate
Show answer & explanation

—

Static methods are accessible without an object.

Q100. Which of the following is a valid use of `this` in a constructor?

Intermediate
A `this();` to call the superclass constructor B `return this;` to return the object C `this = new Student();` D `this.name = name;` to disambiguate fields
Show answer & explanation

`this.name = name;` to disambiguate fields

`this` is used to disambiguate field names from parameters (e.g., `this.name = name;`) and to call another constructor of the same class via `this(...)`.

Q101. What is the rule about `this(...)` in a constructor?

Intermediate
A It must be the last statement in the constructor B It must be the first statement in the constructor C It can only be used in the default constructor D It can be placed anywhere in the constructor
Show answer & explanation

It must be the first statement in the constructor

`this(...)` must be the first statement in a constructor to ensure delegation happens before any other initialization.

Q102. What is the correct initialization order when creating an object?

Intermediate
A Explicit field initializers → memory allocation → default values → constructor body B Constructor body → explicit field initializers → default values → memory allocation C Memory allocation → default values → explicit field initializers → constructor body D Default values → memory allocation → constructor body → explicit field initializers
Show answer & explanation

Memory allocation → default values → explicit field initializers → constructor body

The JVM follows a fixed order: memory allocation, then default field values, then explicit field initializers, and finally the constructor body.

Q103. What happens if you try to call `new Student()` after defining only `Student(String name)`?

Intermediate
A It compiles and uses default values B It automatically calls the parameterized constructor with null C It causes a compile error because the default constructor is gone D It throws a runtime exception
Show answer & explanation

It causes a compile error because the default constructor is gone

Defining any constructor removes the default no-argument constructor, so `new Student()` would not compile unless you explicitly add a no-arg constructor.

Q104. Why might a constructor throw an exception like `IllegalArgumentException`?

Intermediate
A To handle memory allocation failures B To signal that the constructor is overloaded C To allow the object to be garbage collected D To prevent invalid object creation and enforce invariants
Show answer & explanation

To prevent invalid object creation and enforce invariants

Constructors can throw exceptions to prevent an object from being created in an invalid state, thereby enforcing object invariants.

Q105. Consider the following code: ```java class Student { String name; int age; Student() { this("Unknown", 0); } Student(String name, int age) { this.name = name; this.age = age; } } ``` What is the purpose of the no-argument constructor?

Intermediate
A It creates a student with null name and 0 age B It delegates to the parameterized constructor to set default values C It overrides the default constructor D It is required by the compiler
Show answer & explanation

It delegates to the parameterized constructor to set default values

The no-argument constructor uses `this("Unknown", 0)` to delegate to the parameterized constructor, centralizing initialization logic and providing sensible defaults.

Q106. What is the main benefit of using `this(...)` to delegate constructors?

Intermediate
A It improves memory allocation speed B It reduces code duplication by centralizing initialization C It allows calling superclass constructors D It makes the class final
Show answer & explanation

It reduces code duplication by centralizing initialization

Delegating with `this(...)` reduces code duplication by having one constructor do the real initialization while others simply pass appropriate arguments.

Q107. What is the rule about `this(...)` in a constructor?

Intermediate
Show answer & explanation

—

This ensures delegation happens before any other initialization.

Q108. What is the initialization order when creating an object?

Intermediate
Show answer & explanation

—

This fixed order ensures fields have their explicit initial values before the constructor runs.

Q109. Why do constructors have no return type?

Intermediate
Show answer & explanation

—

The name must match the class name exactly.

Q110. How can a constructor enforce object invariants?

Intermediate
Show answer & explanation

—

This is a key design pattern for robust classes.

Q111. What is the benefit of using `this(...)` to delegate constructors?

Intermediate
Show answer & explanation

—

Other constructors simply pass appropriate arguments to the main constructor.

Q112. What happens if you try to call `new Student()` after defining only `Student(String name)`?

Intermediate
Show answer & explanation

—

Defining any constructor removes the default.

Topper level · 24 questions

Q113. Which access modifier would you use for a field that should be accessible only to subclasses, even in different packages?

Advanced
A `public` B `protected` C package-private D `private`
Show answer & explanation

`protected`

`protected` allows access to subclasses in different packages, which is exactly the requirement.

Q114. What is a potential drawback of using `protected` excessively?

Advanced
A It makes fields private B It makes code too secure C It exposes data to subclasses and same-package classes D It prevents inheritance
Show answer & explanation

It exposes data to subclasses and same-package classes

Using `protected` excessively exposes data to more classes than necessary, which can lead to unintended coupling and potential misuse.

Q115. Which of the following correctly describes the relationship between encapsulation and data hiding?

Advanced
A They are the same thing B Data hiding is a subset of encapsulation C They are unrelated D Encapsulation is a subset of data hiding
Show answer & explanation

Data hiding is a subset of encapsulation

Data hiding (making fields private) is one aspect of encapsulation; encapsulation also includes bundling data with methods and controlling access through an interface.

Q116. Consider the following class hierarchy: ```java package com.bank; public class Account { protected double balance; public Account(double initialBalance) { this.balance = initialBalance; } public double getBalance() { return balance; } } ``` ```java package com.bank; public class SavingsAccount extends Account { public SavingsAccount(double initialBalance) { super(initialBalance); } public void applyInterest(double rate) { // Assume rate is a percentage, e.g., 5 for 5% balance += balance * (rate / 100); } } ``` Now, a developer in a different package `com.app` writes: ```java package com.app; import com.bank.SavingsAccount; public class Main { public static void main(String[] args) { SavingsAccount sa = new SavingsAccount(1000); sa.applyInterest(5); System.out.println(sa.getBalance()); } } ``` What is the output and why?

Advanced
A 1000.0, because `applyInterest` does not actually modify the balance due to encapsulation. B 1050.0, because `balance` is `protected` and `SavingsAccount` is a subclass, so it can modify its own inherited field. C Compilation error, because `getBalance()` is not accessible from `com.app` package. D Compilation error, because `balance` is `protected` and cannot be accessed from a subclass in a different package.
Show answer & explanation

1050.0, because `balance` is `protected` and `SavingsAccount` is a subclass, so it can modify its own inherited field.

The `balance` field is `protected`, which allows access within the same package and by subclasses, even in different packages. `SavingsAccount` is a subclass of `Account` and is in the same package (`com.bank`), so it can directly access and modify `balance`. The `applyInterest` method correctly updates the balance to…

Q117. You are designing a `User` class with a `password` field. Which of the following implementations best demonstrates the principle of least privilege and proper encapsulation, while still allowing password validation?

Advanced
A ```java public class User { private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } ``` B ```java public class User { private String password; public void setPassword(String password) { this.password = password; } public String getPasswordHash() { return Integer.toHexString(password.hashCode()); } } ``` C ```java public class User { private String password; public boolean validatePassword(String input) { return this.password.equals(input); } public void setPassword(String password) { if (password.length() >= 8) { this.password = password; } } } ``` D ```java public class User { public String password; public boolean validatePassword(String input) { return this.password.equals(input); } } ```
Show answer & explanation

```java public class User { private String password; public boolean validatePassword(String input) { return this.password.equals(input); } public void setPassword(String password) { if (password.length() >= 8) { this.password = password; } } } ```

Option B correctly encapsulates the `password` field by making it private and providing a setter that validates the password length. It also provides a `validatePassword` method that allows checking a password without exposing the actual password. This follows the principle of least privilege by not exposing the passwo…

Q118. What is the result of the following code? ```java String s; System.out.println(s); ```

Advanced
A Prints null B Prints empty string C Compilation error: variable s might not be initialized D Runtime exception
Show answer & explanation

Compilation error: variable s might not be initialized

Local variables must be initialized before use. Unlike fields, local variables do not get default values, so this code does not compile.

Q119. Consider the following code snippet: ```java class Counter { int count = 0; void increment() { count++; } } public class Main { public static void main(String[] args) { Counter a = new Counter(); Counter b = a; b.increment(); a.increment(); System.out.println(a.count + " " + b.count); } } ``` What is the output, and why?

Advanced
A `2 2` because `a` and `b` refer to the same object, so both see the incremented count. B `0 0` because the `count` field is not accessible through reference variables. C `1 1` because each reference variable maintains its own copy of the `count` field. D `2 1` because `b.increment()` affects only `b`'s copy, while `a.increment()` affects only `a`'s copy.
Show answer & explanation

`2 2` because `a` and `b` refer to the same object, so both see the incremented count.

When `Counter b = a;` is executed, both `a` and `b` store the same reference (memory address) pointing to the same `Counter` object. Therefore, calling `increment()` through either variable modifies the same `count` field. Since `increment()` is called twice total, the shared `count` becomes 2, and both `a.count` and `…

Q120. Given the class definition: ```java class BankAccount { double balance; void deposit(double amount) { balance += amount; } void withdraw(double amount) { balance -= amount; } } ``` Which of the following code segments correctly creates two independent `BankAccount` objects and transfers $50 from the first to the second?

Advanced
A ```java BankAccount acc1 = new BankAccount(); BankAccount acc2 = new BankAccount(); acc1.deposit(100); acc1.withdraw(50); acc2.deposit(50); ``` B ```java BankAccount acc1 = new BankAccount(); BankAccount acc2 = new BankAccount(); acc1.deposit(100); acc1.withdraw(50); acc1.deposit(50); ``` C ```java BankAccount acc1 = new BankAccount(); BankAccount acc2 = acc1; acc1.deposit(100); acc1.withdraw(50); acc2.deposit(50); ``` D ```java BankAccount acc1 = new BankAccount(); BankAccount acc2 = new BankAccount(); acc1.deposit(100); acc2.withdraw(50); acc2.deposit(50); ```
Show answer & explanation

```java BankAccount acc1 = new BankAccount(); BankAccount acc2 = new BankAccount(); acc1.deposit(100); acc1.withdraw(50); acc2.deposit(50); ```

To create two independent objects, you must use `new` twice, as in option B. This ensures `acc1` and `acc2` point to different objects. Then, `acc1.deposit(100)` sets acc1's balance to 100, `acc1.withdraw(50)` reduces it to 50, and `acc2.deposit(50)` adds 50 to acc2's balance. Option A makes both variables refer to the…

Q121. Consider the following code: ```java class Person { String name; Person(String n) { name = n; } void setName(String n) { name = n; } } public class Main { public static void main(String[] args) { Person p1 = new Person("Alice"); Person p2 = new Person("Bob"); p2 = p1; p2.setName("Charlie"); System.out.println(p1.name + " " + p2.name); } } ``` What is printed?

Advanced
A `Alice Charlie` because `p1` still points to the original object, while `p2` points to a new object. B `Charlie Charlie` because `p2` now references the same object as `p1`, and the name is changed through that shared reference. C `Alice Bob` because each object retains its own name. D `null null` because the `setName` method does not work on reference variables.
Show answer & explanation

`Charlie Charlie` because `p2` now references the same object as `p1`, and the name is changed through that shared reference.

After `p2 = p1;`, both `p1` and `p2` refer to the same `Person` object (the one originally created with "Alice"). The object originally created with "Bob" becomes unreachable. Calling `p2.setName("Charlie")` modifies the shared object's `name` field. Therefore, both `p1.name` and `p2.name` print "Charlie", resulting in…

Q122. Which of the following statements correctly explains the behavior of the code below? ```java class Box { int size; Box(int s) { size = s; } } public class Main { public static void main(String[] args) { Box b1 = new Box(10); Box b2 = new Box(20); b1 = b2; b2.size = 30; System.out.println(b1.size); } } ```

Advanced
A It prints `30` because after `b1 = b2;`, both variables refer to the same object, and modifying `b2.size` changes the shared object's field. B It throws a `NullPointerException` because `b1` becomes `null` after the assignment. C It prints `20` because `b1` was assigned the reference to the object with size 20, and that object's size hasn't changed. D It prints `10` because `b1` still points to the original object with size 10.
Show answer & explanation

It prints `30` because after `b1 = b2;`, both variables refer to the same object, and modifying `b2.size` changes the shared object's field.

After `b1 = b2;`, both `b1` and `b2` reference the same `Box` object (the one created with size 20). The original object with size 10 becomes unreachable. When `b2.size = 30;` is executed, it modifies the shared object's `size` field. Since `b1` points to the same object, `b1.size` also reflects 30, so the output is `3…

Q123. A class has a static block and a static field initialized in the declaration. Which runs first?

Advanced
A The static block always runs first B The field initialization always runs first C They run in the order they appear in the source code D It depends on the JVM implementation
Show answer & explanation

They run in the order they appear in the source code

Static initializations (field declarations and static blocks) execute in the order they appear in the class body when the class is loaded.

Q124. Which of the following statements about static methods is true?

Advanced
A They can use `this` to refer to the current object B They are automatically synchronized C They can be overridden in subclasses D They can access instance variables via an object reference
Show answer & explanation

They can access instance variables via an object reference

Static methods cannot directly access instance variables, but they can if given an object reference (e.g., as a parameter). They cannot use `this`.

Q125. What is the purpose of a static block?

Advanced
A To create multiple instances of the class B To override static methods C To initialize instance variables D To perform one-time setup when the class is loaded
Show answer & explanation

To perform one-time setup when the class is loaded

Static blocks are used for complex static initialization, like loading configuration files, and run once when the class is loaded.

Q126. Which of the following is NOT a characteristic of static members?

Advanced
A They are automatically final B They are shared across all objects C They belong to the class, not instances D They can be accessed without creating an object
Show answer & explanation

They are automatically final

Static members are not automatically final; they can be mutable (e.g., a static counter). `final` is a separate keyword.

Q127. What is the order of initialization of static fields and static blocks?

Advanced
Show answer & explanation

—

This is similar to instance initialization order.

Q128. Consider the following Java code: ```java class Base { static int x = 10; static { x += 5; } static void show() { System.out.print("Base " + x + " "); } } class Derived extends Base { static int x = 20; static { x += 10; } static void show() { System.out.print("Derived " + x + " "); } } public class Test { public static void main(String[] args) { Base b = new Derived(); b.show(); System.out.print("Main " + Base.x + " " + Derived.x); } } ``` What is the output?

Advanced
A Derived 30 Main 15 30 B Derived 30 Main 15 20 C Base 15 Main 15 30 D Base 15 Main 15 20
Show answer & explanation

Base 15 Main 15 30

Static methods are hidden, not overridden, so `b.show()` calls `Base.show()` because the reference type is `Base`. `Base.x` is 15 (10+5 from static block). `Derived.x` is 30 (20+10 from static block). Thus output is `Base 15 Main 15 30`.

Q129. Which of the following statements about constructors is true?

Advanced
A Constructors can have a return type like `void` B Constructors are inherited by subclasses C Constructors can throw exceptions to prevent invalid object creation D Constructors can be called using dot notation on an existing object
Show answer & explanation

Constructors can throw exceptions to prevent invalid object creation

Constructors can throw exceptions (e.g., `IllegalArgumentException`) to prevent invalid object creation. They have no return type and are called only with `new`.

Q130. In the context of object lifecycle, what is the role of the constructor?

Advanced
A It marks the object for garbage collection B It defines the class's static methods C It is the final step in the creation phase, making the object ready for use D It allocates memory for the object on the stack
Show answer & explanation

It is the final step in the creation phase, making the object ready for use

The constructor is the final step in the creation phase. After it completes, the object is fully initialized and ready for use.

Q131. What is the role of constructors in dependency injection?

Advanced
Show answer & explanation

—

This is a common pattern in frameworks like Spring.

Q132. Can a constructor throw an exception? Give an example.

Advanced
Show answer & explanation

—

This prevents invalid object creation.

Q133. What is the difference between a constructor and a method?

Advanced
Show answer & explanation

—

These are key distinguishing features.

Q134. Consider the following Java class: ```java class Account { private double balance; private String owner; Account() { this("Unknown", 0.0); } Account(String owner) { this(owner, 0.0); } Account(String owner, double balance) { if (balance < 0) { throw new IllegalArgumentException("Balance cannot be negative"); } this.owner = owner; this.balance = balance; } } ``` What is the result of executing `new Account("Alice", -5.0)`?

Advanced
A It causes a compile-time error because the constructor call is invalid. B It creates an `Account` object with owner "Alice" and balance 0.0. C It creates an `Account` object with owner "Alice" and balance -5.0. D It throws `IllegalArgumentException` because the balance is negative.
Show answer & explanation

It throws `IllegalArgumentException` because the balance is negative.

The three-argument constructor explicitly checks `if (balance < 0)` and throws `IllegalArgumentException` before assigning any fields. Since -5.0 is negative, the exception is thrown, preventing the creation of an invalid object. The other options are incorrect because the constructor does not silently adjust the balan…

Q135. Given the following class definitions: ```java class Parent { Parent() { System.out.print("Parent "); } } class Child extends Parent { private int value = 10; Child() { System.out.print("Child "); } } ``` What is the output when executing `new Child()`?

Advanced
A `Child Parent` B `Child` C `Parent Child` D `Parent`
Show answer & explanation

`Parent Child`

In Java, when a subclass object is created, the superclass constructor is implicitly called before the subclass constructor body executes. Here, `Parent`'s no-argument constructor prints "Parent ", then `Child`'s constructor prints "Child ". The explicit field initializer `int value = 10;` runs before the `Child` const…

Q136. Consider the following class: ```java class Config { private static final int MAX = 100; private int limit; Config(int limit) { this.limit = limit; } Config() { this(MAX); } } ``` What happens if you attempt to compile and run `new Config()`?

Advanced
A It compiles but throws a runtime exception because `MAX` is not initialized. B It compiles and creates a `Config` object with `limit` set to 100. C It fails to compile because `this(MAX)` must be the first statement, but it is not. D It fails to compile because `MAX` is not accessible in the constructor.
Show answer & explanation

It compiles and creates a `Config` object with `limit` set to 100.

The no-argument constructor calls `this(MAX)`, which is a valid delegation to the parameterized constructor. `MAX` is a `static final` constant, accessible from any instance method or constructor. The call `this(MAX)` is the first statement, satisfying the rule. Therefore, the code compiles and creates a `Config` objec…

Make your own

Your notes can be a kit like these

Every kit here was made from real study material. Point Veda at a chapter, a PDF, a photo or a link and get notes, flashcards, practice MCQs, games and a scored test — free, in 42 languages.

  • Chapter notes
  • Flashcards
  • Practice MCQs
  • Scored tests
  • Exam prep

Get Veda free See what students get

Free to start · No ads · Works in 42 languages