🚀 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
Java Execution Flow: Class Loader, JRE Internals, and Static vs Instance
More Relevant Posts
-
🚀 Day 31 – Core Java | Understanding Static Variables & Memory Optimization Today’s session focused on one important question: Why do we actually need static variables in Java? To understand this, we explored how Java programs execute in memory and how improper design can waste a large amount of memory in real-world applications. 🔑 Key Concepts Learned ✔ Java Execution Environment A Java program runs inside the JRE, which contains: Code Segment Stack Segment Heap Segment Static Segment (Method Area / Metaspace) ✔ Execution Flow of a Java Program Class is loaded into memory Static variables are initialized Static block executes main() method runs Objects are created in the Heap Instance variables get memory Constructor executes Instance methods run ✔ Static vs Instance Variables Instance Variable - Belongs to an object Memory allocated every time an object is created Static Variable - Belongs to the class Memory allocated only once during class loading ✔ Real-World Example (Bank Loan System) We built a simple application to calculate Simple Interest. Formula: SI = (P × T × R) / 100 Where: P → Principal amount (user input) T → Time / Tenure (user input) R → Rate of Interest (fixed by bank) Key observation: If R is an instance variable, every object stores its own copy → memory waste. Solution: static float R = 15.2f; Now only one copy exists for the entire class, saving memory even if millions of users access the application. ✔ Important Takeaway Static variables are used for efficient memory utilization when a value must remain common for all objects. Examples: Bank interest rate Mathematical constants (PI) Configuration values ✔ Static Block Static blocks are used to initialize static variables during class loading. Example: static { R = 15.2f; } 💡 Biggest Insight Good developers don’t just write code that works. They write code that is: Memory efficient Scalable Production ready Understanding concepts like static variables and memory behavior is what separates a beginner from a real Java developer. #Day31 #CoreJava #JavaMemory #StaticKeyword #JVM #JavaInternals #DeveloperLearning #JavaProgramming
To view or add a comment, sign in
-
🚀 Day 41 – Core Java | Interfaces & Pure Abstraction Today’s session introduced one of the most important concepts in Java — Interfaces, and how they help achieve pure abstraction and standardization in software development. 🔹 Why Interfaces Were Introduced In early Java development, different database vendors created their own driver implementations with different method names. Example: getConnection() startConnection() establishConnection() Although all performed the same operation, the inconsistent method names forced developers to rewrite code whenever the database changed. To solve this problem, Java introduced Interfaces. Interfaces act as a standard contract, ensuring that all implementations follow the same method structure. 🔹 What is an Interface? An interface is a collection of pure abstract methods. Example: interface Calculator { void add(); void sub(); } Key idea: Interface methods contain only method signatures The implementation is provided by classes 🔹 Implementing an Interface Classes implement interfaces using the implements keyword. class MyCalculator implements Calculator { public void add() { System.out.println("Addition logic"); } public void sub() { System.out.println("Subtraction logic"); } } Here the class promises to provide the implementation for all abstract methods. 🔹 Important Interface Rules 1️⃣ Interfaces Provide Standardization Interfaces act like a contract ensuring that all classes follow the same method structure. 2️⃣ Interfaces Promote Polymorphism Using an interface reference, we can point to objects of implementing classes. Example: Calculator ref = new MyCalculator(); This enables loose coupling, code flexibility, and reduced redundancy. 3️⃣ Interface Methods Are Public Abstract by Default Even if we don’t write them explicitly: void add(); Java internally treats it as: public abstract void add(); 4️⃣ Interface Reference Cannot Access Specialized Methods Methods defined only in the implementing class cannot be accessed using interface reference. They can be accessed only through downcasting. 🔹 Key Takeaway Interfaces help achieve: ✔ Pure Abstraction ✔ Standardization of method names ✔ Loose coupling in applications ✔ Flexible and maintainable code Understanding interfaces is essential because they are widely used in frameworks, APIs, and enterprise Java development. #CoreJava #JavaInterfaces #Abstraction #Polymorphism #JavaOOP #JavaLearning #DeveloperJourney #InterviewPreparation
To view or add a comment, sign in
-
🚀 Java Revision Journey – Day 13 Today I revised two important Java concepts that help in understanding how Java programs execute and how modern Java makes code cleaner and more expressive. 📝Method Call Stack in Exceptions The Method Call Stack in Java manages method execution during runtime. Whenever a method is called, Java creates a stack frame and pushes it onto the call stack. When the method finishes execution, the frame is removed. 📌 When an exception occurs, Java starts searching upward through the call stack to find a matching catch block. If no matching handler is found, the program terminates and a stack trace is printed. This concept helps developers to: Understand exception propagation Identify where the exception originated Debug runtime errors using stack trace information Understanding the call stack is essential for diagnosing issues and writing reliable Java applications. 💻 Java Method References I also revised Method References, a feature introduced in Java 8 that provides a cleaner and shorter alternative to lambda expressions. A method reference allows referring to an existing method without executing it, using the :: operator. It improves readability and reduces boilerplate code when a lambda simply calls an existing method. 📍 Types of Method References in Java 1️⃣ Reference to a Static Method ClassName::staticMethodName 2️⃣ Reference to an Instance Method of a Particular Object objectReference::instanceMethod 3️⃣ Reference to an Instance Method of an Arbitrary Object ClassName::instanceMethod 4️⃣ Reference to a Constructor ClassName::new 🔖 Method References and Functional Interfaces Method references work only with Functional Interfaces (interfaces with exactly one abstract method). Important points: Method signature must match the functional interface method Common functional interfaces include Consumer, Supplier, Function, and Predicate Frequently used with Streams and Collections API 📌 Learning concepts like Exception Call Stack and Method References helps in understanding how Java works internally while also writing cleaner, more modern Java code. Step by step, continuing to strengthen my Java fundamentals and deepening my understanding of the language. #Java #JavaLearning #JavaDeveloper #Java8 #MethodReference #ExceptionHandling #OOP #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
Day 45: Organizing the Architecture – Mastering Java Packages 🏗️📦 As my Java projects grow in complexity, staying organized is no longer optional—it’s a necessity. Day 45 of my Full Stack journey was a deep dive into Packages, the namespaces that keep our code modular, readable, and conflict-free. Here is the Day 45 breakdown of "Smart Organization": 1. What is a Package? 🧐 In Java, a package is a container used to group related classes, interfaces, and sub-packages. Think of it like a folder system on your computer that prevents naming conflicts (e.g., having two classes named User in different modules). 2. The 3 Types of Packages 📂 I explored how Java categorizes code based on its source: ▫️ Predefined Packages: Built-in libraries provided by the Java API (e.g., java.util, java.lang, java.io). ▫️ User-Defined Packages: Custom packages created by the developer to organize project-specific logic (e.g., com.narendra.app.service). ▫️ Third-Party Packages: External libraries added to the project to extend functionality (e.g., Hibernate, Spring, or Apache Commons). 3. Four Ways to Access Packages 🔑 I practiced the different techniques to bring classes into scope: ▫️ Single Class Import: Importing only what you need (import java.util.ArrayList;). Best for memory efficiency and clarity. ▫️ Wildcard Import: Importing everything in a package (import java.util.*;). Fast, but can lead to naming "shadowing." ▫️ Fully Qualified Name: Using the complete path directly in the code (java.util.Scanner sc = new ...). No import needed, but it makes code verbose. ▫️ Static Import: Accessing static members (fields/methods) without the class name (import static java.lang.Math.*;). Great for mathematical constants or utility methods. Next up: Access Modifiers and Encapsulation! 🚀 #JavaFullStack #100DaysOfCode #BackendDevelopment #SoftwareArchitecture #CleanCode #JavaProgramming 10000 Coders Meghana M
To view or add a comment, sign in
-
Unspring? I’m currently "unspringing" parts of a Java project ( admittedly, not a huge one ), moving from framework-managed beans to explicit constructor injection. Architecture matters to me. I'm a big believer in explicitly showing dependencies, even at the price of some more manual work. The Comparison: Spring vs. Explicit The Spring Way The container handles the lifecycle and wiring behind the scenes using annotations. Java Sample Code @Configuration public class CoffeeConfig { @Bean public Coffee beans() { return new Coffee("Arabica"); } @Bean public EspressoMachine machine(Coffee beans) { return new EspressoMachine(beans); } } The Explicit Way By reducing the framework footprint, you regain full control over instantiation and visibility. Java Sample Code: public class Main { public static void main(String[] args) { // Explicit wiring: No magic, just Java Coffee beans = new Coffee("Arabica"); EspressoMachine machine = new EspressoMachine(beans); machine.brew(); } } Pros and Cons of Unspringing Pros * Fast Startup & Testing: Pure Java tests and apps start instantly without waiting for classpath scanning or @SpringBootTest context loading. * Total Transparency: Explicit dependencies are easier to understand, debug. "Go to Definition" replaces runtime break points. * Fail-Fast Design: Catch wiring errors and circular dependencies at compile time rather than at runtime. * More modular code - relying on spring may lead some developers to lazily injecting a large number of singleton dependencies into a class. Cons * Interface Pollution: Constructors can become "dirty" or bloated when passing objects through multiple layers. * Increased Boilerplate: Manual "glue code" for instantiation grows as the project scales. * Manual Management: You lose automated features like @Transactional (though not used in this project) and other AOP-based magic. Note: I’m not removing Spring entirely, but I am significantly reducing its role in dependency injection to favor more predictable, standard Java. #java #spring #di #dependencyinjection #architecture #softwaredesign #cleancode #dependencies
To view or add a comment, sign in
-
-
Understanding the Java "main()" Method — "public static void main(String[] args)" Every Java program starts execution from the main() method. When you run a Java program, the JVM (Java Virtual Machine) looks for this method as the entry point. If a program does not contain a valid "main()" method, the JVM will not start execution. The commonly used syntax is: public static void main(String[] args) Each word in this declaration has a specific purpose: • public → Access modifier that allows the JVM to call the method from outside the class. If it is not public, the JVM cannot access it. • static → Allows the method to be called without creating an object of the class. The JVM can directly invoke the method when the program starts. • void → Specifies that the method does not return any value. Once the main method finishes execution, the Java program terminates. • main → The method name recognized by the JVM as the starting point of the program. Changing this name prevents the program from running. • String[] args → An array that stores command-line arguments passed when running the program. Example: class Example { public static void main(String[] args) { System.out.println("Hello, Java!"); } } Java also allows equivalent forms like: public static void main(String args[]) public static void main(String... args) All of these work because the parameter is still treated as a String array. Key Takeaway: The "main()" method acts as the entry point of a Java application, allowing the JVM to begin executing the program. #Java #JavaProgramming #CoreJava #JVM #BackendDevelopment #Programming #LearnToCode
To view or add a comment, sign in
-
-
*Fail-Fast vs Fail-Safe Iterators in Java Ever encountered a ConcurrentModificationException and wondered why? Here's the reason. When working with Java collections, iterators allow us to traverse elements. However, modifying a collection during iteration leads to different behavior depending on the iterator type. 1] Fail-Fast Iterator Fail-fast iterators throw a ConcurrentModificationException if the collection is structurally modified during iteration (except through the iterator itself). They track changes using an internal modification count (modCount). Example: List<String> list = new ArrayList<>(List.of("A", "B", "C")); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String value = iterator .next(); list.add("D"); // Causes ConcurrentModificationException } -> Detects bugs early -> Prevents unpredictable behavior -> Used by: ArrayList, HashMap, HashSet 2] Fail-Safe Iterator Fail-safe iterators operate on a snapshot (copy) of the collection rather than the original structure. This allows modifications during iteration without throwing exceptions. Example: CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(List.of("A", "B")); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String value = iterator .next(); list.add("C"); // No exception } -> Safe in concurrent environments -> No ConcurrentModificationException > Used by: CopyOnWriteArrayList, ConcurrentHashMap Understanding this difference helps write safer and more predictable Java code. #Java #JavaCollections #BackendDevelopment #JavaDeveloper #Programming
To view or add a comment, sign in
-
📌 Fail-Fast vs Fail-Safe Iterators in Java (A Concept Many Ignore) While working with Java collections, there’s a small concept that many developers overlook: 👉 Fail-Fast vs Fail-Safe Iterators But this concept can save you from real production bugs. 🧠 What is a Fail-Fast Iterator? Fail-Fast iterators immediately throw an exception if the collection is modified during iteration. Example: List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); for (Integer i : list) { list.add(3); // ❌ Modification during iteration } 👉 This throws: ConcurrentModificationException 🔎 Why Does This Happen? Fail-Fast iterators track a variable called: 👉 modCount If the collection is modified during iteration, the iterator detects it and throws an exception. Fail-Safe Iterator? Fail-Safe iterators do NOT throw exceptions. Instead, they work on a copy of the collection. Example: CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>(); list.add(1); list.add(2); for (Integer i : list) { list.add(3); // ✅ No exception } 🎯 When Should You Care? - While iterating collections - While modifying lists in loops - While debugging ConcurrentModificationException - While writing multi-threaded code Follow for more Java concepts, interview questions, and system design insights. #Java #Collections #SoftwareEngineering #JavaDeveloper #Programming
To view or add a comment, sign in
-
-
✨🪄 Day 42 of 90 – Java Backend Development 🔥☄️ The Java Virtual Machine (JVM) is the invisible engine that allows Java applications to run on any device or operating system without modification. Acting as a crucial abstraction layer between compiled Java code and the underlying hardware, it fulfills the famous "Write Once, Run Anywhere" (WORA) promise. When you compile a Java program, it isn't turned into machine-specific code; instead, it becomes bytecode, which the JVM then interprets or compiles on-the-fly into instructions the local processor understands. Beyond just execution, the JVM is a sophisticated environment that manages memory automatically through Garbage Collection, optimizes performance via Just-In-Time (JIT) compilation, and enforces strict security boundaries, making it one of the most robust and widely used runtime environments in modern computing. 👉 Key responsibilities of the JVM i)Loading Code: Uses Class Loaders to pull in the necessary files. ii)Verifying Code: Ensures the bytecode doesn't violate security or structural constraints. iii)Executing Code: Converts bytecode into native machine code. iv)Memory Management: Allocates space for objects and automatically cleans up unused memory. 👉 How Java program runs? i)You write code → Hello.java ii)Compiler converts it → Hello.class (bytecode) iii)JVM loads the class iv)JVM verifies the bytecode v)Execution Engine runs it vi)Output is produced. 👉 Main components of JVM 👉 Class Loader Subsystem i)Loads .class files into memory ii)Performs: Loading Linking Initialization 👉 Runtime data areas (Memory Areas) JVM divides memory into: Heap → Stores objects Stack → Stores method calls & local variables Method Area → Stores class metadata, static variables PC Register → Keeps track of current instruction Native Method Stack → For native methods (like C/C++) 👉 Execution engine Executes bytecode Contains: Interpreter → Line-by-line execution JIT (Just-In-Time) Compiler → Converts bytecode into native machine code for faster performance 👉 Garbage Collector (GC) Automatically deletes unused objects from Heap Prevents memory leaks No manual memory management (unlike C/C++) #JVM #Compiler #Interepter #JavaEnvironment
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
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