Essential Java OOPs Interview Questions
Polymorphism in Java
Polymorphism allows objects of different classes to be treated as objects of a common type. This is achieved through method overriding (a subclass provides a specific implementation for a method defined in its superclass) and interface implementation (classes implement methods defined in an interface). Polymorphism enhances code flexibility and reusability.
Interfaces in Java
An interface is a reference type defining a contract; a set of methods that implementing classes must provide. Interfaces cannot be instantiated; they're used to achieve abstraction and multiple inheritance (a class can implement many interfaces).
Java 8 Interface Enhancements: Default and Static Methods
Java 8 introduced default and static methods in interfaces. Default methods provide implementations within the interface, allowing interfaces to evolve without breaking existing code. Static methods are utility methods associated with the interface itself.
Threads and Multitasking in Java
A thread is a unit of execution within a program. Multithreading allows multiple threads to run concurrently within a single program, improving performance and responsiveness. Each thread has its own stack but shares the same memory space.
Deadlocks in Multithreading
A deadlock occurs when two or more threads are blocked indefinitely, each waiting for a resource held by another. Four conditions must be met for a deadlock to occur: mutual exclusion, hold and wait, no preemption, and circular wait.
Strategies to prevent or resolve deadlocks include:
- Careful resource ordering.
- Using timeouts.
- Employing techniques to avoid circular wait conditions.
ArrayList vs. Vector in Java
ArrayList | Vector |
---|---|
Not synchronized; more efficient for single-threaded applications. Resizes by 50%. | Synchronized; thread-safe; less efficient due to synchronization overhead. Resizes by 100%. |
Lists vs. Sets in Java
List | Set |
---|---|
Ordered collection; allows duplicate elements; accessed by index. | Unordered collection; does not allow duplicates; accessed by element value. |
Examples: ArrayList , LinkedList |
Examples: HashSet , TreeSet |
Encapsulation in Object-Oriented Programming
Encapsulation bundles data (fields) and methods (that operate on that data) within a class. It restricts direct access to internal data, managing access through well-defined methods. Encapsulation enhances security, maintainability, and code organization.
Lambda Expressions in Java 8
Lambda expressions provide a concise way to represent anonymous functions (functions without a name). They simplify code, especially when working with functional interfaces (interfaces with a single abstract method).
The hashCode()
Method in Java
The hashCode()
method returns an integer value representing an object's hash code, used for efficient lookup in hash-based collections. Objects that are equal (as determined by the equals()
method) must have the same hash code.
==
vs. equals()
for Object Comparison
== |
equals() |
---|---|
Compares object references (memory addresses). | Compares object contents (you define the comparison logic). |
The super
Keyword in Java
The super
keyword refers to the superclass (parent class) of the current class. It's used to access or call methods and constructors of the superclass from within a subclass.
Try-with-Resources Statement (Java 7)
The try-with-resources
statement simplifies resource management by automatically closing resources (like files or database connections) at the end of the try
block, even if exceptions are thrown.
The transient
Keyword in Java
The transient
keyword prevents a variable from being serialized. This is useful for data that should not be persisted when saving object state (e.g., sensitive information).
Comparable vs. Comparator Interfaces in Java
Comparable | Comparator |
---|---|
Defines the natural ordering of objects of a class. Implemented within the class itself. | Defines a custom comparison for objects. Implemented separately from the class. |
Static Methods in Java
A static
method belongs to the class itself, not to any instance of the class. It's called using the class name (e.g., MyClass.myStaticMethod()
). static
methods cannot directly access instance variables or call instance methods.
The volatile
Keyword
The volatile
keyword in Java ensures that changes to a variable are immediately visible to all threads, preventing caching issues. It does not, however, guarantee atomicity for complex operations.
The finalize()
Method
The finalize()
method is called by the garbage collector before an object is garbage collected. It's used for cleanup, but relying on it is generally discouraged; explicit resource management (using try-with-resources
or other techniques) is preferred.
The this
Keyword
The this
keyword in Java refers to the current instance of a class. It's used to:
- Access instance variables (especially when there's a name conflict with parameters).
- Call another constructor in the same class (constructor chaining).
Assigning to `this`
You cannot assign a value to the this
keyword; it's implicitly assigned and is a final reference.
Using `this` to Access Static Members
While you can technically use this
to access static members, it's generally not recommended because static members are accessed using the class name.
Constructor Chaining with `this`
Constructor chaining with this()
allows calling another constructor within the same class, streamlining initialization.
Inheritance
Inheritance enables classes to inherit properties and methods from parent classes, promoting code reuse and establishing relationships (IS-A).
Types of Inheritance in Java
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
- Multiple Inheritance (through interfaces)
Why Use Inheritance in Java?
- Code reusability
- Runtime polymorphism
- Data hiding
- Method overriding
Superclass of All Classes
java.lang.Object
is the root class in Java; all classes directly or indirectly inherit from it.
Why No Multiple Inheritance of Classes in Java?
To avoid ambiguity (multiple parent classes with the same method), Java only allows single inheritance of classes but supports multiple inheritance through interfaces.
Aggregation
Aggregation describes a "has-a" relationship between classes. One class contains a reference to another, but the contained object can exist independently.
Composition
Composition is a stronger form of aggregation; the contained object cannot exist without the container object.
Aggregation vs. Composition
Aggregation | Composition |
---|---|
Weaker "has-a" relationship. | Stronger "part-of" relationship. |
Why Java Avoids Pointers
Pointers are avoided in Java to enhance security and simplify memory management. They can be error-prone if not handled carefully.
The super
Keyword
The super
keyword refers to the immediate parent class. It's used to access members of the superclass, especially when they're overridden in the subclass.
Constructor Chaining with super()
Constructor chaining with super()
allows calling the superclass constructor from within the subclass constructor. This is essential for initializing inherited fields.
Uses of the super
Keyword
- To invoke a superclass constructor.
- To access hidden superclass methods and fields.
this
vs. super
this |
super |
---|---|
Refers to the current object instance. | Refers to the parent class object. |
Example: Implicit super()
Call
Java Code
class Person {
public Person() {
System.out.println("Person class constructor called");
}
}
public class Employee extends Person {
public Employee() {
System.out.println("Employee class constructor called");
}
public static void main(String args[]) {
Employee e = new Employee();
}
}
Output
Person class constructor called
Employee class constructor called
Using `this()` and `super()` Together
You cannot use both this()
and super()
in the same constructor because they must be the first statement.