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?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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.
BeginnerShow 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?
BeginnerShow answer & explanation
—
This is the core definition.
Q8. List the four access levels in Java from most restrictive to least restrictive.
BeginnerShow answer & explanation
—
This order is essential for understanding visibility.
Q9. What is the visibility of a `private` member?
BeginnerShow 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?
BeginnerShow answer & explanation
—
This is also called default access.
Q11. What is the visibility of a `protected` member?
BeginnerShow answer & explanation
—
Protected extends package-private with subclass access.
Q12. What is the visibility of a `public` member?
BeginnerShow answer & explanation
—
No restrictions.
Q13. What is a getter method?
BeginnerShow answer & explanation
—
Getters provide read access without exposing the field directly.
Q14. What is a setter method?
BeginnerShow answer & explanation
—
Setters allow controlled modification with validation.
Q15. Name two benefits of encapsulation.
BeginnerShow answer & explanation
—
These are the key benefits listed in the source.
Q16. What is a common pattern that uses encapsulation in Java?
BeginnerShow answer & explanation
—
JavaBeans are a classic example.
Q17. What is a class in Java?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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.
BeginnerShow 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.
BeginnerShow 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?
BeginnerShow answer & explanation
—
This tests the fundamental definition of a class.
Q27. What does the `new` keyword do?
BeginnerShow answer & explanation
—
This tests understanding of object creation.
Q28. How do you access fields and methods of an object?
BeginnerShow 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?
BeginnerShow answer & explanation
—
Reference variables are initialized to `null` by default.
Q30. What exception is thrown when you call a method on a `null` reference?
BeginnerShow answer & explanation
—
This tests knowledge of a common runtime error.
Q31. What is object state?
BeginnerShow answer & explanation
—
State is the data part of an object.
Q32. What is object behavior?
BeginnerShow answer & explanation
—
Behavior is the functionality part of an object.
Q33. If no constructor is defined in a class, what happens?
BeginnerShow answer & explanation
—
This tests knowledge of default constructors.
Q34. Do two objects of the same class share their instance fields?
BeginnerShow answer & explanation
—
This tests the concept of instance independence.
Q35. What is the result of `Car myCar;` without `new`?
BeginnerShow answer & explanation
—
This tests the difference between declaration and instantiation.
Q36. What is the purpose of the dot operator?
BeginnerShow answer & explanation
—
This tests basic syntax.
Q37. Which of the following best describes a static field?
BeginnerShow 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`?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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.
BeginnerShow 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?
BeginnerShow answer & explanation
—
This is the fundamental distinction between class-level and object-level data.
Q43. Why is the `main` method declared static?
BeginnerShow 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?
BeginnerShow answer & explanation
—
It is used for complex static initialization.
Q45. Give an example of a static constant and explain why it is useful.
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow answer & explanation
—
The compiler knows there is no instance context.
Q48. What is the purpose of a static initializer block?
BeginnerShow answer & explanation
—
It runs once at class loading time.
Q49. Can a static method access another static method directly?
BeginnerShow answer & explanation
—
Static members can access each other directly.
Q50. What is the primary purpose of a constructor in Java?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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?
BeginnerShow 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.
BeginnerShow 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.
BeginnerShow 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?
BeginnerShow answer & explanation
—
This is the fundamental definition of a constructor.
Q59. What does the default constructor do?
BeginnerShow answer & explanation
—
The compiler provides it only if no other constructor is defined.
Q60. When does the default constructor disappear?
BeginnerShow answer & explanation
—
This is a common source of confusion.
Q61. What is a parameterized constructor?
BeginnerShow answer & explanation
—
It allows setting the initial state directly.
Q62. What is constructor overloading?
BeginnerShow answer & explanation
—
Each constructor must have a unique signature.
Q63. What does the `this` keyword refer to in a constructor?
BeginnerShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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.
IntermediateShow 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?
IntermediateShow answer & explanation
—
This is the standard pattern.
Q73. What is the principle of least privilege in access control?
IntermediateShow answer & explanation
—
This minimizes exposure and reduces risk.
Q74. What is the relationship between encapsulation and data hiding?
IntermediateShow answer & explanation
—
Encapsulation includes data hiding but is not limited to it.
Q75. What happens if you make a field public?
IntermediateShow answer & explanation
—
Public fields allow direct modification without validation.
Q76. Why does encapsulation improve maintainability?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow answer & explanation
—
This is a key distinction in Java's type system.
Q85. What happens when you assign one reference variable to another?
IntermediateShow answer & explanation
—
This tests understanding of reference semantics.
Q86. What is a constructor?
IntermediateShow answer & explanation
—
This tests understanding of constructors.
Q87. Why are classes considered reusable?
IntermediateShow answer & explanation
—
This tests the benefit of classes.
Q88. Why can't a static method directly access an instance variable?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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.
IntermediateShow 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.
IntermediateShow 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?
IntermediateShow answer & explanation
—
This is different from instance method overriding.
Q96. Why are utility methods like `Math.sqrt()` static?
IntermediateShow answer & explanation
—
This makes them efficient and easy to use.
Q97. What is a common use of static fields for shared state?
IntermediateShow answer & explanation
—
Static fields are ideal for class-level data.
Q98. Explain the difference between `static` and `final`.
IntermediateShow answer & explanation
—
They are orthogonal concepts.
Q99. How does the JVM call the `main` method if no object exists?
IntermediateShow answer & explanation
—
Static methods are accessible without an object.
Q100. Which of the following is a valid use of `this` in a constructor?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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)`?
IntermediateShow 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`?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow 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?
IntermediateShow answer & explanation
—
This ensures delegation happens before any other initialization.
Q108. What is the initialization order when creating an object?
IntermediateShow answer & explanation
—
This fixed order ensures fields have their explicit initial values before the constructor runs.
Q109. Why do constructors have no return type?
IntermediateShow answer & explanation
—
The name must match the class name exactly.
Q110. How can a constructor enforce object invariants?
IntermediateShow answer & explanation
—
This is a key design pattern for robust classes.
Q111. What is the benefit of using `this(...)` to delegate constructors?
IntermediateShow 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)`?
IntermediateShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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); ```
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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); } } ```
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow 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?
AdvancedShow answer & explanation
—
This is a common pattern in frameworks like Spring.
Q132. Can a constructor throw an exception? Give an example.
AdvancedShow answer & explanation
—
This prevents invalid object creation.
Q133. What is the difference between a constructor and a method?
AdvancedShow 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)`?
AdvancedShow 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()`?
AdvancedShow 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()`?
AdvancedShow 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…
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