<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohamed Eid on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Eid on Medium]]></description>
        <link>https://medium.com/@3eid?source=rss-9352a1d79d72------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z4Tbzb6GfjpyM5urfG4WWg.png</url>
            <title>Stories by Mohamed Eid on Medium</title>
            <link>https://medium.com/@3eid?source=rss-9352a1d79d72------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:02:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@3eid/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reference Type in Java: Memory Allocation, Storage, Assignment, and Passing by Value]]></title>
            <link>https://medium.com/@3eid/reference-type-in-java-allocation-storage-explanation-assignment-and-passing-by-value-c6252ca53b86?source=rss-9352a1d79d72------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6252ca53b86</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mohamed Eid]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 12:30:54 GMT</pubDate>
            <atom:updated>2024-10-31T13:45:17.428Z</atom:updated>
            <content:encoded><![CDATA[<p>Java’s memory model makes a clear distinction between primitive and reference types, a distinction that shapes everything from variable storage to parameter passing and assignment behavior. In this article, we’ll explore the details of reference types in Java, how they’re allocated and stored, and how Java’s memory model affects assignment and parameter passing.</p><h3>Table of Contents</h3><ol><li><strong>Introduction to Primitive vs. Reference Types</strong></li><li><strong>Memory Allocation and Storage of Primitive and Reference Types</strong></li><li><strong>Storage Cases for Reference Types</strong></li><li><strong>Pass-by-Value and Pass-by-Reference in Java</strong></li><li><strong>Assignment Behavior with Reference Types</strong></li><li><strong>Comparison: Reference Types vs. Pointers</strong></li><li><strong>Conclusion</strong></li></ol><h3><strong>1. Introduction to Primitive vs. Reference Types</strong></h3><p>Java data types are divided into two categories: <strong>Primitive Types</strong> and <strong>Reference Types</strong>.</p><h4><strong>a. Primitive Types:</strong></h4><p>These store basic, atomic values directly.<br>Examples include int, double, boolean, char, etc.<br>Each primitive type has a fixed size:</p><ul><li>int: 4 bytes</li><li>double: 8 bytes</li><li>char: 2 bytes (for UTF-16 characters)</li><li>boolean: 1 bit</li></ul><h4><strong>b. Reference Type</strong>:</h4><p>These don’t store data directly; instead, they store an8-byte identifier This identifier refers to the location of an object stored in the heap, a special memory area managed by the JVM for dynamic memory.</p><p>This distinction in data types leads to differences in how Java handles memory, parameter passing, and assignment operations. Let’s look at how each type is stored in memory.</p><p><strong>Reference types have a dual storage structure:</strong></p><ol><li>The <strong>reference variable</strong> (the 8-byte identifier) is stored in either the <strong>stack</strong> (if it’s local variable) or the <strong>heap</strong> ( if it’s an instance variable)</li><li>The <strong>object</strong> itself<strong> </strong>stored in the <strong>heap</strong>, where the JVM manages.</li></ol><h3>2. Memory Allocation and Storage of Primitive and Reference Types</h3><p>Java stores variables in two main memory locations: the <strong>stack</strong> and the <strong>heap</strong>.</p><p><strong>Stack Memory</strong>: This area holds primitive values and references (the 8-byte identifiers). The size of each type is fixed:</p><ul><li>int: 4 bytes</li><li>double: 8 bytes</li><li>char: 2 bytes</li><li>Reference: 8 bytes (identifier)</li><li>etc…</li></ul><p><strong>Heap Memory</strong>: This area holds complex objects such as arrays, strings, and instances of classes.</p><p>The following code snippet illustrates how primitive and reference types are stored:</p><pre>class DataHolder {<br>    int primitiveValue;          // Primitive Instance variable, It will be stored in the object in the heap when object is instantiated)<br>    String referenceValue;       // Reference Instance variable, It will be stored in the object in the heap when object is instantiated), pointing to a String in the heap.<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        int primitive = 10;      // stored in the stack (primitive type local variable)<br>        DataHolder holder = new DataHolder(); // &#39;holder&#39; reference stored in stack pointing to a DataHolder object in heap<br>        holder.primitiveValue = 42;  // primitive instance variable stored in the object in heap<br>        holder.referenceValue = &quot;Hello World&quot;; // Reference Instance variable Points to a String object in heap<br>    }<br>}</pre><p>In this example:</p><ul><li>primitive is a 4-byte integer stored directly in the stack.</li><li>holder is an 8-byte reference stored in the stack, referring to a DataHolder object in the heap.</li><li>The primitiveValue is stored within the DataHolder object in the heap.</li><li>The referenceValue holds an 8-byte identifier that points to a String object, also in the heap.</li></ul><figure><img alt="Memory illustration for the code above" src="https://cdn-images-1.medium.com/max/567/1*YX_W-mMnw9g7UMcfyBWraA.png" /></figure><p><strong>Note: You can expand your knowledge about java memory management, heap, and stack from </strong><a href="https://medium.com/@3eid/deep-dive-into-java-memory-management-heap-stack-metaspace-and-garbage-collection-df6548fe6860"><strong>this article</strong></a><strong>.</strong></p><h3>3. Storage Cases for Reference Types</h3><p>In Java, there are two main scenarios for storing reference variables:</p><p><strong>a. Local Variable in a Function Call Frame</strong>: When a reference type is declared as a local variable within a method, it’s stored on the stack. It holds the 8-byte identifier that refers to an object in the heap.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        String localReference = &quot;Hello&quot;; // &#39;localReference&#39; is in stack, points to String &quot;Hello&quot; in heap<br>    }<br>}</pre><p>Here, localReference is stored in the stack and contains an identifier pointing to the &quot;Hello&quot; string object in the heap.</p><p><strong>b. Instance Variable within an Object in the Heap</strong>: If a reference is an instance variable within an object, both the reference and the object are stored in the heap. However, the reference still holds an 8-byte identifier pointing to another object in the heap.</p><pre>class Book {<br>    String title; // &#39;title&#39; reference within the Book object in heap<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Book book = new Book();   // &#39;book&#39; reference in stack, object in heap<br>        book.title = &quot;Java Programming&quot;; // &#39;title&#39; is a reference within the Book object<br>    }<br>}</pre><p>In this example:</p><ul><li>The book reference is stored in the stack.</li><li>ABook object is stored in the heap, and within it, title holds an 8-byte identifier pointing to a String object in the heap.</li></ul><h3>4. Pass-by-Value and Pass-by-Reference in Java</h3><p>Java uses <strong>pass-by-value</strong> exclusively, even for reference types, which often leads to confusion.</p><p>When passing arguments to methods’ parameters, It may be:</p><ul><li><strong>Primitives</strong>: A copy of the primitive value is passed.</li><li><strong>Reference Types</strong>: A copy of the 8-byte reference is passed, meaning the method receives a reference to the same object. So both the reference variable passed and the method parameter will be pointing to the same object.</li></ul><p><strong>Example:</strong></p><pre>class Person {<br>    String name;<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Person person = new Person();<br>        person.name = &quot;John&quot;;<br>        <br>        modifyPerson(person);<br>        System.out.println(person.name); // Outputs: &quot;Alice&quot; (name changed)<br>        <br>        reassignReference(person);<br>        System.out.println(person.name); // Outputs: &quot;Alice&quot; (original reference unchanged)<br>    }<br><br>    public static void modifyPerson(Person p) {<br>        p.name = &quot;Alice&quot;; // Modifies the original object&#39;s property<br>    }<br><br>    public static void reassignReference(Person p) {<br>        p = new Person(); // Only local reference &#39;p&#39; is changed, not the original<br>        p.name = &quot;Bob&quot;;<br>    }<br>}</pre><ul><li>The modifyPerson method changes the name property on the same object.</li><li>The reassignReference method creates a new different Person object, make the local p reference variable points to that new object, changes the name property on the newobject, this reassignment does not affect the original person reference outside the method.</li></ul><h3>5. Assignment Behavior with Reference Types</h3><p>Assignment behavior differs across objects, strings, arrays, and other reference types:</p><ul><li><strong>Objects</strong>: Assigning one object reference to another results in both references pointing to the same object.</li><li><strong>Strings</strong>: Strings are immutable, meaning that assigning a new string value creates a new object rather than modifying the original.</li><li><strong>Arrays</strong>: Like other objects, arrays are mutable and share references when assigned, allowing changes in one reference to affect all references.</li></ul><p><strong>Example of Each:</strong></p><pre>// Objects<br>Person personA = new Person();<br>Person personB = personA; // Both personA and personB refer to the same object<br><br>// Strings (Immutable)<br>String str1 = &quot;Hello&quot;;<br>String str2 = str1;   // both str1 and str2 pointing to the same &quot;hello&quot; object<br>str1 = &quot;World&quot;; // str1 now pointing to a new string object &quot;World&quot;, but str2 still points to &quot;Hello&quot;<br><br>// Arrays (Mutable)<br>int[] array1 = {1, 2, 3};<br>int[] array2 = array1;<br>array1[0] = 10;<br>System.out.println(array2[0]); // Outputs: 10 (shared array reference)</pre><h3>6. Comparison: Reference Types vs. Pointers</h3><p>Though reference types in Java are sometimes compared to pointers, they differ fundamentally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HcLmniiV55cpIRIxrzJZdQ.png" /></figure><p>In Java, the JVM manages references as abstract identifiers that allow for garbage collection and prevent accidental access to invalid memory.</p><h3>7. Conclusion</h3><p>Understanding Java’s reference types is essential for managing memory effectively and avoiding common bugs like unintended shared references. By knowing how Java’s memory model works, developers can optimize code for better performance and minimize runtime errors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6252ca53b86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Java Memory Management: Heap, Stack, Metaspace, and Garbage Collection]]></title>
            <link>https://medium.com/@3eid/deep-dive-into-java-memory-management-heap-stack-metaspace-and-garbage-collection-df6548fe6860?source=rss-9352a1d79d72------2</link>
            <guid isPermaLink="false">https://medium.com/p/df6548fe6860</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Mohamed Eid]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 10:42:13 GMT</pubDate>
            <atom:updated>2024-10-31T13:41:12.924Z</atom:updated>
            <content:encoded><![CDATA[<p>Java’s memory management model is a critical part of the Java Virtual Machine (JVM) and can make or break application performance. From managing dynamic allocation on the heap to organizing method calls in the stack, and tracking metadata in the Metaspace, each area has a distinct role in ensuring efficient memory usage. This guide will take a deep dive into these areas, with examples and notes to clarify concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*2VTlsH_KZt6dNPoP.png" /></figure><h3>Overview of Java Memory Areas</h3><p>Java’s memory model divides memory into several key areas:</p><ul><li><strong>Heap</strong>: The primary area for dynamic memory allocation, storing objects and instance variables.</li><li><strong>Stack</strong>: Manages method execution, including method call frames and local variables.</li><li><strong>Metaspace</strong>: Stores metadata for class structures, static data, and constants (replacing PermGen in Java 8).</li></ul><p>Let’s explore each of these areas in detail.</p><h3>1. Stack</h3><p>The <strong>Stack</strong> is crucial for managing <strong>method execution</strong>, storing method call frames, local variables, and references to objects in the heap. Each thread has its own stack, providing thread isolation and supporting concurrent execution.</p><p><strong>Note: You can expand your knowledge about Java reference type from </strong><a href="https://medium.com/@3eid/reference-type-in-java-allocation-storage-explanation-assignment-and-passing-by-value-c6252ca53b86?source=user_profile_page---------0-------------9352a1d79d72---------------"><strong>this article</strong></a><strong>.</strong></p><h3>Characteristics of the Stack</h3><ul><li><strong>Local Variables and References</strong>: Local variables are stored in the stack. Here’s an example:</li></ul><pre>public class Main {<br>    public void methodA() {<br>        int x = 5; // Stored in the stack<br>        Car myCar = new Car(); // Reference is in the stack; object is in the heap<br>    }<br>}</pre><p><strong>. LIFO Memory Management</strong>: The stack follows a Last-In-First-Out (LIFO) approach. Each method call adds a stack frame, and the frame is removed when the method completes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*lM3m0q4_FGlSKjhCbmu7Xg.png" /></figure><h4>Important Notes:</h4><ul><li><strong>StackOverflowError</strong>: If the stack exceeds its allocated space (e.g., due to infinite recursion), a StackOverflowError occurs (ex: infinite recursion).</li><li><strong>Performance</strong>: Stack access is faster than heap access due to its simple structure, requiring no garbage collection.</li></ul><h3>2. Heap</h3><p>The <strong>Heap</strong> is the main memory pool for dynamic allocation in Java, storing all objects created during runtime. Java’s automatic garbage collection handles memory cleanup when objects are no longer referenced, making the heap essential for long-term storage.</p><h4>Characteristics of the Heap:</h4><ul><li><strong>Instance Variables and Object Allocation</strong>: When you create an object using new, it’s allocated on the heap. For example:</li></ul><pre>class Car {<br>    public String color;<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        new Car();         // Anew Car object Allocated on the heap, but its reference is not preserved! (not accesible/referenced) Garbage collection eligible): <br>        Car myCar;         // Reference type Varaiable (allocated on the stack) (pointing to null)<br>        myCar = new Car(); // New Car object Allocated on the heap and its reference stored on myCar on the stack.<br>        mycar.color = &quot;Black&quot;; // New String object allocated in heap and its reference is stored in instance reference variabl color of the object<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*5cL1gnfSKtrLoB3T-HPUfQ.png" /></figure><ul><li><strong>Garbage Collection</strong>: Once objects lose references (e.g., after a variable goes out of scope), they become eligible for garbage collection.</li></ul><h3>Important Notes:</h3><ul><li><strong>OutOfMemoryError</strong>: When the heap is full and cannot allocate new memory, Java throws an OutOfMemoryError.</li><li><strong>Access</strong>: Heap is Shared across all threads and accessible to every method call frame.</li></ul><h3>Example: Stack vs. Heap Storage</h3><pre>public class Example {<br>    public void stackExample() {<br>        int num = 10; // Stored in the stack<br>        String text = &quot;Hello&quot;; // Reference is in the stack, but &quot;Hello&quot; (object of class String) is in Heap (in the string pool area)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*qxYiBn9sc8H7SN1WuGCgqg.png" /></figure><h3>3. Metaspace (Method Area / Class Area)</h3><p>The <strong>Metaspace</strong> stores metadata about loaded classes and methods, such as field information, method names, and constants. Metaspace offers flexible memory allocation for class metadata.</p><h3>Characteristics of Metaspace</h3><ul><li><strong>Class Metadata</strong>: Metaspace stores class structures, including field and method information.</li><li><strong>Constant Pool</strong>: Stores constant values like method names and literals.</li><li><strong>Static Variables</strong>: Houses class-level static variables and constant data. For example:</li></ul><pre>class Example {<br>    static int count = 0; // Stored in Metaspace<br>}</pre><h4>Garbage Collection of Metaspace</h4><p>Unused classes can be unloaded and their memory reclaimed by the JVM when they are no longer referenced. This is especially important for applications that load and unload many classes dynamically.</p><h3>Garbage Collection (GC)</h3><p>Garbage Collection is an automatic memory management process that frees memory occupied by unreferenced objects. In Java, GC operates through a combination of minor and major collection cycles.</p><h3>Phases of Garbage Collection</h3><ol><li><strong>Marking</strong>: Identifies all live objects that are still referenced.</li><li><strong>Copying/Compacting</strong>: Moves live objects to reduce fragmentation and organize memory efficiently.</li><li><strong>Sweeping</strong>: Reclaims memory used by dead objects.</li></ol><h3>Example: Manual GC Hint</h3><p>While Java GC is automatic, you can <strong>request</strong> a garbage collection cycle using System.gc(), though this is just a suggestion to the JVM.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        Car myCar = new Car();<br>        myCar = null; // Eligible for GC<br>        System.gc();  // Request GC<br>    }<br>}</pre><blockquote><strong><em>Note</em></strong><em>: </em><em>System.gc() does not guarantee immediate garbage collection. It merely suggests it to the JVM.</em></blockquote><h3>Comparing Heap, Stack, and Metaspace</h3><p>Here’s a comparison to summarize the roles of each memory area:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*90mtZ4bFetNdZ7gFllUmrw.png" /></figure><h3>Conclusion</h3><p>Java memory management is a powerful, automated system that optimizes memory use by dividing memory into specialized areas, each tailored for specific tasks. Understanding the heap, stack, and metaspace, along with the workings of garbage collection, is essential for building efficient and performant Java applications. By using these areas effectively, Java ensures robust and scalable memory management, making it one of the most dependable programming languages for large-scale applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df6548fe6860" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>