Java Interview Preparation Q1 to Q5
Q1) Explain the concept of OOP and its principles.
Object-Oriented Programming System (OOPS) is a programming paradigm based on the concept of "objects", which can contain data and code to manipulate that data. The four main principles of OOP are:
Encapsulation: Binding data (variables) and methods (functions) that operate on the data into a single unit or class.
Inheritance: Mechanism by which one class can inherit properties and methods from another class, promoting code reuse.
Polymorphism: Ability of different classes to be treated as instances of the same class through a common interface, often achieved through method overriding and overloading.
Abstraction: Hiding complex implementation details and showing only the necessary features of an object.
Q2) What are the differences between abstract classes and interfaces?
Abstract Class:
Can have both abstract methods (without implementation) and concrete methods (with implementation).
Can have member variables.
Can have constructors.
Supports inheritance (a class can extend only one abstract class).
Interface:
Can have only abstract methods (until Java 8, which introduced default and static methods with implementation).
Cannot have member variables, only constants (static final)
Q3) How does garbage collection work in Java?
Garbage collection in Java is the process of automatically freeing up memory by destroying objects that are no longer in use. The Java Virtual Machine (JVM) performs this process, primarily using the Mark-and-Sweep algorithm:
Mark: The garbage collector identifies which objects are reachable (in use) and marks them.
Sweep: The garbage collector then reclaims the memory used by unmarked objects (unreachable).
The garbage collector may use different algorithms (like generational garbage collection) and run in various modes (serial, parallel, concurrent).
Q4) What are the differences between checked and unchecked exceptions?
Checked Exceptions:
Checked at compile-time.
Must be either caught or declared in the method signature using throws.
Examples: IOException, SQLException.
Unchecked Exceptions:
Checked at runtime.
Do not need to be declared or caught.
Examples: NullPointerException, ArrayIndexOutOfBoundsException.
Q5) Can you explain the concept of multithreading and synchronization?
Answer:
Multithreading: A process of executing two or more threads simultaneously to perform multiple tasks concurrently. It allows maximum utilization of CPU.
Synchronization: A mechanism to control the access of multiple threads to shared resources. It ensures that only one thread can access a resource at a time, preventing data inconsistency and thread interference.
java
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}.
Cannot have constructors.
Supports multiple inheritance (a class can implement multiple interfaces).
Comments
Post a Comment