$ Core Java — Complete Interview Revision
// 6-7 Yrs Experience — Full Core Java + OOP Revision Before Interview
1. Java Platform & Execution
Quick Reference
JDK
Development Kit = JRE + Compiler + Debugger + Tools
JRE
Runtime Environment = JVM + Core Libraries
JVM
Loads classes, executes bytecode, manages memory & GC
javac
Compiles .java → .class (bytecode)
Remember
JDK = JRE + Development Tools
JRE = JVM + Libraries
JVM = Executes Java Bytecode
Execution Flow & Features
.java → Output
.java File
javac Compiler
.class Bytecode
JVM
Machine Code / Output
JVM makes Java platform independent — bytecode runs on any OS with a JVM ("write once, run anywhere").
Java Features
✓ Platform Independent ✓ Object Oriented ✓ Secure ✓ Robust ✓ Portable ✓ Multithreaded ✓ High Performance (JIT) ✓ Auto Garbage Collection ✓ Distributed ✓ Dynamic
2. Data Types, Wrappers & Casting
Primitive Data Types (8)
byte
1 byte
short
2 bytes
int
4 bytes
long
8 bytes
float
4 bytes
double
8 bytes
char
2 bytes
boolean
JVM Dependent
Primitive vs Object · Wrapper Classes · Autoboxing
Primitive
StorageStored Directly (Stack)
SpeedFast
NullCannot Be Null
MethodsNo Methods
Exampleint age = 25;
Object (Wrapper)
StorageReference Type, Stored In Heap
SpeedSlower (boxing overhead)
NullCan Be Null
MethodsHas Methods
ExampleInteger age = 25;
Wrapper Mapping + Why Needed
byte→Byteshort→Short, int→Integer, long→Long
float→Floatdouble→Double
char→Characterboolean→Boolean
Why Wrapper Classes?
Collections store Objects → Generics require Objects → Utility methods → Can store null
Autoboxing / Unboxing & Integer Caching
Autoboxing vs Unboxing
int
→ autobox →
Integer
Integer
→ unbox →
int
Example: Integer x = 10; int y = x;
Integer Cache (-128 to 127)
Integer a = 100; Integer b = 100; → a == b → true (cached) Integer a = 200; Integer b = 200; → a == b → false (new objects)
⚠ Always use .equals() to compare wrapper values, never ==.
3. Object Class & String
Object Class — Root of Every Class
Methods on java.lang.Object
toString() equals() hashCode() clone() getClass() wait() notify() notifyAll() finalize() (deprecated)
Default toString()ClassName@HashCode. Always override for readable output, e.g. Employee{id=101,name=John}.
String Immutability, Pool & Comparison
String Memory Model
├── String s1 = "Java"; → goes to String Constant Pool (reused if exists) └── String s2 = new String("Java"); → new Heap Object + separate Pool entry
Pool purpose: reuse objects, save memory, improve performance. String a="Java"; String b="Java"; → same object.
==
ComparesReference / Memory Address
equals()
ComparesActual Value / Content
✓ Why String is immutable: Security, Caching, Thread Safety, Performance, enables String Pool.
String vs StringBuilder vs StringBuffer
String
Immutable — every modification creates a new object.
Thread SafeSlow on Modification
StringBuilder ⭐
Mutable, modifies same object, no synchronization.
Not Thread SafeFastestSingle Thread
StringBuffer
Mutable, synchronized methods — safe across threads.
Thread SafeSlowerMulti Thread
Common String Methods
length()size of string
charAt()char at index
substring()extract portion
contains()check substring
equalsIgnoreCase()case-insensitive compare
startsWith()/endsWith()prefix/suffix check
replace() / trim()modify content
split()tokenize by delimiter
indexOf()position of substring
4. Variables, Casting, Operators & Arrays
Variable Types
LocalInside a method, must be initialized before use
InstanceInside class, per-object, gets default value
StaticBelongs to class, shared across all objects
Type Casting
Implicit int → long (widening, automatic) Explicit double → int (narrowing, needs cast)
Operators
Arithmetic + − * / % Relational == != > < >= <= Logical && || ! Bitwise & | ^ ~ Shift << >> >>>
Control Statements
if · if-else · switch · for · while · do-while · break · continue · return
Array vs ArrayList
Array
SizeFixed
StoresPrimitives + Objects
PerfFast, continuous memory, index starts at 0
ArrayList
SizeDynamic / Resizable
StoresObjects only
PerfSlight overhead vs array, more flexible
5. OOP — Four Pillars
Quick Reference
Class
Blueprint / Template — Variables & Methods
Object
Instance of a Class
Encapsulation
Data Hiding — Wraps Data + Methods
Inheritance
Code Reusability — IS-A Relationship
Polymorphism
One Interface, Many Forms
Abstraction
Hide Implementation Details
Four Pillars Detail
1. Encapsulation
Wrapping data and methods into a single unit; achieved using private variables with public getters/setters.
Data HidingSecurityMaintainability
Ex: private balance + getBalance()
2. Inheritance
Child class inherits properties & behavior from a parent class — promotes code reusability, IS-A relationship.
SingleMultilevelHierarchicalMultiple (via Interface)
Ex: class Dog extends Animal
3. Polymorphism
One interface, many forms — the same action behaves differently on different objects.
Compile-Time (Overload)Runtime (Override)
Ex: A Person can be Employee, Patient & Father at once
4. Abstraction
Showing only essential details and hiding implementation complexity from the user.
Abstract ClassInterface
Ex: car.start() hides engine internals
Inheritance Types & Polymorphism
│ ├── Inheritance (IS-A): child reuses parent's members │ ├── Single: Dog extends Animal │ ├── Multilevel: Puppy extends Dog extends Animal │ ├── Hierarchical: Dog, Cat both extend Animal │ └── Multiple (via Interface): class Duck implements Flyable, Swimmable — Java doesn't allow multiple class inheritance (diamond problem) │ └── Polymorphism: same call, different behavior ├── Compile-Time — Overloading: add(int,int) vs add(int,int,int) └── Runtime — Overriding: Animal.speak() → Dog.speak() @Override
6. Relationships & Abstract Class vs Interface
HAS-A Relationship Types
AssociationHAS-A, fully independent — Teacher ↔ Student
AggregationWeak HAS-A, parts exist independently — Department ↔ Employee
CompositionStrong HAS-A, parts can't exist alone — Car ↔ Engine
Abstract Class vs Interface
Feature Comparison
FeatureAbstract ClassInterface
ConstructorYesNo
VariablesAny Typepublic static final
MethodsAbstract + ConcreteAbstract, Default, Static
InheritanceSingleMultiple
StateYesNo
Interface vs Abstract Class
│ ├── Interface: 100% Contract — "What to do" │ └── A class can implement multiple interfaces │ └── Abstract Class: Partial Implementation — "What + How (partial)" └── A class can extend only one abstract class
Interface → Contract. Abstract Class → Partial Implementation.
7. Constructors, this/super, Overload vs Override
Object / Constructor Flow
new Employee()
Memory Allocated
Constructor Executed
Object Initialized
Reference Returned
Types: Default Constructor (no args), Parameterized Constructor, Copy Constructor (user-defined pattern).
Constructor Chaining: this() = same class, super() = parent class. Must be the first statement.
this
Refers toCurrent Object
Used forCurrent variable, method, constructor chaining
super
Refers toParent Class
Used forParent variable, method, parent constructor call
Overloading vs Overriding
Overloading
WhenCompile-Time Polymorphism
RuleSame name, different signature
Varies byNumber / Type / Order of Params
ClassSame class
Overriding
WhenRuntime Polymorphism
RuleSame signature, same/covariant return
Varies byImplementation in Child Class
ClassParent → Child (@Override)
8. static / final, Access Modifiers, Packages
static Members
Static Variable → one copy, shared by all objects (constants, counters, config) Static Method → can access only static members, cannot use this/super Static Block → runs once when class loads, for static init Static Nested Class → no outer object needed
final Keyword
final Variable → cannot change (constant) final Method → cannot override final Class → cannot extend
static final together → compile-time constant, e.g. final int MAX = 100;
Access Modifiers
ModifierSame ClassPackageChildOutside
privateYesNoNoNo
defaultYesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes
Packages & Class Loading
Packages organize classes, avoid name conflicts, provide access control. import class · import static static members · package.* wildcard (no sub-packages)
Class Loading Order
Class Loaded
Static Block
main()
Object + Constructor
9. SOLID Principles
S — SRP
Single Responsibility — one class, one reason to change
O — OCP
Open for Extension, Closed for Modification
L — LSP
Child must replace Parent without breaking behavior
I — ISP
Many small interfaces > one large interface
D — DIP
Depend on Abstraction, not Concrete class
Quick Example — ISP + DIP
Bad: NotificationService → handles Email + SMS + WhatsApp inside same class Good: Notification Interface → EmailService, SMSService, WhatsAppService (separate implementations)
10. Inner Classes, Enum, Record, Annotations
Types of Inner Classes
Member InnerNon-static, needs outer object, accesses all outer members
Static NestedStatic, no outer object needed, accesses only static members
Local InnerDeclared inside a method, scope limited to that method
Anonymous InnerNo class name, one-time use, now mostly replaced by Lambdas
Enum · Record · Annotations
Enum
Special class representing a fixed set of constants. Can have fields, constructors, methods, interfaces, switch support.
Type SafetyCompile-Time Check
Record (Java 16+)
Immutable data carrier. Auto-generates constructor, getters, equals(), hashCode(), toString().
Less BoilerplateEx: record Employee(int id, String name)
Annotations
Metadata for compiler, framework, or runtime — @Override, @Deprecated, @FunctionalInterface, @Component, @Autowired.
Retention: SOURCE/CLASS/RUNTIME
11. Cloning, Immutability, equals/hashCode, Comparable vs Comparator
Shallow vs Deep Copy
Shallow Copy
PrimitivesCopied
ReferencesShared — nested object changes reflect in both
Trade-offFast, less memory
Deep Copy
PrimitivesCopied
ReferencesNested objects also copied → fully independent
Trade-offSafe, more memory
Cloneable is a marker interface required for clone(), otherwise CloneNotSupportedException.
Immutable Class — How to Build
final class
private final fields
No Setters
Init via Constructor
Defensive Copies for mutable fields
Benefits: Thread Safe, Simple, Secure, Cache Friendly, Reliable. Examples: String, Wrapper Classes, Record.
== vs equals() vs hashCode()
==
ComparesReference / Memory Address
equals()
ComparesContent / Business Value
Why Override Both equals() & hashCode()?
Key
hashCode()
Find Bucket
equals()
Correct Entry
Rule: Equal objects must have the same hashCode(). Overriding only equals() breaks HashMap/HashSet.
Comparable vs Comparator
Comparable
SortingSingle / Natural Ordering
LocationInside the class
MethodcompareTo()
Use WhenEmployee ID, Student Roll No, Product ID
Comparator
SortingMultiple / Custom Ordering
LocationOutside the class
Methodcompare()
Use WhenSort by Salary, Age, Department, Name
12. Serialization & Reflection
Serialization Flow
Java Object
ObjectOutputStream
Byte Stream
File / Network
ObjectInputStream
Java Object (restored)
Requires Serializable (marker interface). serialVersionUID ensures class compatibility on deserialization. transient fields (passwords, OTP) are skipped; static fields are never serialized.
Reflection
Inspect / modify / invoke classes, methods, fields — at runtime. Get Class Object: obj.getClass() · Employee.class · Class.forName() Used By: Spring, Hibernate, JUnit, Dependency Injection, ORM Disadvantages: Slow, breaks encapsulation, security risk — avoid in business logic
13. Garbage Collection & Memory Model
GC Flow & Eligibility
Object Created
Used
Reference Lost
Eligible for GC
Memory Reclaimed
Eligible when: reference = null · object out of scope · anonymous object · reassigned reference · island of isolation. System.gc() only requests GC, not guaranteed. finalize() is deprecated — avoid.
Heap vs Stack & JVM Memory Areas
Heap
StoresObjects
ScopeShared, managed by GC, large memory
Stack
StoresMethod calls, local variables
ScopeThread-specific, auto-cleared
JVM Memory Areas
JVM Memory → Heap Stack Metaspace PC Register Native Stack
Memory Errors
OutOfMemoryError → heap full (large objects, memory leak, infinite collection growth) StackOverflowError → deep / infinite recursion
Memory Leaks & Reference Types
Memory Leak — Causes & Prevention
Cause: Static Collections · Unclosed Resources · Listeners · Caches · ThreadLocal · Large Maps Prevent: Close resources · Remove listeners · Limit cache size · Avoid static collections · Use weak references · Monitor heap
Weak / Soft / Phantom Reference
WeakReference → collected even if reference exists — used in caching SoftReference → collected only when memory is low — memory-sensitive cache PhantomReference → advanced cleanup — rare interview topic
14. Best Practices & Common Differences
Real Project Best Practices
Prefer Composition Over Inheritance
Use Constructor Injection over Setter Injection
Mark constants as static final
Keep fields private, program to interfaces
Follow SOLID Principles
Avoid deep inheritance hierarchies
Always override toString()
Override equals() and hashCode() together
Never use == for String comparison
Use StringBuilder inside loops
Prefer Record for DTOs (Java 17+)
Use Enum instead of String constants
Avoid clone() in modern Java — use copy constructor/Builder
Make domain objects immutable where possible
Close resources via try-with-resources
Use Optional as return type, not as field/param
Follow DRY, KISS, YAGNI
Keep methods small, one responsibility per class
Top Interview Differences
HeapvsStack
SerializablevsExternalizable
Shallow CopyvsDeep Copy
==vsequals()
equals()vshashCode()
ComparablevsComparator
Abstract ClassvsInterface
StringvsStringBuilder
ArrayvsArrayList
CompositionvsInheritance
CheckedvsUnchecked Exception
HashMapvsConcurrentHashMap
ListvsSet
HashSetvsTreeSet
HashMapvsHashtable
Interview Tips — Frequently Asked "Why"
Why override hashCode() with equals()?
HashMap first uses hashCode() to locate the bucket, then equals() to identify the correct object. Overriding only equals() breaks hash-based collections.
Why is String immutable?
Security, Thread Safety, Caching, String Pool reuse, and reliability as a HashMap key.
Comparable or Comparator?
Comparable for one natural ordering (defined inside the class). Comparator when multiple sorting strategies are needed (defined outside the class).
Why prefer Enum over String constants?
Type safety, compile-time checking, better readability, and switch support.
15. 50 One-Liner Revision
JDK → Development Kit
JRE → Runtime Environment
JVM → Executes Bytecode
Object → Parent Class of All
String → Immutable
String Pool → Reuses String Objects
Wrapper → Object Representation of Primitive
Autoboxing → Primitive to Wrapper
Unboxing → Wrapper to Primitive
Encapsulation → Data Hiding
Abstraction → Hide Implementation
Inheritance → Code Reuse
Polymorphism → One Interface, Many Forms
Constructor → Object Initialization
this → Current Object
super → Parent Object
Overloading → Compile Time
Overriding → Runtime
static → Belongs to Class
final → Cannot Change
private → Same Class Only
protected → Package + Child
public → Everywhere
Package → Organize Classes
SOLID → Maintainable Code
Enum → Type Safe Constant
Record → Immutable Data Carrier
Annotation → Metadata
Clone → Copy Object
Shallow Copy → Shared Reference
Deep Copy → Independent Copy
Immutable → Cannot Change After Creation
== → Compare Reference
equals() → Compare Content
hashCode() → Hash Bucket
Comparable → Natural Sorting
Comparator → Custom Sorting
Serializable → Convert Object to Bytes
transient → Skip Field in Serialization
Reflection → Runtime Inspection
Heap → Object Memory
Stack → Method Memory
GC → Cleans Unused Objects
Memory Leak → Unused but Referenced Object
try-with-resources → Auto Close
DRY → Don't Repeat Yourself
KISS → Keep It Simple
YAGNI → Build Only What's Needed
Array → Fixed Size
ArrayList → Dynamic Size
16. 6-7 Yrs Interview Expectations & Revision Flow
Interviewers Expect You To Explain
✓ Internal Working ✓ JVM Basics ✓ Memory Management ✓ OOP Design ✓ SOLID Principles ✓ Object Lifecycle ✓ Collection Selection ✓ Performance Considerations ✓ Multi-threading Basics ✓ Real Project Examples ✓ Why One Approach Is Better Than Another
Core Java Revision Flow
Java Platform (JDK→JRE→JVM)
Data Types → Wrapper Classes → String
OOP (4 Pillars) → SOLID
Constructors → static/final → Object Class
equals/hashCode → Comparable
Serialization → Reflection
Garbage Collection → Best Practices