Static vs Instance in Java – Execution Flow Made Simple One of the most important concepts in Java is understanding the difference between static members and instance members — and how the execution flow actually works. Let’s break it down ✅ Class-Level Members (Static) 1.Static Variable 2.Static Block 3.Static Method 🔹 These belong to the class, not the object. 🔹 They are loaded only once when the class is loaded into memory. 🔹 Static members can be accessed by both static and instance methods. ✅ Object-Level Members (Instance) 1.Instance Variable 2.Instance Block 3.Instance Method 4.Constructor Instance Method 🔹 These belong to the object. 🔹 They are created every time a new object is created. 🔹 Instance members can be accessed only through an object. 🔹 Execution Flow in Java Understanding execution order is very important for interviews. 🚀 Step 1: Program Starts Execution begins from the main() method. 📌 Step 2: Class Loading When a class loads: 1️⃣ Static variables initialize 2️⃣ Static block executes 3️⃣ Static methods can be called This happens only once per class. If multiple classes are involved, each class will load separately and execute its own static variables and static blocks. 📌 Step 3: Object Creation When we create an object: 1️⃣ Instance variables initialize 2️⃣ Instance block executes 3️⃣ Constructor executes 4️⃣ Then instance methods run 💡 Important: The instance block runs before the constructor. 🔹 Quick Summary ✔ Static → Belongs to Class ✔ Instance → Belongs to Object ✔ Class loads → Static executes ✔ Object created → Instance block → Constructor → Methods Mastering this concept makes your Java fundamentals strong and helps you confidently answer interview questions. TAP Academy #Java #OOPS #Programming #Developers #CodingJourney
Java Static vs Instance Members: Execution Flow Explained
More Relevant Posts
-
Understanding Future vs CompletableFuture in Java When working with concurrent programming in Java, we often need to execute tasks asynchronously so the main thread does not get blocked. Two important concepts used for this are Future and CompletableFuture. 🔹 What is Future? Future represents the result of an asynchronous computation. It allows a task to run in another thread and returns the result once the computation is completed. Example: ExecutorService executor = Executors.newFixedThreadPool(2); Future<String> future = executor.submit(() -> { Thread.sleep(2000); return "Task Completed"; }); String result = future.get(); System.out.println(result); In this example: • The task runs in a separate thread • Future holds the result of that task Limitations of Future Future has some important limitations: • "get()" blocks the thread until the result is available • Cannot chain multiple asynchronous tasks • Hard to combine multiple Futures together Because of these limitations, Java introduced CompletableFuture in Java 8. 🔹 What is CompletableFuture? CompletableFuture is an enhanced version of Future that supports non-blocking asynchronous programming. It allows us to: • Chain multiple asynchronous tasks • Combine multiple results • Handle exceptions easily Example: CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { return "Processing Completed"; }); future.thenAccept(result -> { System.out.println(result); }); Here: • The task runs asynchronously • Once completed, the result is processed automatically • The main thread does not block 🔹 Why CompletableFuture is powerful • Supports functional programming style • Enables parallel task execution • Improves performance in backend systems 🔹 Real-world use cases In Spring Boot microservices, CompletableFuture can be used for: • Calling multiple APIs in parallel • Processing background tasks • Improving REST API response time Understanding asynchronous programming concepts like Future and CompletableFuture helps developers build scalable and high-performance backend systems. #Java #SpringBoot #Microservices #JavaConcurrency #BackendDevelopment
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 47 – Java 2026: Smart, Stable & Still the Future Static Initializer in Java (ClassLoader & Memory Explained) A static initializer block in Java is used to initialize static variables. It executes only once when the class is loaded into memory by the JVM ClassLoader, before any object is created. It is useful when initialization requires logic or multiple statements, not just a direct assignment. class Example { static int number; static { System.out.println("Static block executed"); number = 50; } public static void main(String[] args) { System.out.println("Main method started"); System.out.println("Number: " + number); } } Output Static block executed Main method started Number: 50 How it Works in JVM When a Java program runs, the JVM loads classes using the ClassLoader in three steps: Loading – .class file is loaded into JVM memory (Method Area). Linking – JVM verifies the class and allocates memory for static variables. Initialization – static variables and static blocks execute. Memory Structure Method Area Class metadata Static variables Static blocks Heap Objects created using new Stack Method execution frames Static members are stored in the Method Area because they belong to the class, not to objects. Key Point A static initializer runs only once during class loading, ensuring efficient one-time setup such as configuration loading, driver initialization, or cache preparation. #Java #JavaDeveloper #JVM #ClassLoader #BackendDevelopment #Programming#100series
To view or add a comment, sign in
-
🚀 Java Revision Journey – Day 10 Today I revised the concepts of Abstract Classes and Interfaces in Java and how they help achieve abstraction and flexible application design. 🔖 Abstract Class and Abstract Method: An abstract class is a class that cannot be instantiated and is used to provide partial abstraction. It can contain both abstract methods (without implementation) and concrete methods (with implementation). Abstract methods must be implemented by subclasses. 🔖 Interface: An interface defines a contract for classes by specifying method declarations. It mainly provides abstraction for behavior and allows classes to implement multiple interfaces. Interfaces can also contain default and static methods. 🔖 Abstract Class vs Interface: Abstract classes provide partial abstraction, while interfaces are mainly used to achieve a higher level of abstraction for behavior definition. 🔖Multiple Inheritance through Interface: Java does not support multiple inheritance using classes to avoid complexity. However, a class can implement multiple interfaces, allowing multiple inheritance in a structured way. 🔖Hybrid Inheritance through Interface: Hybrid inheritance is a combination of two or more types of inheritance. In Java, this can be achieved using interfaces. 🔖Diamond Problem and Code Ambiguity: Multiple inheritance using classes can create ambiguity, known as the diamond problem. Java avoids this by not allowing multiple inheritance with classes. Interfaces solve this problem with clear implementation rules. 🔖Loose Coupling vs Tight Coupling: Interfaces help achieve loose coupling, where components depend on abstractions rather than concrete implementations. This makes applications easier to maintain and extend. 💻 Understanding these concepts is essential for designing scalable, maintainable, and well-structured Java applications. Continuing to strengthen my Java fundamentals step by step. #Java #JavaLearning #JavaDeveloper #OOP #BackendDevelopment #Programming #JavaRevisionJourney
To view or add a comment, sign in
-
-
Day 10 | Full Stack Development with Java Today’s focus was on one of the most important building blocks in Java — Methods. Understanding methods helped me clearly see how Java programs are structured and executed. What is a Method? In Java, a method is a block of code that performs a specific task inside a class. Method Syntax: returnType methodName(parameters) { // method body } methodName → Name of the method parameters → Inputs passed to the method returnType → Value returned after execution method body → Code that performs the task Types of Methods in Java I learned that there are 4 types: 1️⃣ No Input, No Output No parameters No return value Example: prints result directly 2️⃣ No Input, With Output No parameters Returns a value 3️⃣ With Input, No Output Takes parameters Does not return anything 4️⃣ With Input, With Output Takes parameters Returns a value This classification made method behavior very clear. Memory Understanding (Stack vs Heap) While calling methods: Stack Segment Stores method calls Creates stack frames Stores local variables Heap Segment Stores objects Stores instance variables When a method is called: A stack frame is created. Parameters and local variables go into stack. Objects created using new go into heap. After method execution, control returns to the caller. Main Method Java Copy code public static void main(String[] args) Entry point of Java program Called by JVM Accepts command-line arguments Does not return any value (void) Key Takeaway Methods are the foundation of: Code reusability Modular programming Clean architecture Understanding how methods interact with memory (Stack & Heap) is helping me think like a backend developer. 10 days of consistency. Building Java fundamentals step by step. #Day10 #Java #Methods #FullStackDevelopment #BackendDevelopment #LearningInPublic #ProgrammingJourney
To view or add a comment, sign in
-
-
🚀 Java Series – Day 18 📌 Serialization in Java (Why Serializable is a Marker Interface?) 🔹 What is it? Serialization is the process of converting a Java object into a byte stream so it can be stored in a file or transferred over a network. The reverse process is called Deserialization. Java uses the Serializable interface to enable serialization. 🔹 Why do we use it? Serialization is useful when we want to save object state or send objects across systems. For example: In a banking or login system, user session data can be serialized and stored, then later restored when needed. 🔹 Why is Serializable a Marker Interface? A marker interface is an empty interface (no methods) that signals the JVM to perform special behavior. "Serializable" does not contain any methods. It simply tells the JVM: 👉 “This object is allowed to be converted into a byte stream.” If a class does not implement "Serializable", Java will throw a NotSerializableException. 🔹 Example: import java.io.*; class Student implements Serializable { int id; String name; Student(int id, String name) { this.id = id; this.name = name; } } public class Main { public static void main(String[] args) throws Exception { Student s = new Student(1, "Raushan"); // Serialization ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.txt")); out.writeObject(s); out.close(); System.out.println("Object Serialized"); } } 💡 Key Takeaway: "Serializable" is a marker interface that enables object serialization without defining any methods. What do you think about this? 👇 #Java #Serialization #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Java Series – Day 21 📌 Inner Classes in Java (Static vs Non-Static) 🔹 What is it? An Inner Class is a class defined inside another class. Java provides different types of inner classes: • Member Inner Class (Non-static) • Static Nested Class • Local Inner Class (inside method) • Anonymous Inner Class 🔹 Why do we use it? Inner classes help in logical grouping of classes and improve code readability & encapsulation. For example: In a banking system, a "Bank" class can contain an inner class "Account" to tightly couple related logic. 🔹 Static vs Non-Static Inner Class: • Non-Static Inner Class (Member Inner Class) - Requires outer class object - Can access all members of outer class - Used when inner class depends on outer class • Static Inner Class (Static Nested Class) - Does NOT require outer class object - Can access only static members of outer class - Used for utility/helper classes 🔹 Example: class Outer { int x = 10; static int y = 20; // Non-static inner class class Inner { void display() { System.out.println("x = " + x); // can access all } } // Static inner class static class StaticInner { void display() { System.out.println("y = " + y); // only static access } } } public class Main { public static void main(String[] args) { // Non-static inner class Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); inner.display(); // Static inner class Outer.StaticInner obj = new Outer.StaticInner(); obj.display(); } } 💡 Key Takeaway: Use non-static inner classes when tightly coupled with outer class, and static inner classes for independent utility behavior. What do you think about this? 👇 #Java #InnerClass #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Java Revision Journey – Day 14 Today I revised Exception Handling in Java, an essential concept for writing stable and error-free applications. 📝 Exception Handling Overview Exception Handling is used to manage runtime errors so that the program doesn’t crash and continues its normal flow. It helps in handling unexpected situations effectively. 📌 Java Exception Hierarchy All exceptions and errors are derived from the Throwable class, which has two main branches: Exception: An event that occurs during program execution which can be handled to prevent program termination. Error: A serious problem that occurs during execution which cannot be handled by the application and usually causes program failure. 📍 Types of Exceptions 1️⃣ Built-in Exceptions Checked Exceptions → Checked at compile time, must be handled Unchecked Exceptions → Occur at runtime, handling is optional 2️⃣ User-Defined Exceptions Custom exceptions created by the programmer 💻 Exception Handling Keywords try → Code that may cause exception catch → Handles the exception finally → Always executes (used for closing resources) 📌 Printing Exception Info printStackTrace() → Full error details toString() → Exception name + description getMessage() → Only description 🔁 throw vs throws throw → Used to explicitly throw an exception throws → Declares exceptions that a method may throw ⚙️ Flow of try-catch JVM executes try block If exception occurs → jumps to matching catch Then executes finally block If no catch → handled by JVM default handler 📌 Important Note finally may not execute in rare cases like System.exit(), JVM crash, or infinite loop. 💡 Understanding exception handling helps in building robust, maintainable, and production-ready Java applications. Continuing to strengthen my Java fundamentals step by step 💪 #Java #JavaLearning #ExceptionHandling #JavaDeveloper #OOP #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
📘 Why Does Java Allow the `$` Symbol in Identifiers? While learning about Java identifiers, I noticed something interesting. Unlike many programming languages, **Java allows the `$` symbol in identifier names.** Example: ```java int $value = 100; int total$amount = 500; ``` But this raises an interesting question: 👉 Why was `$` added to Java identifiers in the first place? 🔹 The historical reason When Java was designed in the 1990s, the language architects included `$` mainly for internal use by Java compilers and tools. The Java compiler often generates special class names automatically. For example, when you create an inner class, the compiled class file often uses `$` in its name: ``` OuterClass$InnerClass.class ``` Here, `$` helps represent the relationship between the outer class and the inner class. 🔹 Use in frameworks and generated code Many frameworks, libraries, and code generation tools also use `$` internally to create unique identifiers without conflicting with normal developer-defined names. 🔹 Should developers use `$` in identifiers? Technically, it is allowed. However, Java naming conventions discourage its use in normal code. The `$` symbol is generally reserved for: • Compiler-generated classes • Framework-generated code • Internal tooling 🔹 Key takeaway Sometimes language features exist not for everyday developers, but to support the ecosystem of compilers, frameworks, and tools that power the language. The `$` symbol in Java identifiers is one such design choice. #Java #Programming #SoftwareDevelopment #Coding #ComputerScience #LearnInPublic
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
-
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