Understanding Execution Flow and Constructors in Java Today I explored how Java executes static blocks, instance blocks, and constructors when objects are created. Key concepts I practiced: 1--> Static Block Runs only once when the class is loaded. It always prints before anything else in the class. 2--> Instance Block Executes every time an object is created, and it runs before the constructor. Useful when multiple constructors share common initialization logic. 3--> Default & Parameterized Constructors The default constructor initializes objects without arguments The parameterized constructor allows passing custom values By printing messages in each block, I clearly understood Java’s execution order: -->Static block -->Static method -->Instance block -->Constructor -->Other methods Attaching the console output below for clarity. Thanks Prasoon Bidua Sir for the guidance and support in understanding core fundamentals. #Java #Constructors #OOP #ExecutionFlow #CoreJava #LearningInPublic
Java Execution Flow: Static Blocks, Instance Blocks, and Constructors
More Relevant Posts
-
Variables in Java — From Code to Memory 🧠☕ In Java, a variable is more than just a name holding a value. It defines how data is stored, accessed, and managed inside the JVM. Here’s a simple breakdown 👇 🔹 Local Variables Declared inside methods or blocks Stored in Stack memory Created when a method is called, removed when it ends No default values 🔹 Instance Variables Declared inside a class (outside methods) Belong to an object Stored in Heap memory Each object has its own copy 🔹 Static Variables Declared using static Belong to the class, not objects Stored in Method Area (MetaSpace) Single shared copy across all objects How Memory Works Behind the Scenes ⚙️ 🟦 Stack Memory Stores local variables and method calls Works in LIFO order Fast and thread-safe 🟧 Heap Memory Stores objects and instance variables Shared across threads Managed by Garbage Collection 🟨 Reference Variables Stored in Stack Point to objects in Heap Why This Matters ❓ Understanding variables helps you: ✔ Write efficient code ✔ Avoid memory leaks ✔ Debug faster ✔ Perform better in interviews Strong fundamentals build strong developers 🚀 #Java #CoreJava #JVM #JavaBasics #MemoryManagement #SoftwareEngineering #Programming #LearningJourney
To view or add a comment, sign in
-
-
📘 Architecture Of Java This diagram shows how a Java program runs step by step and why Java is fast, safe, and platform-independent. 🔹 1. Java Source Code We write our program in a .java file. 🔹 2. Compilation The Java compiler converts the source code into bytecode (.class file). ➡️ Bytecode can run on any system. 🔹 3. Java Virtual Machine (JVM) The JVM is the heart of Java: Loads classes using the Class Loader Manages memory using Garbage Collection Handles errors and supports multithreading 🔹 4. JIT Compiler The Just-In-Time (JIT) Compiler converts frequently used bytecode into machine code while the program is running. 🔹 5. Native Machine Code Finally, the CPU executes the code faster, improving performance. ✨ In simple words: Java uses the JVM and JIT to make programs portable, reliable, and fast.
To view or add a comment, sign in
-
-
⚡Static Methods in Interfaces Before Java 8, helper/utility logic lived in separate utility classes: Collections, Arrays, Math They didn’t belong to objects — they belonged to the concept itself. Java later allowed static methods inside interfaces so the behavior can live exactly where it logically belongs. 👉 Now the interface can hold both the contract and its related helper operations. 🧠 What Static Methods in Interfaces Mean A static method inside an interface: Belongs to the interface itself Not inherited by implementing classes Called using interface name only No object needed. No utility class needed. 🎯 Why They Exist ✔ Removes unnecessary utility classes The operation belongs to the type, not to instances. 🔑 Static vs Default Default → inherited behavior, object can use/override it Static → helper behavior, called using interface name only, not inherited 💡 Interfaces now contain: Contract + Optional Behavior(default) + Helper Logic(static) Use static when the behavior must stay fixed for the interface/class itself cant be overridden. Use default when you want a common behavior but still allow children to override it or just use the parent default implementation. Default methods exist only for interfaces (to evolve them without breaking implementations). In abstract classes you simply write a normal concrete method — no default keyword needed. GitHub link: https://lnkd.in/esEDrfPy 🔖Frontlines EduTech (FLM) #Java #CoreJava #Interfaces #DefaultMethods #StaticMethods #OOP #BackendDevelopment #Programming #CleanCode #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs
To view or add a comment, sign in
-
-
🚀Java practice - Day 87 Completed! 👍 Problem: Sum of Squares of Special Elements Language: Java Today’s problem was about identifying special elements in a 1-indexed array. An element is considered special if its index divides the length of the array (n % i == 0). The task was to calculate the sum of the squares of such elements.✨ #Day87 #Java #LeetCode #Arrays #ProblemSolving #DailyCoding #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
🔹 Today I learned about Strings in Java • A String is a sequence of characters enclosed in double quotes. • In Java, Strings are objects used to store and manipulate text. 🔹 Types of Strings • Immutable Strings – Once created, their value cannot be changed Examples: name, date of birth, gender • Mutable Strings – Their value can be changed Examples: password, email, months of the year 🔹 Ways to Create Strings • Using new keyword → String s1 = new String("java"); • Without new keyword → String s2 = "java"; 🔹 Memory Allocation (Heap Segment) • String Constant Pool (SCP) – Does not allow duplicate values – Strings created without new are stored here • Heap Area – Allows duplicate objects – Strings created with new are stored in the heap 🔹 Ways to Compare Strings • == → Compares references (memory locations) • equals() → Compares values • compareTo() → Compares strings character by character • equalsIgnoreCase() → Compares values ignoring case differences #TapAcademy #Java #JavaProgramming #LearningJava #StringConcept #ProgrammingBasics #CodingJourney #TechLearning
To view or add a comment, sign in
-
-
📌 start() vs run() in Java Threads Understanding the difference between start() and run() is essential when working with threads in Java. 1️⃣ run() Method • Contains the task logic • Calling run() directly does NOT create a new thread • Executes like a normal method on the current thread Example: Thread t = new Thread(task); t.run(); // no new thread created 2️⃣ start() Method • Creates a new thread • Invokes run() internally • Execution happens asynchronously Example: Thread t = new Thread(task); t.start(); // new thread created 3️⃣ Execution Difference Calling run(): • Same call stack • Sequential execution • No concurrency Calling start(): • New call stack • Concurrent execution • JVM manages scheduling 4️⃣ Common Mistake Calling run() instead of start() results in single-threaded execution, even though Thread is used. 🧠 Key Takeaway • run() defines the task • start() starts a new thread Always use start() to achieve true multithreading. #Java #Multithreading #Concurrency #CoreJava #BackendDevelopment
To view or add a comment, sign in
-
Today I revisited an important Core Java concept :- Variable Shadowing. Shadowing happens when a constructor parameter has the same name as a class member variable. Example of the problem: private String name; public Employee(String name) { name = name; // Shadow problem } Here, both sides refer to the constructor parameter. The instance variable never gets assigned. Result: The object prints default values like null or 0.0. Correct way using this: public Employee(String name) { this.name = name; // Proper assignment } this refers to the current object’s instance variable. Key takeaway: Without this, constructor parameters can hide instance variables. With this, we clearly differentiate between object state and local scope. A small keyword, but critical for proper object initialization. Strong OOP fundamentals prevent subtle bugs in real systems. #Java #CoreJava #OOP #Encapsulation #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
The Significance of Overriding toString() in Java: -toString() provides a String representation of an object and is used to convert an object to a String. -Every meaningful object representation in Java ultimately depends on toString(). -If standard library classes override it to maintain clarity and structure, custom classes should follow the same principle. -Every class in Java automatically inherits the toString() method from the Object class. -Overriding toString() is not just a method override. It is a design responsibility. Grateful to my mentor Anand Kumar Buddarapu for consistently guiding me to understand concepts beyond theory and apply them practically. #Java #OOP #ObjectOrientedProgramming #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
-
🚀 Container With Most Water | Java | Two Pointer Approach I solved the “Container With Most Water” problem using an optimized Two Pointer technique in Java. The goal is to find two lines that together with the x-axis form a container, such that the container holds the maximum amount of water. 🧠 Approach: Start with two pointers at both ends of the array. Calculate the width between them. The height is determined by the smaller of the two values. Update the maximum area. Move the pointer pointing to the smaller height inward. This greedy strategy works because the area depends on both width and minimum height, and moving the smaller height gives a chance to find a larger area. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Practicing DSA problems daily to improve logical thinking and optimization skills. #Java #DSA #TwoPointer #ProblemSolving #CodingJourney #LeetCode #DataStructures
To view or add a comment, sign in
-
-
🚀ARRAYS IN JAVA As I dive deeper into Java, I’m realizing that even the fundamentals have some hidden gems. Most of us start with the standard Array, but have you played around with Jagged Arrays? So , Hi LinkedIn 👋 Here’s the breakdown of first time experience: We usually visualize a 2D array like a spreadsheet—every row has the exact same number of columns. It’s clean, it’s structured, but it’s rigid. 💡 The Fascinating Fact: Java’s "Array of Arrays" Here is the eye-opener: In Java, a multi-dimensional array isn't a single block of memory. It is actually an array that holds other arrays. Because of this architecture, Java allows for Jagged Arrays—where every row can have a completely different length. 🤯 🛠️ how it matters?? 🤔 Memory Efficiency Real-World Logic Dynamic Thinking and more... It’s these small nuances that make Java so flexible and powerful. To my fellow developers: did you use jagged arrays in your early projects? #Java #CodingNewbie #SoftwareEngineering #DataStructures #BackendDevelopment #TechLearning 💻 See it in action 👇
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