How the JVM Executes Java Methods

Most Java developers use methods every day. But very few actually know what's happening inside the JVM when they do. I was one of them. Until I went deep on it. Let me walk you through it simply. class Test {   public static void main(String[] args) {     m1();   }   public static void m1() {     m2();   }   public static void m2() {     int x = 10;   } } Take this code: main() → calls m1() → calls m2() Here's what JVM actually does: 1️⃣ JVM starts → creates the main thread 2️⃣ That thread gets its own Stack Area in memory 3️⃣ main() goes in → starts running 4️⃣ main() calls m1() → m1() goes on top → main() just... waits 5️⃣ m1() calls m2() → m2() goes on top → m1() waits too 6️⃣ m2() runs (it's at the top, so it gets to go first) 7️⃣ m2() finishes → removed from stack 8️⃣ m1() wakes up → finishes → removed 9️⃣ main() wakes up → finishes → removed 🔟 Stack memory is gone. JVM cleaned it up itself. A few things that actually surprised me: → Only ONE method is running at any moment. The rest are just waiting. → The stack works LIFO — last in, first out. Like a pile of plates. → Each method call creates its own little space (stack frame) → And the Garbage Collector? It doesn't touch stack memory at all. JVM handles it directly. Once I understood this, debugging became so much clearer. You stop guessing and start actually reading what the JVM is doing. This is the kind of stuff nobody teaches you in tutorials. But it's what makes you a stronger Java developer. #Java #JVM #CoreJava #Programming #LearningInPublic #JavaDeveloper #SoftwareDevelopment

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories