Skip to content

Commit

Permalink
Reference types article
Browse files Browse the repository at this point in the history
  • Loading branch information
Luci-MG committed Dec 31, 2024
1 parent 7cb3804 commit 4831d35
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 35 deletions.
58 changes: 24 additions & 34 deletions docs/langdives/Java/ReferenceTypesInDepth.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
# **Reference Types In Depth.**

Let's deep dive to understand How memory management, object references, and behaviors work in Java, with a focus on **String handling** and other reference types like **arrays, classes, and wrapper objects**.
Let's deep dive to understand How memory management, object references, and behaviors work in Java in this article, with a focus on String handling and other reference types like arrays, classes, and wrapper objects.

---

## **Intro**
- **Primitive types** store values directly in **stack memory**.
- **Reference types** store **references (addresses)** to objects located in **heap memory**.
- When you assign a reference type (e.g., `String` or an array), **only the reference (address)** is copied, not the actual data. This means **multiple references can point to the same object**.

---
Primitive types store values directly in stack memory Where as Reference types store references (addresses) to objects located in heap memory, When you assign a reference type (e.g., `String` or an array), only the reference (address) is copied, not the actual data. This means multiple references can point to the same object.


## **String**
The **`String`** class in Java is a special reference type with some unique behaviors. Strings are **immutable** once a `String` object is created, it cannot be changed. Any modification on a `String` results in the creation of a **new object** in memory.
The **`String`** class in Java is a special reference type with some unique behaviors. Strings are immutable once a `String` object is created, it cannot be changed. Any modification on a `String` results in the creation of a new object in memory.

**String Pool (Interned Strings)**:
A special memory area inside the heap used to store string literals. If a string literal like `"Hello"` is created, Java first checks the string pool to see if it already exists. If it does, it returns the reference from the pool. If not, the string is added to the pool.
### **String Pool (Interned Strings)**
A special memory area inside the heap used to store string literals. If a string literal like `"Hello"` is created, Java first checks the string pool to see if it already exists. If it does, it returns the reference from the pool. If not, the string is added to the pool.

???+ example
```java
Expand All @@ -25,7 +22,7 @@ The **`String`** class in Java is a special reference type with some unique beha
System.out.println(s1 == s2); // true (same reference)
```

**Heap Memory**:
### **Heap Memory**
When you use the `new` keyword, a new `String` object is always created in the heap memory. Even if the same string already exists in the string pool, the `new` keyword forces the creation of a separate instance in the heap.

???+ example
Expand All @@ -38,7 +35,6 @@ When you use the `new` keyword, a new `String` object is always created in the h
```
When you use `new String()`, Java forces the creation of a new object in heap even if the same string exists in the pool.

---

## **Arrays**
Arrays are reference types, meaning the array variable stores a reference to the memory location where the array data is stored.
Expand All @@ -53,12 +49,11 @@ Arrays are reference types, meaning the array variable stores a reference to the
System.out.println(arr1[0]); // Output: 10 (both arr1 and arr2 reference the same array)
```

**How Array References Work:**
**How Array References Work:**

- `arr1` and `arr2` point to the same memory location in the heap.
- If you change the array via `arr2`, the change will reflect in `arr1` because both refer to the same object.
- `arr1` and `arr2` point to the same memory location in the heap.
- If you change the array via `arr2`, the change will reflect in `arr1` because both refer to the same object.

---

## **Classes and Objects**
When you create an object using `new`, the reference variable points to the object in heap memory.
Expand All @@ -78,15 +73,14 @@ When you create an object using `new`, the reference variable points to the obje
System.out.println(p1.name); // Output: Bob (both references point to the same object)
```

**How References Work with Objects:**
**How References Work with Objects:**

- `p1` and `p2` point to the **same Person object**. Changing the object via `p2` affects `p1`.
- This is how **shallow copies** work only the reference is copied, not the object itself.
- `p1` and `p2` point to the same Person object. Changing the object via `p2` affects `p1`.
- This is how shallow copies work, only the reference is copied, not the object itself.

---

## **Wrapper Classes**
Wrapper classes (`Integer`, `Double`, `Boolean`, etc.) wrap primitive types into objects. These are reference types, and Java performs **autoboxing/unboxing** to convert between primitive types and wrapper objects.
Wrapper classes (`Integer`, `Double`, `Boolean`, etc.) wrap primitive types into objects. These are reference types, and Java performs autoboxing/unboxing to convert between primitive types and wrapper objects.

???+ example
```java
Expand All @@ -103,14 +97,13 @@ Wrapper classes (`Integer`, `Double`, `Boolean`, etc.) wrap primitive types into

**Wrapper Caching**

- Java caches `Integer` objects in the **range -128 to 127** for performance.
- Beyond this range, **new objects** are created.
- Java caches `Integer` objects in the range -128 to 127 for performance.
- Beyond this range, new objects are created.

---

## **Reference and Deep Copy**

**Shallow Copy**: Copies only the **reference**, so both variables refer to the same object.
**Shallow Copy**: Copies only the reference, so both variables refer to the same object.
???+ example
```java
int[] original = {1, 2, 3};
Expand All @@ -120,7 +113,7 @@ Wrapper classes (`Integer`, `Double`, `Boolean`, etc.) wrap primitive types into
System.out.println(original[0]); // Output: 100
```

**Deep Copy**: Creates a **new object** with the same data.
**Deep Copy**: Creates a new object with the same data.
???+ example
```java
int[] original = {1, 2, 3};
Expand All @@ -130,40 +123,37 @@ Wrapper classes (`Integer`, `Double`, `Boolean`, etc.) wrap primitive types into
System.out.println(original[0]); // Output: 1
```

---

## **Null/`NullPointerException`**
When a reference is **not initialized**, it holds the value **`null`**. Accessing a field or method on a **`null` reference** throws a **`NullPointerException`**.
When a reference is not initialized, it holds the value `null`. Accessing a field or method on a `null` reference throws a `NullPointerException`.

???+ example
```java
Person p = null;
System.out.println(p.name); // Throws NullPointerException
```

---

## **Garbage Collection**
Java uses **Garbage Collection** to manage memory. When no references point to an object, it becomes **eligible for garbage collection**.
Java uses Garbage Collection to manage memory. When no references point to an object, it becomes eligible for garbage collection.

???+ example
```java
Person p1 = new Person(); // Object created
p1 = null; // Now eligible for garbage collection
```

---
We will learn about garbage collection more in depth in another article.


## **Summary**

- **Strings**: Immutable, stored in the **String Pool** if created with literals. `new String()` creates a separate object.
- **Strings**: Immutable, stored in the String Pool if created with literals. `new String()` creates a separate object.
- **Arrays**: Reference types, so multiple variables can point to the same array object.
- **Classes**: Objects are referenced in memory; multiple references can point to the same object.
- **Classes**: Objects are referenced in memory multiple references can point to same object.
- **Wrapper Classes**: Use caching for certain ranges (e.g., `Integer` values from -128 to 127).
- **Garbage Collection**: Objects are eligible for garbage collection when no active references point to them.

---


## **String Pool In Depth**

Expand Down
2 changes: 1 addition & 1 deletion mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ nav:
- 4 Pillars: langdives/Java/4Pillars.md
- Access modifiers: langdives/Java/AccessModifPPPPP.md
- Keywords/Terminologies: langdives/Java/KeyWordsTerminolgies.md
- Primitives References: langdives/Java/PrimitiveReferenceTypes.md
- Primitives & References: langdives/Java/PrimitiveReferenceTypes.md
- Reference Types Indepth: langdives/Java/ReferenceTypesInDepth.md
- Pass By Value: langdives/Java/JavaPassBy.md # TODO:: need to edit this title
- Collections JCF: langdives/Java/Collections-JCF.md
Expand Down

0 comments on commit 4831d35

Please sign in to comment.