Java & OOP Interview Guide 1
Java & OOP
Interview Preparation Guide
Comprehensive Answers for Technical Interviews
April 6, 2026
Contents
Java & OOP Interview Guide 2
OOP Concepts
Object-Oriented Programming is built on four fundamental pillars:
Encapsulation
Bundling data (fields) and the methods that operate on that data into a single unit (class), while
restricting direct access via access modifiers.
public class BankAccount {
private double balance ; // hidden from outside
public void deposit ( double amount ) {
if ( amount > 0) this . balance += amount ;
}
public double getBalance () {
return balance ;
}
}
Why it matters: Protects internal state, enforces invariants, and allows internal changes without
breaking external code.
Inheritance
A child class acquires the fields and methods of a parent class, promoting code reuse.
public class Animal {
public void eat () { System . out . println ( " Eating ... " ) ; }
}
public class Dog extends Animal {
public void bark () { System . out . println ( " Woof ! " ) ; }
}
Java supports single class inheritance only (one extends), but a class can implement multiple
interfaces.
Polymorphism
The ability of an object to take many forms.
Compile-time (Overloading): Same method name, different parameter lists.
Runtime (Overriding): Subclass provides its own implementation of a parent’s method; actual
method called is resolved at runtime via dynamic dispatch.
Animal a = new Dog () ; // reference type : Animal , object type : Dog
a . eat () ; // calls Dog ’s eat () if overridden
Abstraction
Hiding complex implementation details and exposing only the necessary interface to the user.
Achieved via abstract classes and interfaces.
Java & OOP Interview Guide 3
The static Keyword
The static keyword indicates that a member belongs to the class itself rather than to any
particular instance.
Aspect Static Member Instance Member
Belongs to Class Object instance
Memory One copy (Method Area) Per object (Heap)
Access [Link] [Link]
Can access Only other static members directly Both static & instance
public class Counter {
static int count = 0; // shared across all instances
int id ; // unique per instance
Counter () { id = ++ count ; }
static int getCount () { return count ; } // static method
}
Static blocks run once when the class is loaded, useful for one-time initialization.
Singleton vs. Static
Feature Singleton Static Class
Nature An object (single instance of a class) A class with only static members; no
instance
Inheritance Can implement interfaces, extend classes Cannot participate in polymorphism
Lazy init Yes (created on first use) No (loaded with class)
Serialization Possible Not applicable
State Holds instance state Holds only static state
Testing Easier to mock via interfaces Hard to mock
// Singleton ( thread - safe with enum )
public enum D at ab as eC on ne ct io n {
INSTANCE ;
public void connect () { /* ... */ }
}
// Static utility class
public final class MathUtils {
private MathUtils () {} // prevent instantiation
public static int add ( int a , int b ) { return a + b ; }
}
Interview Tip
Use Singleton when you need a single object that participates in OOP (interfaces, polymorphism,
dependency injection). Use a static utility class for stateless helper methods (e.g., Math,
Collections).
Java & OOP Interview Guide 4
Abstract Class vs. Interface
Feature Abstract Class Interface
Instantiation No No
Methods Abstract + concrete Abstract, default, static (Java 8+)
Fields Any (including non-final) Only public static final
Constructors Yes No
Multiple inherit. Single (extends) Multiple (implements)
Access modifiers All allowed Methods are public by default
When to use Shared state / base implementation Defining a contract / capability
// Abstract class : partial implementation + shared state
public abstract class Shape {
String color ;
abstract double area () ;
void display () { System . out . println ( " Color : " + color ) ; }
}
// Interface : pure contract
public interface Drawable {
void draw () ;
default void resize () { System . out . println ( " Resizing ... " ) ; }
}
Rule of Thumb
“Is-a” relationship → abstract class. “Can-do” capability → interface.
final, finally, finalize
Keyword Type Purpose
final Modifier Restricts modification: final variable (con-
stant), final method (cannot override), fi-
nal class (cannot extend).
finally Block Code block in try-catch that always exe-
cutes (cleanup: closing streams, releasing
locks).
finalize Method Called by GC before object destruc-
tion (deprecated since Java 9; use
try-with-resources or Cleaner in-
stead).
final int MAX = 100; // constant
try {
riskyOperation () ;
} catch ( Exception e ) {
handleError ( e ) ;
} finally {
cleanup () ; // always runs
}
Java & OOP Interview Guide 5
Primitive Data Types
Java has 8 primitive types. They are not objects and are stored on the stack (or inlined).
Type Size Default Range Wrapper
byte 1 byte 0 −128 to 127 Byte
short 2 bytes 0 −32,768 to 32,767 Short
int 4 bytes 0 ±2.1 × 109 Integer
long 8 bytes 0L ±9.2 × 1018 Long
float 4 bytes 0.0f ±3.4 × 1038 Float
double 8 bytes 0.0d ±1.7 × 10308 Double
char 2 bytes ’\u0000’ 0 to 65,535 Character
boolean 1 bit* false true/false Boolean
Autoboxing/Unboxing: Java automatically converts between primitives and their wrapper classes.
Integer wrapped = 42; // autoboxing : int -> Integer
int unwrapped = wrapped ; // unboxing : Integer -> int
Java Collections Framework
The Collections Framework provides data structures and algorithms under [Link].
Core Interfaces Hierarchy
Iterable → Collection → List, Set, Queue
Separate: Map (key-value pairs, does not extend Collection).
List Implementations
ArrayList LinkedList Vector
Backing Dynamic array Doubly-linked list Dynamic array
Access O(1) random O(n) random O(1) random
Insert/Del O(n) (shifting) O(1) at ends O(n)
Thread-safe No No Yes (synchronized)
Best for Read-heavy Insert/delete-heavy Legacy; prefer
[Link]
Array vs. ArrayList
Feature Array ArrayList
Size Fixed at creation Dynamic (grows automatically)
Type Primitives + Objects Objects only (uses wrappers for primi-
tives)
Performance Faster (no overhead) Slight overhead (boxing, resizing)
Methods Only length Rich API: add, remove, contains. . .
Generics No Yes
Java & OOP Interview Guide 6
HashMap vs. Hashtable
Feature HashMap Hashtable
Thread-safe No (use ConcurrentHashMap) Yes (all methods synchronized)
Null keys/values One null key, many null values No nulls allowed
Performance Faster (no synchronization overhead) Slower
Introduced Java 1.2 Java 1.0 (legacy)
Iteration Fail-fast iterator Enumerator (not fail-fast)
Interview Tip
Always prefer HashMap in single-threaded contexts and ConcurrentHashMap in multi-threaded
contexts. Hashtable is legacy.
Set & Queue Quick Reference
Set: HashSet (unordered, O(1)), LinkedHashSet (insertion order), TreeSet (sorted, O(log n)).
Queue/Deque: PriorityQueue (heap-based), ArrayDeque (double-ended), LinkedList (also
implements Deque).
Mutable vs. Immutable Objects
Definitions
Mutable: State can be changed after creation (e.g., StringBuilder, ArrayList, Date).
Immutable: State cannot change after creation (e.g., String, Integer, wrapper classes).
Why is String Immutable?
String Pool: Multiple references can share the same literal safely.
Thread Safety: No synchronization needed.
Security: Class names, URLs, file paths cannot be altered.
Hashcode Caching: Hash is computed once; safe as HashMap key.
String s = " Hello " ;
s . concat ( " World " ) ; // returns new String ; s is still " Hello "
s = s . concat ( " World " ) ; // s now points to a NEW " Hello World "
StringBuilder sb = new StringBuilder ( " Hello " ) ;
sb . append ( " World " ) ; // modifies the SAME object
Creating an Immutable Class
public final class Money { // 1. final class
private final String currency ; // 2. final fields
private final double amount ;
public Money ( String currency , double amount ) { // 3. constructor init
this . currency = currency ;
this . amount = amount ;
Java & OOP Interview Guide 7
public String getCurrency () { return currency ; } // 4. only getters
public double getAmount () { return amount ; } // no setters
}
Tip
For mutable fields (e.g., Date, List), return defensive copies from getters to preserve im-
mutability.
Exception Handling
Exception Hierarchy
[Link]
Error (unrecoverable: OutOfMemoryError, StackOverflowError)
Exception
IOException (checked)
SQLException (checked)
RuntimeException (unchecked)
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
ClassCastException
IllegalArgumentException
Checked vs. Unchecked Exceptions
Checked Unchecked
Verified at Compile time Runtime
Must handle? Yes (try-catch or throws) No (optional)
Extends Exception RuntimeException
Examples IOException, SQLException NullPointerException,
ArithmeticException
Exception Handling Syntax
try {
FileReader fr = new FileReader ( " file . txt " ) ;
} catch ( F i l e N o t F o u n d E x c e p t i o n e ) {
System . out . println ( " File not found : " + e . getMessage () ) ;
} catch ( IOException e ) {
System . out . println ( " IO error : " + e . getMessage () ) ;
} finally {
System . out . println ( " Always executes " ) ;
}
Try-with-Resources (Java 7+)
try ( BufferedReader br = new BufferedReader ( new FileReader ( " f . txt " ) ) ) {
String line = br . readLine () ;
Java & OOP Interview Guide 8
} // br . close () called automatically - implements AutoCloseable
Custom Exceptions
public class I n s u f f i c i e n t F u n d s E x c e p t i o n extends Exception {
private double deficit ;
public I n s u f f i c i e n t F u n d s E x c e p t i o n ( double deficit ) {
super ( " Insufficient funds . Deficit : " + deficit ) ;
this . deficit = deficit ;
}
public double getDeficit () { return deficit ; }
}
Best Practices
(1) Catch specific exceptions, not generic Exception. (2) Never swallow exceptions silently.
(3) Prefer try-with-resources for AutoCloseable resources. (4) Use custom exceptions for
domain-specific errors. (5) Avoid using exceptions for flow control.
Can We Create an Instance of an Interface?
Short Answer: No, you cannot directly instantiate an interface with new MyInterface().
However, you can use:
1. A concrete class implementing the interface:
interface Greeting { void greet () ; }
class HelloGreeting implements Greeting {
public void greet () { System . out . println ( " Hello ! " ) ; }
}
Greeting g = new HelloGreeting () ; // reference type is interface
2. An anonymous inner class:
Greeting g = new Greeting () {
@Override
public void greet () { System . out . println ( " Hi ! " ) ; }
};
3. A lambda expression (functional interfaces only):
Greeting g = () -> System . out . println ( " Hey ! " ) ;
g . greet () ;
Tip
In cases 2 and 3, the JVM creates an anonymous class behind the scenes. You are not instantiating
the interface directly; you are providing an implementation inline.
Java & OOP Interview Guide 9
Converting Array to ArrayList
String [] arr = { " Java " , " Python " , " C ++ " };
// Method 1: Arrays . asList () - returns FIXED - SIZE list
List < String > list1 = Arrays . asList ( arr ) ;
// list1 . add (" Go ") ; // throws U n s u p p o r t e d O p e r a t i o n E x c e p t i o n !
// Method 2: new ArrayList < >( Arrays . asList () ) - MODIFIABLE
List < String > list2 = new ArrayList < >( Arrays . asList ( arr ) ) ;
list2 . add ( " Go " ) ; // works fine
// Method 3: Collections . addAll ()
List < String > list3 = new ArrayList < >() ;
Collections . addAll ( list3 , arr ) ;
// Method 4: Java 8+ Stream
List < String > list4 = Arrays . stream ( arr )
. collect ( Collectors . toList () ) ;
// Method 5: List . of () ( Java 9+) - IMMUTABLE
List < String > list5 = List . of ( arr ) ;
// For primitive arrays ( e . g . , int []) :
int [] nums = {1 , 2 , 3};
List < Integer > intList = Arrays . stream ( nums )
. boxed ()
. collect ( Collectors . toList () ) ;
Common Pitfall
[Link]() returns a fixed-size list backed by the array. Modifications to the list reflect
in the array and vice versa. Wrap it in new ArrayList<>() for a truly independent, modifiable
list.
Garbage Collection
What is Garbage Collection?
Garbage Collection (GC) is the automatic memory management process where the JVM identifies
and reclaims objects that are no longer reachable by any live thread.
How Objects Become Eligible for GC
Nulling a reference: obj = null;
Reassigning a reference: obj = new Object();
Object created inside a method (local scope ends)
Island of isolation (objects referencing only each other, but unreachable from roots)
Java & OOP Interview Guide 10
Generational Model
Region Description GC Type
Young Gen (Eden + Survivor) Newly created objects Minor GC (fast)
Old Gen (Tenured) Long-lived objects Major GC (slower)
Metaspace Class metadata (replaced PermGen in Java —
8)
Key GC Algorithms
Serial GC: Single-threaded; suitable for small applications.
Parallel GC: Multi-threaded for throughput.
G1 GC: Default since Java 9; divides heap into regions; balances latency and throughput.
ZGC / Shenandoah: Ultra-low-pause collectors for large heaps.
Important Points
[Link]() is only a request; the JVM may ignore it.
finalize() is deprecated — use try-with-resources or [Link].
GC roots: static fields, local variables on stack, active threads, JNI references.
SQL Quick Reference (for Java Interviews)
Interviewers often test basic SQL alongside Java. Key topics:
JDBC Workflow
// 1. Load driver ( auto since JDBC 4.0)
// 2. Get connection
Connection conn = DriverManager . getConnection ( url , user , pass ) ;
// 3. Create statement ( use Pr epared Statem ent to prevent SQL injection )
Pre paredS tateme nt ps = conn . prepareStatement (
" SELECT * FROM employees WHERE dept = ? "
);
ps . setString (1 , " Engineering " ) ;
// 4. Execute query
ResultSet rs = ps . executeQuery () ;
while ( rs . next () ) {
System . out . println ( rs . getString ( " name " ) ) ;
}
// 5. Close resources ( or use try - with - resources )
rs . close () ; ps . close () ; conn . close () ;
Java & OOP Interview Guide 11
Common SQL Concepts Asked
Topic Key Points
JOINs INNER, LEFT, RIGHT, FULL OUTER, CROSS
GROUP BY / HAVING Aggregate then filter groups
Indexes Speed up reads, slow down writes; B-Tree vs. Hash
Normalization 1NF, 2NF, 3NF — eliminate redundancy
Transactions ACID properties; [Link](false) in JDBC
Statement vs. PreparedStatement PreparedStatement is precompiled, safer (prevents SQL
injection), and faster for repeated queries
Bonus: Commonly Asked Follow-ups
== vs. .equals()
== compares references (memory addresses).
.equals() compares content/value (if overridden properly).
String a = new String ( " Hi " ) ;
String b = new String ( " Hi " ) ;
System . out . println ( a == b ) ; // false ( different objects )
System . out . println ( a . equals ( b ) ) ; // true ( same content )
String Pool
String literals are stored in a special pool in heap memory. Identical literals point to the same pooled
object, saving memory.
String x = " Hello " ;
String y = " Hello " ;
System . out . println ( x == y ) ; // true ( same pool reference )
this and super
this — refers to the current object; used to resolve ambiguity, call constructors.
super — refers to the parent class; used to call parent constructors or overridden methods.
Method Overloading vs. Overriding
Overloading Overriding
Where Same class Subclass
Signature Same name, different params Same name & params
Return type Can differ Same or covariant
Binding Compile time (static) Runtime (dynamic)
@Override Not used Recommended
Java & OOP Interview Guide 12
Access Modifiers Summary
Modifier Class Package Subclass World
public
protected Ö
(default) Ö Ö
private Ö Ö Ö
Best of luck with your interview!