Day 11/30 🚀 Java Deep Dive: Class Loading, Static Flow & Execution Order In our recent Java sessions, I explored what really happens when a Java program runs — and it completely changed my understanding beyond the common “execution starts from main()” belief. 🔍 Key Learnings: ✅ A Java file can contain multiple classes → compilation generates multiple .class files ✅ JVM executes the class that contains the main method ✅ Before main() runs, JVM performs class loading and initializes: ➡️ Static variables ➡️ Static blocks ➡️ Then the main method stack frame is created 🧠 7 Elements of a Java Class: Static Variables Static Block Static Methods Instance Variables Instance Block Instance Methods Constructors ⚖️ Golden Rule: 👉 Static belongs to the class 👉 Instance belongs to the object This directly impacts memory allocation and execution flow: Static members → loaded once in the method area / static segment Instance members → created per object in the heap Instance block executes before constructor during object creation 🛠️ Behind the Scenes Flow: Source Code → Compilation → Bytecode → JVM → Class Loader → Static Initialization → main() → Object Creation → Constructor → Methods → Garbage Collection Understanding this internal flow helped me connect OOP concepts, memory model, and JVM architecture instead of treating them as separate topics. 📌 This is a crucial foundation for: ✔ Writing optimized Java code ✔ Understanding static vs instance behavior ✔ Cracking interviews on JVM & class loading #Java #JVM #OOP #ClassLoader #StaticKeyword #JavaInternals #ProgrammingJourney #SDEPreparation
Java Class Loading & Execution Order Explained
More Relevant Posts
-
☕ #ThinkingInJava — Post No. 2 Building deeper Java understanding, one concept at a time. 👉 What made me revisit this? While exploring Java file structure, I had a follow-up curiosity: if multiple classes can exist in one file, what happens to the main() method? Where should it live, and which one runs? 👇 💡 Java Concept — Multiple classes & main() behavior Java allows flexibility in structuring classes inside a file, but execution behavior is very explicit and runtime-driven. ✅ Core Rules / Facts • A Java file can contain multiple classes, but at most one can be public • The main() method does not have to be inside the public class • You can define main() in any class within the file • If multiple classes contain main(), none runs automatically • JVM executes only the class explicitly specified at runtime (or selected in IDE) 🎯 Interview One-liner 👉 In Java, the main() method can exist in any class, and when multiple entry points exist, the JVM runs only the class explicitly invoked. 🧠 Why this matters in real projects Understanding entry-point behavior helps while debugging multi-class utilities, running POCs, and organizing automation helpers that may contain independent executable code. 🔖 Takeaway Execution in Java is explicit → Structure is flexible → Clarity comes from understanding entry points hashtag #Java #AutomationSpecialist #TestAutomation
To view or add a comment, sign in
-
🚀 Day 30 – Core Java | How Java Actually Executes (Static, Class Loader & JRE Internals) Today completely changed our understanding of Java execution. For 30 days, we believed: “Java program execution starts from the main method.” Today we proved — that is NOT the complete truth. 🔹 What Really Happens When a Java Program Runs? Step-by-step execution flow: 1️⃣ OS gives control to JVM 2️⃣ JVM loads the class (via Class Loader) 3️⃣ During class loading: Static Variables are initialized Static Blocks are executed 4️⃣ Only then → main() method is executed So execution does NOT start from main directly. It starts from: Static members during class loading. 🔹 Class Loader – The Hidden Hero When a class is required during execution: JVM does not load it alone It takes help from Class Loader Class Loader loads required .class files into memory Important Interview Point: Class Loader is a part of JDK that helps JVM load classes during execution. 🔹 File Name vs Class Name – Biggest Myth Broken We proved practically: File name does NOT have to match class name. A single .java file can contain multiple classes. Multiple classes can even contain main() methods. JVM executes only the class you explicitly give while running. Example: javac Code.java java Demo JVM executes only Demo.class. 🔹 Inside RAM – JRE Structure When binary code is loaded into RAM: It enters JRE and is divided into: Code Segment Static Segment Heap Segment Stack Segment Execution order inside memory: 1️⃣ Static Variables 2️⃣ Static Block 3️⃣ main() 4️⃣ Object Creation → Heap 5️⃣ Instance Block 6️⃣ Constructor 7️⃣ Instance Methods This is the real execution hierarchy. 🔹 Static vs Instance (Golden Rule) Static belongs to Class Instance belongs to Object Static members are loaded during class loading. Instance members are created during object creation. Static cannot directly access instance members. Instance can access static members. This single rule clears 50% of Java confusion. 💡 Biggest Takeaway Java execution is not about writing syntax. It is about understanding: Class loading Memory allocation Stack & Heap behavior Static vs Instance lifecycle Execution flow order Strong fundamentals in memory behavior = Strong technical interviews. Day 30 built real internal clarity of Java execution. From here onwards, we move deeper into static concept and its real-world importance 🚀 #Day30 #CoreJava #JavaExecution #StaticKeyword #ClassLoader #JVM #JavaInternals #DeveloperJourney
To view or add a comment, sign in
-
🚀 Day 30 and 31 – Deep Dive into Static in Java Over the last two days, I gained a strong understanding of the Static concept in Java from both execution and real-world perspectives. 1️⃣ How Java Program Executes (Memory Understanding) I understood how a Java program runs inside JRE memory, which includes: 1.Code Segment 2.Stack 3.Heap 4.Method Area (Static Segment / Meta space) 2️⃣ Execution Order in Java 1.Static variables 2.Static block 3.main() method 4.Object creation 5.Instance block 6.Constructor 7.Instance methods This clearly explains the difference between class-level loading and object-level creation. 3️⃣ Static vs Instance – Core Difference 🔹 Static Belongs to Class Memory allocated once Loaded during class loading Shared among all objects 🔹 Instance Belongs to Object Memory allocated per object Loaded during object creation Separate copy for each object 4️⃣ 💡 Real-Time Use Case of Static (Banking Example) Using a loan interest calculation example: If 10000 objects are created Instance variable creates 10000 copies in memory Static variable creates only 1 shared copy ✅ This improves memory efficiency and application performance. 5️⃣ 🔧 Static Members and Their Use Cases 🔹 Static Variable Used when value must be common for all objects Example: rate of interest, PI value, shared counters 🔹 Static Block Executes once during class loading Used to initialize static variables 🔹 Static Method Can be called without creating an object Used for utility/helper methods Example: Math class methods 6️⃣ 📌 Key Takeaways Static improves memory optimization Static belongs to class, not object Static variables load only once Static block runs once during class loading Static methods do not require object creation Execution flow understanding is important before learning Inheritance Feeling more confident about how Java works internally in memory 💻✨ Grateful to my trainer Sharath R for explaining the concept clearly and practically 🙌 #Java #CoreJava #OOPS #StaticKeyword #LearningJourney #BackendDevelopment #SoftwareEngineering #FullStackDeveloper
To view or add a comment, sign in
-
-
🚀 Day 31 – Mastering Object Representation & String Handling in Java Understanding how objects communicate their data is a crucial step toward writing clean, professional Java code. Today’s focus was on mastering the toString() method and strengthening concepts around the String class. 📚 Concepts Covered ✔ Overriding toString() for meaningful object representation ✔ Using StringBuilder for efficient string construction ✔ Understanding how Java handles Strings internally ✔ Writing cleaner and more readable output for objects 💻 Hands-On Implementation Built a Car class and customized the toString() method to print structured and readable object details instead of default memory references. 💡 Key Takeaway By overriding toString(), we move from debug-unfriendly outputs to clear, structured, and professional object representation — a small change that significantly improves code quality and maintainability. Additionally, understanding the String class helps in writing optimized and efficient Java programs, especially when dealing with large-scale applications. 📈 What This Shows • Attention to clean coding practices • Understanding of core OOP concepts • Focus on writing maintainable and readable code • Practical implementation over just theory #Java #CoreJava #JavaProgramming #OOP #SoftwareDevelopment #CleanCode #StringHandling #DeveloperJourney #LearningInPublic #BackendDevelopment #TechSkills #Consistency
To view or add a comment, sign in
-
-
🚀 Day 32 – Core Java | Static Concepts & Introduction to Inheritance Today’s session connected two important concepts in Java: Static members and the second pillar of OOP – Inheritance. 🔑 Key Concepts Learned ✔ Static Variable Belongs to the class, not the object Only one copy exists in memory Used when a value is common for all objects Example: Bank interest rate or mathematical constant π ➡ Advantage: Efficient memory utilization ✔ Static Block Static blocks execute during class loading, even before the main() method. Two major uses: • Initialize static variables • Execute code before the program enters main() Execution order: Static Variables → Static Block → main() Method Multiple static blocks are allowed, and they execute in the order written in the program. ✔ Static Method Static methods can be accessed without creating an object. Example scenario: Converting Miles → Kilometers does not depend on any object. So the method can be declared as static. Called using: ClassName.methodName() Example: Car.milesToKilometer(380); ➡ Advantage: No object creation → Better memory usage ✔ Static vs Instance Access Rule Important concept from Java execution: • Static members can access only static data directly • Instance members can access both static and instance data Reason: Instance variables get memory only when an object is created, but static members execute during class loading. So static code cannot access something that doesn't yet exist in memory. 🧩 Introduction to Inheritance (2nd Pillar of OOP) Inheritance allows one class to acquire properties and behaviors of another class. Definition: Inheritance is the process where one class acquires the properties and behaviors of another class. Example: class Hacker extends BankAccount Here: • BankAccount → Parent / Superclass • Hacker → Child / Subclass ✔ Advantages of Inheritance • Code Reusability • Reduced development time • Less effort in building similar applications Real-world example: Many games reuse mechanics from earlier games, modifying only certain features instead of rebuilding everything. ✔ Important Rule Private members do NOT participate in inheritance Reason: Private data is protected by Encapsulation, and inheritance cannot violate that protection. ✔ First Type of Inheritance Single Inheritance Parent Class → Child Class Example: BankAccount → Hacker 💡 Biggest Takeaway Understanding static execution, memory behavior, and inheritance helps developers write code that is: Efficient Reusable Scalable These concepts form the foundation for advanced Java topics like polymorphism and abstraction. #Day32 #CoreJava #JavaOOP #StaticKeyword #Inheritance #JavaProgramming #DeveloperJourney #LearningJava
To view or add a comment, sign in
-
🏗️Constructors: The Blueprint of Object Creation in Java🏗️ I just wrapped up a focused quiz module on Constructors in Java, scoring 8.5 out of 9! ✅ Constructors are the gateway to object-oriented programming - they define how objects are born, initialized, and prepared for use. This deep dive reinforced that while constructors seem straightforward, mastering their nuances is essential for writing clean, maintainable code. Topics Explored: - Default Constructor - Understanding when the compiler provides one automatically (and when it doesn’t). - No-Argument Constructor - Explicitly defining constructors with no parameters for flexible object creation. - Parameterized Constructors - Injecting initial state directly at object instantiation, ensuring objects are created in a valid state. - "this" Keyword - Disambiguating between instance variables and constructor parameters (e.g., "this.name = name"). - "this()" Constructor Chaining - Calling one constructor from another to avoid code duplication and enforce mandatory initialization rules. The Mistakes made : I scored perfectly on most sections, but the half-point deduction came from one of the "Constructor in Java" questions (scored 0.5/1). These subtle deductions are always the most valuable - they highlight the edge cases and nuances that separate "it compiles" from "it's production-ready." In this case, it was likely a question about constructor inheritance, the rules of constructor chaining, or when the default constructor is *not* automatically provided. Why This Matters: Constructors are more than just syntax - they're your first line of defense for creating valid objects. Understanding them deeply helps you: - Ensure object integrity - Objects are never left in an partially initialized state. - Write DRY code - Reuse initialization logic via `this()` instead of duplicating it. - Avoid subtle bugs - Like accidentally losing the default constructor when adding a parameterized one, which can break framework expectations (e.g., JPA, Spring). If you're also revisiting Java fundamentals, I'd love to hear: What's the most surprising constructor behaviour you've encountered? Or a tricky constructor question that stumped you in an interview? Drop it in the comments! 👇 #Java #Constructors #ObjectOrientedProgramming #CleanCode #SoftwareEngineering #LearningJourney #CoreJava TAP Academy
To view or add a comment, sign in
-
-
Many people write Java code every day, but very few stop and think about how memory actually works behind the scenes. Understanding this makes debugging and writing efficient code much easier. Here’s a simple way to think about Java memory inside the JVM: 1. Heap Memory This is where all the objects live. Whenever we create an object using "new", the memory for that object is allocated in the heap. Example: "Student s = new Student();" The reference "s" is stored somewhere else, but the actual "Student" object is created inside the Heap. Heap memory is shared and managed by Garbage Collection, which automatically removes unused objects. 2. Stack Memory Stack memory is used for method execution. Every time a method runs, a new stack frame is created. This frame stores local variables and references to objects. When the method finishes, that stack frame is removed automatically. That’s why stack memory is fast and temporary. 3. Method Area (Class Area) This part stores class-level information such as: • Class metadata • Static variables • Method definitions • Runtime constant pool It is created once when the class is loaded by the ClassLoader. 4. Thread Area / Program Counter Each thread has its own program counter which keeps track of the current instruction being executed. It helps the JVM know exactly where the thread is in the program. In simple terms: Stack → Method execution Heap → Object storage Method Area → Class definitions Thread Area → Execution tracking Understanding this flow gives a much clearer picture of what really happens when a Java program runs. #Java #JVM #BackendDevelopment #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
🚀 Day 13— Restarting My Java Journey with Consistency Today's Learnings: 🔹 Instance Variables & Instance Methods These belong to objects and are accessed using the object reference. They help define the state and behavior of objects. 🔹 Local Variables Local variables do not get default values in Java. They must be initialized before use, otherwise the compiler throws an error. 🔹 Constructors in Java Constructors are special methods used to initialize objects at the time of creation. No return type Same name as class Example: Student s1 = new Student(); When an object is created, the constructor is automatically invoked to initialize the object. Types of constructors : • Default Constructor – No parameters • Parameterized Constructor – Accepts values to initialize object fields Important rule: If a programmer defines any constructor, Java does not create a default constructor automatically. 🔹 this Keyword this refers to the current object. It is commonly used to distinguish instance variables from local variables. 🔹 Constructor Overloading A class can have multiple constructors with different parameter lists to initialize objects in different ways. 🔹 Constructor Chaining Using this() we can call one constructor from another constructor within the same class. Important rule: The this() call must be the first statement inside a constructor. Interview Specific: 🔹 Can We Call a Constructor Manually? No. Constructors cannot be called like normal methods. They are automatically invoked when an object is created using the new keyword. 🔹 Interesting Runtime Insight When we create an object using new, Java allocates memory in the heap at runtime. But what if heap does not have enough free space, then Java will throw a runtime exception. Learning daily with Coder Army and Aditya Tandon Bhaiya and Rohit Negi Bhaiya #Day13 #Java #Consistency #BackendDevelopment #LearningJourney #SoftwareEngineering #CoderArmy
To view or add a comment, sign in
-
-
🚀 Understanding Escape Analysis in Java (and why it matters more than you think). Most Java developers assume that every object they create lives on the heap and adds pressure to the Garbage Collector. But the JVM is smarter than that. 👉 Enter Escape Analysis — a powerful JIT optimization that decides whether an object really needs to exist on the heap at all. 🧠 What is Escape Analysis? Escape Analysis determines if an object “escapes” the scope in which it was created. ✅ No Escape → Object stays within the method ⚠️ Method Escape → Object is returned or passed outside ❌ Thread Escape → Object is shared across threads ⚡ Why should you care? Because it unlocks major performance optimizations: 🔹 Stack Allocation - Objects that don’t escape may be allocated on the stack instead of the heap → faster + no GC overhead 🔹 Scalar Replacement - JVM may break objects into primitive fields → sometimes no object is created at all 🔹 Lock Elimination - Unnecessary synchronization can be removed when objects are thread-local 💡 Simple Example A small method using a temporary object: Point p = new Point(1, 2); return p.x + p.y; 👉 If p doesn’t escape, JVM may: Skip heap allocation Replace it with simple integers Result? Cleaner, faster execution behind the scenes. Escape Analysis is: ✔ Done at runtime by the JIT compiler ✔ Not guaranteed (depends on code patterns) ✔ More effective in simple, predictable logic 🧩 Why this matters in real systems In high-throughput applications: Reducing allocations = less GC pressure Less GC = better latency Better latency = happier users 🚀 🔍 Takeaway Not every object you write actually gets created. The JVM constantly optimizes your code in ways most developers never see. Understanding these internals helps you: ✔ Write better-performing code ✔ Debug performance issues ✔ Think beyond “just writing code” #Java #JVM #Performance #BackendEngineering #SystemDesign #Programming
To view or add a comment, sign in
-
🧠 If you truly understand Java variables, you understand Java memory. Most beginners memorize syntax. Strong developers understand scope + memory behavior. This simple distinction changes how you write clean, bug-free, scalable Java code 👇 🔹 Local Variables 📍 Live in stack memory 📍 Exist only within a method or block 📍 Fast, temporary, and short-lived 🔹 Instance Variables 📍 Stored in heap memory 📍 Declared inside a class, outside methods 📍 Every object gets its own copy 🔹 Static (Class) Variables 📍 Also stored in heap memory 📍 Declared using the static keyword 📍 One shared copy across all objects 📌 Why this matters in real projects: ✔ Better memory management ✔ Fewer unexpected bugs ✔ Cleaner object-oriented design ✔ Stronger interview fundamentals 💡 Java isn’t just about writing code. It’s about knowing where your data lives and how long it survives. 💬 Which concept confused you most when learning Java — local vs instance or instance vs static? Drop it in the comments 👇 Let’s learn together. #Java #CoreJava #JavaDeveloper #Programming #SoftwareEngineering #ComputerScience #CodingBasics #LearnJava #DeveloperCommunity #TechEducation #CleanCode #MemoryManagement
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Great share.