Core Java
Quick Reference Cheatsheet
OOP Principles
EncapsulationBind data+methods, hide with access modifiers
InheritanceAcquire behavior from parent class
PolymorphismMany forms of methods (not objects)
AbstractionHides complexity behind all three above
Class = Blueprint defining:
Behavior (methods)  · Identity (name)  · State (instance field values)
Is Java pure OOP? No — lacks multiple inheritance, operator overloading; has primitive types.
Real-World Examples
Encapsulation: BankAccount — balance is private, only deposit()/withdraw() can modify it; ensures balance never goes negative
Inheritance: HttpServletMyController — inherits request handling, lifecycle hooks; child overrides doGet()/doPost()
Polymorphism: PaymentProcessor.process(Payment p) — at runtime p could be CreditCard, UPI, or Wallet; correct method invoked via vtable
Abstraction: JDBC — you call connection.prepareStatement() without knowing if it's MySQL, Postgres, or Oracle underneath
Access Modifiers
ModifierSame ClassSame PkgSubclass (diff pkg)Unrelated (diff pkg)
private
default
protected
public
Top-level classes: only public or default. Private constructor allowed in abstract class; Spring/Hibernate access via reflection.
JDK / JRE / JVM
JDKJRE + dev tools (for programmers)
JREJVM + library classes (for users)
JVMJIT compilation + GC; platform-specific
JVM Architecture
Class LoadersRuntime Data AreaExecution Engine
Class Loaders (delegation hierarchy)
BootstrapCore APIs / java.base (C/C++)
Platformjava.sql, java.xml (formerly Extension)
ApplicationYour code + classpath JARs
Parent asked first. Child loads only if parent fails → prevents class hijacking.
Runtime Data Areas
AreaPerStoresNotes
Method AreaJVMClass-level data, static fieldsImplemented by Metaspace
HeapJVMObjects, instance vars, arraysShared; Eden→Survivor→OldGen
StackThreadStack frames (local vars, operand stack)Not shared; StackOverflowError
PC RegisterThreadAddr of current instructionThread private
Native StackThreadNative method execution (JNI)Maps to OS thread
Heap Generations
Young Gen: Eden + S0 + S1 (+ Keep Area) → Minor GC  · Old Gen: long-lived objects (age > 15) → Major GC  ·  Object ≥ 50% heap → directly promoted to Old
Metaspace
ReplacedPermGen (removed Java 8)
LocationNative RAM (not JVM heap)
GrowsDynamically (no fixed-size OOM)
Storesklass metadata, method bytecode, constant pools
GC triggerWhen hits High Water Mark threshold
Freed whenClassLoader becomes unreachable
Heap has java.lang.Class object per class (bridge to metadata). Used in instanceof & Reflection API.
Garbage Collectors
GCSTW?Compacts?PauseNotes
SerialFullYesHighSingle thread GC
ParallelFullYesMediumMulti-thread GC
CMSPartialNoLowDeprecated Java 9 (fragmentation)
G1PartialYes~100msDefault since Java 9; region-based
ZGCMinimalYes~10msColored pointers + load barriers
ShenandoahMinimalYes~10msForwarding pointer; concurrent
EpsilonNo GCNoneNo reclaim; JVM crashes when full
GC runs as daemon thread. System.gc() is a hint only — never rely on it in production.
Tiered Compilation (Java 8+)
 L0 InterpreterSlow start, profiling begins
 L1 C1 SimpleTrivial methods, no profiling
 L2 C1 LimitedBasic counters, C2 queue full
 L3 C1 FullStandard: fast + full profiling
 L4 C2Peak: inlining, escape analysis
Before Java 8: choose Client (C1) or Server (C2). Now JVM auto-promotes based on method hotness.
Sorting
Primitive arraysDual-Pivot Quicksort
Object arraysTimsort (stable)
Very smallInsertion Sort
Timsort = Merge + Insertion. Stable — equal elements preserve relative order. Primitives don't need stability.
Exception Hierarchy
Complete Hierarchy Tree
java.lang.Throwable
├── Error (unchecked — do NOT catch)
│ ├── VirtualMachineError
│ │ ├── StackOverflowError
│ │ └── OutOfMemoryError
│ ├── LinkageError
│ │ ├── NoClassDefFoundError
│ │ └── UnsatisfiedLinkError
│ └── AssertionError
└── Exception
├── IOException (checked)
│ ├── FileNotFoundException
│ └── EOFException
├── SQLException (checked)
├── ClassNotFoundException (checked)
├── InterruptedException (checked)
├── ReflectiveOperationException (checked)
│ ├── NoSuchMethodException
│ └── IllegalAccessException
└── RuntimeException (unchecked)
├── NullPointerException
├── ClassCastException
├── IndexOutOfBoundsException
│ ├── ArrayIndexOutOfBoundsException
│ └── StringIndexOutOfBoundsException
├── IllegalArgumentException
│ └── NumberFormatException
├── IllegalStateException
├── UnsupportedOperationException
├── ArithmeticException
├── ConcurrentModificationException
└── SecurityException
Checked vs Unchecked
· Checked: must handle (try/catch or throws) — compiler enforces
· Unchecked (Runtime): optional to handle — programming errors
· Error: JVM-level, unrecoverable — never catch
Key Rules
· Override can throw fewer checked exceptions, never more
· Union catch: catch(A | B e)
· try-with-resources: closing exception → suppressed
· finally return silently discards thrown exception ⚠
· Exception thrown in finally overrides catch exception
· Avoid exceptions for flow control
· ClassNotFoundException: class missing at runtime from classpath
· NoClassDefFoundError: class found at compile time, not at runtime (missing JAR)
Custom Exception
· Extend Exception → checked
· Extend RuntimeException → unchecked
· Always provide message + cause constructor
String Internals
Immutable?Yes — memory, security, thread-safe, cacheable
Storage (Java 9+)Compact Strings: byte[] or char[]
String PoolHeap (GC eligible). Interning dedupes literals
new String()Always new heap object (bypasses pool)
+ operatorCompiles to StringBuilder.append()
Dynamic concatGoes to heap, NOT pool
StringBuilder vs StringBuffer
StringBuilderNot thread-safe, fast
StringBufferSynchronized, slight overhead. Resize: 2*size+2
Useful Methods
appendinsert(i,v)delete(s,e)reversesetLength(0)isBlank() Java11strip()join(delim,...)intern()
Inner Classes
TypeAccess outerNotes
Static nestedStatic members onlyNo outer instance needed. Builder pattern.
MemberAll outer membersNeeds outer instance. new outer.new Inner()
LocalOuter fields + effectively final method varsDefined inside a method
AnonymousSame as localOne-shot impl. Compiler makes Iface$1.class
Abstract Class vs Interface
FeatureAbstract ClassInterface
Instantiate
Constructor✅ (for subclass init)
Instance fields❌ (public static final only)
Multiple inherit
Default methods✅ (Java 8+)
Static methods
Private methods✅ (Java 9+)
State❌ (constants only)
Use abstract: shared code + state + IS-A.  Use interface: contract, unrelated classes, multiple behavior.   Default method override cannot be made abstract. SAM interface = Functional Interface.
Relationships
IS-A
Generalizationclass A extends B
Realizationclass A implements B
HAS-A / Association
Simple AssocA has B, B has A — both exist independently
AggregationA has List<B>; B exists independently
CompositionA creates B inside itself; B dies with A
DependencyA uses B temporarily (param/local var)
Polymorphism & Method Dispatch
Parent obj = new Child();
obj.method(); // → Child's (dynamic dispatch via vtable)
obj.field // → Parent's field (compile-time)
obj.staticMethod() // → Parent's (method hiding, compile-time)
invoke* bytecode instructions
invokeVirtualInstance methods (vtable lookup)
invokeStaticStatic methods (compile-time)
invokeSpecialprivate, final, constructors, super
invokeInterfaceInterface method calls
invokedynamicLambdas, dynamic langs (Java 7+)
invokedynamic (Lambda flow)
1. invokedynamic run()Runnable
2. Bootstrap: LambdaMetafactory.metafactory()
3. Returns CallSiteMethodHandle
4. JVM replaces dynamic link with direct call
Also used for String concat (Java 9+)
vtable: per-class in metaspace. Non-static/non-private/non-final methods get a slot. Overriding updates child's vtable slot.
hashCode & equals Contract
Contractequals() → same hashCode (not vice versa)
String hashs[0]·31^(n-1) + … + s[n-1]
Must override hashCode when you override equals. Use Objects.hash(fields...).
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User u = (User) o;
return id == u.id && Objects.equals(email, u.email);
}
@Override public int hashCode() {
return Objects.hash(id, email);
}
Annotations
Built-in
@OverrideVerify method overrides parent
@DeprecatedMark API as outdated
@SuppressWarningsIgnore specific compiler warnings
@FunctionalInterfaceEnforce SAM; error if >1 abstract method
@SafeVarargsSuppress vararg type warnings
@NativeField may be referenced by native code
Meta Annotations
@TargetWhere annotation applies (METHOD, TYPE…)
@RetentionSOURCE / CLASS / RUNTIME
@InheritedSubclasses inherit parent's annotations
@DocumentedInclude annotation usage in Javadoc
@RepeatableSame annotation multiple times on element
Reference Types
StrongNormal variable; GC never collects
SoftSoftReference<T> — collected only on memory shortage
WeakWeakReference<T> — collected on next GC run
PhantomCan't access obj; enqueued to ReferenceQueue after collection
wr.get() returns strong ref — object won't be GC'd while held. Use phantom for post-mortem cleanup.
Static & Final
Static
static varClass-level, shared by all instances
static blockRuns once on class load; init static vars
static methodClass-scoped; no this or super
static inner classNo outer instance needed — new Outer.Inner()
top-level classCannot be static
Final
final fieldCan't be reassigned after init
final methodCan't be overridden
final classCan't be extended (e.g. String)
Casting & Boxing
Widening (auto)
byte→short→char→int→long→float→double
Narrowing (explicit cast)
int i = (int) 3.14;
Autoboxingint → Integer (compiler)
UnboxingInteger → int (compiler)
Covariant returnOverride with subtype return type ✅
LTS Releases
Java 8Lambda, Stream, Optional, java.time, Metaspace replaces PermGen
Java 11var in lambda, Epsilon GC, HTTP Client API
Java 17Sealed classes, pattern matching instanceof, remove Applet API
Java 21Sequenced Collections, record patterns, Generational ZGC, virtual threads
Java 25Primitive types in instanceof & switch patterns
Regex (java.util.regex)
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("abc123");
while (m.find()) m.group(); // 123
// matches() = whole string
// find() = partial match
// m.group(1) for capture groups
Patterns
.any char\ddigit\Dnon-digit\w[a-zA-Z0-9_]\s / \Swhitespace / non^ $start / end of string(abc)capture group(?:abc)non-capturing* + ?0+ / 1+ / 0|1{n,m}between n and m times|or
⚠ Compile outside loops: static final Pattern P = Pattern.compile(...)
JAR & Classpath
# Compile into bin/
javac -d bin src/Main.java
 
# Create executable JAR
jar --create --file App.jar \
--main-class com.example.Main -C bin .
 
# Run JAR
java -jar App.jar
 
# Compile with classpath
javac -cp "lib.jar" -d bin Main.java
java -cp "lib.jar;bin" com.example.Main
Windows: ; in classpath. Mac/Linux: :. First entry wins on duplicate class names.
Object Methods & Java Memory Model
Object (root) class methods
equalshashCodetoStringgetClassclonefinalizenotifynotifyAllwait
finalize() = legacy GC cleanup hook. Replaced by try-with-resources + AutoCloseable.
Java Memory Model (JMM)
Visibilityvolatile — flush/read from main memory
Atomicitysynchronized — indivisible op
OrderingCompiler/CPU may reorder; happens-before prevents it
happens-beforeActions before edge visible to actions after; volatile enforces
Without sync, threads may cache stale values indefinitely.
CORE JAVA CHEATSHEET  ·  OOP · JVM · Memory · GC · Exceptions · Strings · Annotations