🚀 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
Java Static Concept Explained
More Relevant Posts
-
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
-
-
Day 21 – Accessing Non-Static Members of a Class in Java Yesterday I explored static members in Java. Today’s concept was the opposite side of it: 👉 Non-Static Members (Instance Members) Unlike static members, non-static members belong to objects, not the class itself. That means we must create an object of the class to access them. 🔹 Syntax new ClassName().memberName; or ClassName obj = new ClassName(); obj.memberName; 🔹 Example class Demo4 { int x = 100; int y = 200; void test() { System.out.println("running test() method"); } } class MainClass2 { public static void main(String[] args) { System.out.println("x = " + new Demo4().x); System.out.println("y = " + new Demo4().y); new Demo4().test(); } } Output x = 100 y = 200 running test() method 🔹 Important Observation Every time we write: new Demo4() ➡️ A new object is created. Each object has its own copy of non-static variables. This is why instance variables are object-specific, unlike static variables which are shared across objects. 📌 Key takeaway • Static members → belong to the class • Non-static members → belong to objects • Accessing instance members requires object creation Understanding this concept is essential for mastering Object-Oriented Programming in Java. Step by step building stronger Core Java fundamentals. #Java #CoreJava #JavaFullStack #OOP #Programming #BackendDevelopment #LearningInPublic #SoftwareDevelopment
To view or add a comment, sign in
-
-
Day 38 - 🚀 Understanding toString() in Java In Java, the toString() method is used to return a string representation of an object. It belongs to the Object class, which means every Java class inherits it by default. 📌 Default Behavior If you don't override toString(), Java prints a combination of class name + hashcode. class Person { String name; int age; } Person p = new Person(); System.out.println(p); Output: Person@1a2b3c This output is usually not very useful for users or developers. 📌 Overriding toString() To display meaningful object information, we override the toString() method. class Person { String name; int age; @Override public String toString() { return "Person[name=" + name + ", age=" + age + "]"; } } Output: Person[name=John, age=25] 📌 Why toString() is Important ✔ Provides a human-readable representation of objects ✔ Useful for debugging and logging ✔ Makes object data easier to print and understand 💡 Pro Tip Always use the @Override annotation when implementing toString() to ensure the method is correctly overridden. ✅ Conclusion The toString() method helps convert an object into a clear and readable string format, making debugging and displaying data much easier in Java applications. #Java #OOP #JavaProgramming #ToString #ProgrammingConcepts #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 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 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 12 – Wrapper Classes in Java ⏳ 1 Minute Java Clarity – Converting primitives into objects Primitive data types are fast… But sometimes, Java needs objects instead of primitives 📌 What are Wrapper Classes? Wrapper classes convert primitive types into objects. Ex: int → Integer char → Character double → Double Ex: int num = 10; Integer obj = Integer.valueOf(num); // primitive → object int value = obj.intValue(); // object → primitive System.out.println(obj); 👉 Output: 10 ✅ 📌 Why do we need Wrapper Classes? ✔ Required for Collections (like ArrayList) ✔ Useful for utility methods ✔ Helps in object manipulation 📌 Autoboxing & Unboxing 🔹 Autoboxing → primitive → object Integer a = 10; 🔹 Unboxing → object → primitive int b = a; 💡 Quick Summary ✔ Wrapper classes = primitive → object ✔ Autoboxing makes conversion automatic ✔ Widely used in real-world Java programs 🔹 Next Topic → String Immutability in Java Have you used Wrapper Classes in your projects? 👇 #Java #JavaProgramming #WrapperClasses #CoreJava #JavaDeveloper #BackendDeveloper #Programming #Coding #SoftwareEngineering #LearningInPublic #100DaysOfCode #TechCommunity #ProgrammingTips #1MinuteJavaClarity
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
-
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
-
-
📌 Lambda Expressions in Java — Writing Cleaner Code Lambda expressions allow writing concise and readable code by replacing anonymous classes. They are built on functional interfaces. 1️⃣ What Is a Lambda Expression? A lambda is an anonymous function: • No name • No return type declaration • Shorter syntax Syntax: (parameters) -> expression --- 2️⃣ Traditional vs Lambda Before Java 8: Runnable r = new Runnable() { public void run() { System.out.println("Hello"); } }; With Lambda: Runnable r = () -> System.out.println("Hello"); --- 3️⃣ Syntax Variations • No parameter: () -> System.out.println("Hi") • One parameter: x -> x * 2 • Multiple parameters: (a, b) -> a + b • Multi-line: (a, b) -> { int sum = a + b; return sum; } --- 4️⃣ Why Lambda Is Powerful ✔ Reduces boilerplate code ✔ Improves readability ✔ Enables functional programming ✔ Works seamlessly with Streams --- 5️⃣ Where Lambdas Are Used • Collections (sorting, filtering) • Streams API • Multithreading (Runnable, Callable) • Event handling Example: list.forEach(x -> System.out.println(x)); --- 6️⃣ Important Rule Lambda works only with: ✔ Functional Interfaces (single abstract method) --- 🧠 Key Takeaway Lambda expressions simplify code by focusing on *what to do*, not *how to implement it*. They are the foundation of modern Java programming. #Java #Java8 #Lambda #FunctionalProgramming #BackendDevelopment
To view or add a comment, sign in
-
📌 Method References in Java — Cleaner Than Lambdas Method references provide a concise way to refer to existing methods using lambda-like syntax. They improve readability when a lambda simply calls an existing method. 1️⃣ What Is a Method Reference? Instead of writing a lambda: x -> System.out.println(x) We can write: System.out::println --- 2️⃣ Syntax ClassName::methodName Used when: • Lambda just calls an existing method • No additional logic is required --- 3️⃣ Types of Method References 🔹 Static Method Reference ClassName::staticMethod Example: Integer::parseInt --- 🔹 Instance Method Reference (of object) object::instanceMethod Example: System.out::println --- 🔹 Instance Method Reference (of class) ClassName::instanceMethod Example: String::length --- 🔹 Constructor Reference ClassName::new Example: ArrayList::new --- 4️⃣ Example Comparison Using Lambda: list.forEach(x -> System.out.println(x)); Using Method Reference: list.forEach(System.out::println); --- 5️⃣ Benefits ✔ More readable code ✔ Less boilerplate ✔ Cleaner functional style ✔ Works seamlessly with Streams --- 🧠 Key Takeaway Method references are a shorthand for lambda expressions that call existing methods. Use them when they improve clarity, not just to shorten code. #Java #Java8 #MethodReference #FunctionalProgramming #BackendDevelopment
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