1. What are the four main principles of Object-Oriented Programming (OOP)?
Java is an object-oriented language built around four core pillars:
- Encapsulation: Bundling data (variables) and methods that operate on the data into a single unit (a class), and restricting direct access to some of the object's components (usually via
privatefields andpublicgetters/setters). - Inheritance: A mechanism where a new class (subclass/child) derives properties and behaviors from an existing class (superclass/parent) using the
extendskeyword. This promotes code reusability. - Polymorphism: The ability of an object to take on many forms. In Java, this is achieved through Method Overloading (compile-time polymorphism) and Method Overriding (runtime polymorphism). Understanding Java Polymorphism: Overloading vs. Overriding Explained Simply
- Abstraction: Hiding complex implementation details and showing only the essential features of an object. This is achieved in Java using
abstractclasses andinterfaces.
2. What is the difference between an abstract class and an interface?
Both are used to achieve abstraction, but they serve slightly different design purposes:
- Abstract Class:
- Can have both abstract methods (without a body) and concrete methods (with a body).
- Can have instance variables (fields) with any access modifier (
private,protected,public). - Can have constructors.
- A class can only
extendone abstract class (single inheritance).
- Interface:
- Historically could only have abstract methods, though since Java 8, interfaces can have
defaultandstaticmethods (andprivatemethods since Java 9). - Variables are implicitly
public static final(constants). - Cannot have constructors.
- A class can
implementmultiple interfaces (achieving multiple inheritance of type).
- Historically could only have abstract methods, though since Java 8, interfaces can have
![]()
3. What is the final keyword used for in Java?
The final keyword is a non-access modifier used to restrict the user. It can be applied in three contexts:
- Final Variable: Creates a constant. Once assigned a value, it cannot be changed. (If it's a reference variable, the reference cannot point to a new object, though the object's internal state can still change).
- Final Method: Prevents the method from being overridden by subclasses.
- Final Class: Prevents the class from being inherited/extended by any other class (e.g.,
java.lang.Stringis afinalclass).
4. What is the difference between Stack and Heap memory in Java?
Java divides memory into two primary regions for executing applications:
- Stack Memory:
- Used for static memory allocation and thread execution.
- Stores primitive local variables and references to objects.
- Follows LIFO (Last-In, First-Out) order.
- Each thread has its own private stack. Memory is automatically freed when a method finishes executing.
- Heap Memory:
- Used for dynamic memory allocation.
- All actual objects (created with the
newkeyword) and instance variables live here. - Shared across all threads in the application.
- Managed by Java's Garbage Collector (GC), which automatically frees up memory from objects that are no longer referenced.
5. What does the static keyword mean in Java?
The static keyword indicates that a particular member (variable, method, block, or nested class) belongs to the class itself, rather than to any specific instance (object) of that class.
- Static Variable: Shared among all instances of the class. Only one copy exists in memory.
- Static Method: Can be called without creating an instance of the class (e.g.,
Math.max(5, 10)). Note that static methods cannot directly access non-static (instance) variables or methods. - Static Block: Executed once when the class is first loaded into memory, often used for static initialization.
public class Counter {
static int count = 0; // Shared by all objects
public Counter() {
count++;
}
}
6. What is the difference between Method Overloading and Method Overriding?
Both are forms of polymorphism, but they occur at different times and have different rules:
| Feature | Method Overloading | Method Overriding |
|---|---|---|
| Definition | Multiple methods in the same class with the same name but different parameters. | A subclass provides a specific implementation for a method already defined in its parent class. |
| Polymorphism Type | Compile-time (Static) | Runtime (Dynamic) |
| Parameters | Must be different (type, number, or order). | Must be identical. |
| Return Type | Can be different (as long as parameters differ). | Must be the same (or a covariant subtype). |
7. What is the difference between HashMap and Hashtable?
Both store key-value pairs and implement the Map interface, but Hashtable is a legacy class while HashMap is the modern standard.
- Thread Safety:
Hashtableis synchronized (thread-safe), making it slower in single-threaded environments.HashMapis not synchronized. - Null Keys and Values:
HashMapallows onenullkey and multiplenullvalues.Hashtabledoes not allow anynullkeys ornullvalues (throws aNullPointerException). - Performance:
HashMapis generally much faster because it lacks synchronization overhead. (Note: If you need a thread-safe map today, useConcurrentHashMapinstead ofHashtable).
8. What is the difference between String, StringBuilder, and StringBuffer?
Because String is immutable, concatenating strings in a loop creates many temporary objects in memory. StringBuilder and StringBuffer solve this by providing mutable sequences of characters:
String: Immutable and thread-safe. Best when the text value will not change frequently.StringBuilder: Mutable and not thread-safe (unsynchronized). It is the fastest option and should be your default choice for string manipulation inside a single thread.StringBuffer: Mutable and thread-safe (methods are synchronized). Slightly slower thanStringBuilder, used when multiple threads modify the same string buffer.
9. What is a Constructor, and what is Constructor Chaining?
A constructor is a special block of code used to initialize a newly created object. It has the exact same name as the class and has no return type (not even void). If you don't write one, Java provides a default no-argument constructor.
Constructor Chaining is the process of calling one constructor from another constructor with respect to the current object:
- Use
this()to call another constructor within the same class. - Use
super()to call a constructor from the parent class.
(Note: this() or super() must always be the very first statement inside a constructor).
10. What is the difference between throw and throws?
These two keywords are used in Java exception handling, but they serve different purposes:
throw: Used inside a method body to explicitly throw a single exception object.throws: Used in a method signature to declare that the method might throw one or more checked exceptions, passing the responsibility of handling them to the caller.
public void checkAge(int age) throws IllegalArgumentException {
if (age < 18) {
throw new IllegalArgumentException("Must be 18 or older.");
}
}
11. What are Wrapper Classes, and what is Autoboxing / Unboxing?
Java is not 100% object-oriented because it has eight primitive data types (int, double, boolean, etc.). Wrapper classes (Integer, Double, Boolean, etc.) wrap these primitives into objects so they can be used in Java Collections (like ArrayList<Integer>), which only store objects.
- Autoboxing: The automatic conversion that the Java compiler makes between a primitive type and its corresponding wrapper class (e.g.,
int$\rightarrow$Integer). - Unboxing: The reverse process—converting a wrapper object back into its primitive type (e.g.,
Integer$\rightarrow$int).
Integer numObj = 10; // Autoboxing (int to Integer)
int numPrim = numObj; // Unboxing (Integer to int)
12. What is a Functional Interface and a Lambda Expression in Java 8?
Introduced in Java 8, these features brought functional programming capabilities to Java:
- Functional Interface: An interface that contains exact one abstract method (it can still have multiple
defaultorstaticmethods). It is typically annotated with@FunctionalInterface. Examples includeRunnable,Comparable, andPredicate. - Lambda Expression: A concise way to represent an anonymous function (an implementation of a functional interface) without writing boilerplate anonymous inner classes.
// Traditional way
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Hello!");
}
};
r1.run();
// Using a Lambda Expression
Runnable r2 = () -> System.out.println("Hello!");
r2.run();
13. What is the Java Stream API?
The Stream API (introduced in Java 8) is used to process collections of objects in a functional, declarative way. A Stream is not a data structure; it does not store data or modify the underlying collection. Instead, it carries values from a source through a pipeline of operations:
- Intermediate Operations: Transform a stream into another stream (e.g.,
filter(),map(),sorted()). These are lazy—they don't execute until a terminal operation is called. - Terminal Operations: Produce a final result or side effect (e.g.,
collect(),forEach(),count()).
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Anna");
List<String> aNames = names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.collect(Collectors.toList()); // Result: ["ALICE", "ANNA"]