0% found this document useful (0 votes)
3 views7 pages

Java JVM Notes

Uploaded by

sagarshaivaooo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Java JVM Notes

Uploaded by

sagarshaivaooo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA & JVM INTERNALS

From .java to running Object — Master Revision Notes

01 Big picture flow 02 .java -> .class (compile)

03 Inside a .class file 04 Class Loading: 3 phases

05 Metaspace 06 The Class object

07 Object creation basics 08 Object memory layout

09 [Link] root 10 Method dispatch & invoke*

11 Class vs Interface 12 Static vs Instance

13 JIT compiler magic 14 Constant pool

15 Stack vs Heap 16 Garbage Collection

17 Full init order (master) 18 final keyword

19 String pool special case 20 try/finally rules

21 JVM Architecture diagram

Ultimate one-liner: JVM turns .class bytecode into metadata + Class objects, and every real object is just DATA
+ a POINTER to that metadata.

01 Big picture — one flow to rule everything


.java (code) -> javac -> .class (bytecode) -> ClassLoader -> Metaspace (metadata) -> Class object (heap)
-> Objects (heap instances)

Factory analogy: Class = Factory blueprint · Object = Product · Memory = Warehouse.

02 .java -> .class (Compilation)


class A {
int x = 10;
}

javac compiles Platform-independent bytecode, stored in a .class file.

.class file is NOT an object · NOT executable directly · just a structured binary format.

JVM understands This bytecode format — NOT Java syntax.

03 Inside a .class file — the blueprint package

Contains

Class name · Methods (bytecode) · Fields · Constant pool (strings, refs) · Flags (class/interface/abstract)
04 Class Loading — entry into JVM (ClassLoader)

Triggered the first time a class is actually used: new A(), [Link](), or [Link] (non-constant).

1. Loading Reads .class file, brings it into JVM. Class structure ready, NO values assigned yet.

2a. Verification Checks bytecode is safe and valid.

2b. Preparation Allocates static memory, assigns DEFAULT values. static int x=10 -> x=0 here (not 10 yet).

2c. Resolution Replaces symbolic references with actual memory references (happens silently).

3. Initialization Runs static blocks + assigns real static values, TOP -> BOTTOM, in source order.

static int x = 10;


static { print("hello"); }

-> Execution: x = 10, then print "hello"

05 Metaspace — where the class itself lives

Holds Method definitions · Field structure · Runtime constant pool · vtable / itable

Does NOT hold Objects — only class-level info.

Cleanup Metaspace is cleaned only when the CLASS is unloaded (rare).

06 The Class object — runtime representation

For every loaded type, JVM creates ONE [Link] object in the HEAP. e.g. [Link] refers to that object.

Used for

Reflection · instanceof checks · Method lookup support

07 Object creation — real runtime steps


A obj = new A();

1. Check JVM checks if class is already loaded (loads it if not).

2. Allocate Allocates memory for the object in the Heap.

3. Defaults Sets default values (int->0, Object->null).

4. Field init Runs instance field initializers (e.g. int x = 5).

5. Constructor Runs the constructor body — final setup.

6. Link Object is linked to its class metadata (klass pointer).


08 Object memory layout — actual JVM structure
[ Mark Word | Klass Pointer | Instance Data | Padding ]

Mark Word The "control center": hashcode, GC age, lock state (biased/lightweight/heavyweight), used
by synchronized.

Klass Pointer Points to class metadata in Metaspace — tells JVM what class this is, its methods, its size.

Instance Data The actual fields: int x; String name; etc.

Padding Memory alignment to 8-byte boundaries — pure performance optimization.

Objects do NOT store methods. They store DATA + a pointer to class metadata. Methods live in Metaspace.

09 [Link] — the common root


class A {}

// is actually:
class A extends Object {}

Every object toString() · equals() · hashCode() · wait() · notify()


automatically gets

Why it matters All objects share a common root -> enables polymorphism and uniform handling.

10 Method calls — dispatch & invoke* instructions

invokevirtual Normal instance method — uses vtable index, very fast (almost array access).

invokestatic Static method call.

invokespecial Constructor / private method call.

invokeinterface Interface method — uses itable, slightly indirect (extra lookup).

[Link]() -> JVM looks at the object's class, uses vtable/itable, finds the right method, executes bytecode.

vtable example — overriding


class A { void show() {} }
class B extends A { void show() {} }

[Link] -> show()


[Link] -> overridden show()

MENTAL MODEL — invokevirtual = fast direct jump (vtable). invokeinterface = small extra lookup (itable). JIT optimizes both
heavily.
11 Interfaces vs Classes

Feature Class Interface

Memory layout Yes No

Metadata Metaspace Metaspace

Runtime object Yes No

Dispatch vtable itable

MENTAL MODEL — Interface = contract + dispatch logic. Class = data + behavior.

12 Static vs Instance — under the hood

Static
Instance
Stored ONCE per class. Lives in Metaspace (or associated
structures). Stored PER OBJECT. Lives in Heap.

13 JIT Compiler — where the magic happens

JVM does not just interpret bytecode — it uses Just-In-Time compilation to convert HOT bytecode into native
machine code.

Inlining [Link]() gets replaced directly with the method body — avoids call overhead.

Devirtualization If JVM knows the exact runtime type (A obj = new B()), it skips lookup and calls [Link]()
directly.

Escape Analysis If new A() never "escapes" the method, JVM may allocate it on the STACK or eliminate it
entirely.

14 Constant Pool — the hidden hero

Each class stores String literals · Method references · Field references

Example [Link]("Hi") -> "Hi" is stored in the constant pool.

15 Stack vs Heap — execution model

Stack
Heap
Method calls + local variables. Fast, thread-specific (one
stack per thread). Objects. Shared across all threads.

main() -> Stack frame created -> Objects allocated in heap -> Methods resolved via vtable/itable -> Hot
code -> JIT compiled -> Native execution
16 Garbage Collection — quick touch

Cleans Only HEAP objects.

Metaspace Cleaned only when a class is unloaded.

Mechanism JVM tracks object reachability — unreachable objects become eligible for collection.

17 MASTER ORDER — full init flow (the one to memorize)

1 Loading Class loaded into Metaspace. Structure ready, no values yet.

2 Linking Verification -> Preparation (static defaults) -> Resolution.

3 Initialization Static variables assigned + static blocks run, top -> bottom.

4 Object Creation Heap memory allocated for new instance.

5 Instance defaults Fields set to 0 / null / false.

6 Instance field init Actual field initializer values assigned.

7 Constructor runs Final setup logic executes.

8 Object ready Fully constructed object returned to caller.

One-line cheat code: Load -> Prepare -> Initialize -> Create -> Assign -> Construct

When the flow changes:

Compile-time constant static final int x = 10; (primitive/String, constant expression) -> JVM inlines value
EVERYWHERE. Initialization step may be SKIPPED, static block may NOT run.

Wrapper / Object static final Integer x = 10; is NOT a compile-time constant -> normal initialization happens.
constants

Valid chained constant static final y = A.x; — valid IF A.x itself is a compile-time constant.

Inheritance order Parent class loads & initializes FIRST, then child.

Child-ref to parent static Accessing a PARENT static field via a CHILD reference only triggers the PARENT's
initialization, not the child's.

18 final keyword — clear & simple

final means: "can assign ONLY once."

final int x = 10; // value fixed forever

final int[] arr = {1,2};


arr[0] = 99; // ALLOWED!

Why arr[0]=99 works The REFERENCE is fixed (always points to same array) — but the OBJECT it points to is
still mutable.

Threading — why final matters


Case Result

Without final Other thread may see a half-built object

With final JVM guarantees a fully-built object

19 String special case — String Pool

String s = "abc"; Goes to the String Pool (shared, deduplicated).

new String("abc") Creates TWO objects: one in Pool (from literal) + one fresh in Heap.

.intern() Connects a Heap string back to its Pool reference.

20 try / finally rules

finally always runs Runs regardless of whether try/catch returns, throws, or completes normally.

No return in finally The ORIGINAL return value (from try/catch) is used.

Return in finally OVERRIDES everything — finally's return value wins, even over an exception.

21 JVM Architecture — the full picture

This is the textbook diagram that ties everything above together.

Class Loader

Loads .class files

Performs Linkage (verify, prepare, resolve)

Initializes Classes (static vars + static blocks)

Feeds from Class Files: [Link], [Link], [Link] ...

Runtime Data Areas

JAVA STACK
HEAP
Per-thread stack frames: local vars, operand stack, return
Stores all objects and arrays. GC managed. info.

METHOD AREA
PC REGISTER
Class structure info, constants, static vars, JIT code. Shared
across threads. Program counter for the current thread.

Execution Engine

INTERPRETER JIT COMPILER GARBAGE COLLECTOR

Executes bytecode instruction by Compiles hot code to native machine Reclaims memory from unreachable
instruction. code. objects.

Native Method Interface (JNI) & Native Libraries


JNI Interface to native libraries — bridges Java code with native (C/C++) code.

Native Libraries .so / .dll files — talks to OS / hardware directly.

Class Loader -> Runtime Data Areas -> <-> -> Execution Engine -> <-> -> Native Method Interface -> Native

Libraries

Execution Engine constantly talks to Runtime Data Areas (Heap/Stack/Method Area) while running —
Interpreter and JIT both feed off the same bytecode loaded by the Class Loader.

ULTIMATE TRUTH
JVM is not just running code — it is constantly rewriting, optimizing, and reshaping execution at runtime. Class (static
world) -> Object (instance world) -> Constructor (final touch).

You might also like