Java Variables & Memory Management with JVM

📘 Java Learning Journey — Day 13: Variables & Memory Management Today, I learned about variables and how Java manages memory at runtime. A variable is a memory location used to store values and manipulate data in a program. Every variable is associated with a specific data type, which defines the type of data it can hold. 🔹 Types of Variables in Java 1️⃣ Local Variables Declared inside a method or block Accessible only within that method or block No default values are assigned Memory is allocated in the Stack Segment Memory is deallocated automatically when the method or block execution ends 2️⃣ Instance Variables Declared inside a class, outside any method Accessible throughout the class using object reference Default values are provided by JVM Memory is allocated in the Heap Segment Exists as long as the object exists 🔹 Java Runtime Memory Structure (JRE) When a Java program runs, RAM allocates memory called the Java Runtime Environment (JRE). It consists of four major segments: Code Segment – Stores compiled machine-level (bytecode) instructions Static Segment – Stores static members Stack Segment – Stores local variables and object references Heap Segment – Stores objects and instance variables 🔹 Object Creation & Memory Allocation When execution starts from the main method: Objects are created using the new keyword The object is stored in the Heap Segment The reference variable is stored in the Stack Segment Example: Demo d = new Demo(); Here, new instructs the JVM to create an object in heap memory, while d holds the reference in stack memory. 🚀 This session helped me clearly understand variable scope, lifetime, and JVM memory allocation, which are crucial for writing efficient and optimized Java programs. #Java #CoreJava #Variables #JVM #MemoryManagement #LearningJourney #SoftwareDevelopment

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories