0% found this document useful (0 votes)
8 views8 pages

What Is Garbage Collection in Java

Garbage Collection in Java is an automatic process that deletes unused objects to free up memory, preventing slowdowns or crashes in applications. It works by marking objects for collection when they are no longer needed, and the Garbage Collector (GC) removes them, with the finalize() method providing a last chance to clean up resources. Wrapper classes in Java are object representations of primitive data types, allowing for easier manipulation and storage in collections, while arrays are fixed-size collections of elements of the same type, enabling efficient data management.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

What Is Garbage Collection in Java

Garbage Collection in Java is an automatic process that deletes unused objects to free up memory, preventing slowdowns or crashes in applications. It works by marking objects for collection when they are no longer needed, and the Garbage Collector (GC) removes them, with the finalize() method providing a last chance to clean up resources. Wrapper classes in Java are object representations of primitive data types, allowing for easier manipulation and storage in collections, while arrays are fixed-size collections of elements of the same type, enabling efficient data management.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is Garbage Collection in Java?

Garbage Collection (GC) is the process by which Java automatically deletes objects that are
no longer used to free up memory.

You don’t need to manually delete objects like in C/C++ — Java does it for you!

✅ Why is it needed?

When your program creates many objects (e.g., with new), they use memory (RAM). If unused
objects stay in memory, it can slow down or crash your app. Garbage collection cleans up
those unused objects.

✅ How does it work?

1. You create an object:

String name = new String("Alice");

2. When the object is no longer needed (e.g., you don’t use name anymore), Java marks it for
garbage collection.

3. The Garbage Collector (GC) finds and deletes such objects to free up memory.

Example:

public class Example {

public static void main(String[] args) {

Example obj = new Example(); // Object created

obj = null; // Now it's not used anymore

[Link](); // Suggests Java to run GC (optional)

}
@Override

protected void finalize() {

[Link]("Garbage collected!");

 [Link]() is just a request, not a command.

 The JVM decides when to actually run the GC.

 Java uses algorithms like Mark and Sweep internally.

finalize()

finalize() is a method that gets called by the Garbage Collector (GC) just before an object
is removed (deleted) from memory.

Think of it as a "goodbye" method for the object — it's your last chance to clean up resources
(like closing files or network connections) before the object disappears.

Example:

public class MyClass {

@Override

protected void finalize() throws Throwable {

[Link]("Object is being garbage collected.");

public static void main(String[] args) {

MyClass obj = new MyClass();

obj = null; // Now the object is eligible for GC

[Link](); // Request garbage collection


}

Output

Object is being garbage collected.

Why not to use finalize()?

 It's unpredictable — you don't know when or if it will run.


 It can cause performance problems.
 Java 9+ has deprecated finalize() (it's being removed in future versions).

@Override

This is an annotation that tells Java:

"Hey, I'm overriding a method from the parent class."

In this case, the method being overridden is finalize() — which is inherited from the Object
class (the parent of all Java classes).

� protected void finalize() throws Throwable {

This is the method definition.

Explanation:

Part Meaning
Only this class and its subclasses (and package members) can access this
protected method. It must match the access level of the original method from Object
class.
void This method returns nothing.
finalize()
The method that the Garbage Collector may call before the object is removed
from memory.
throws This means the method might throw any kind of exception (error). Throwable is
Throwable the top of Java’s error hierarchy.
[Link]("Object is being garbage collected.");

This line just prints a message to the console when (or if) finalize() is called. It lets you know
the object is being cleaned up.

What Are Wrapper Classes in Java?

In Java, wrapper classes are object representations of primitive data types like int, char,
boolean, etc.

Java has 8 primitive data types:

 byte, short, int, long, float, double, char, boolean

These are not objects — they are simple, fast, and memory-efficient. But sometimes, you need
to treat data as objects, especially when working with collections or using features that require
objects.

That’s where wrapper classes come in. They “wrap” the primitive data types into objects.

Primitive Types and Their Wrapper Classes

Primitive Type Wrapper Class


byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
All wrapper classes are located in the [Link] package and are immutable (their values cannot be
changed once created).

Why Do We Need Wrapper Classes?

Here are common reasons wrapper classes are used:

1. Working with Collections (like ArrayList)


Java's collections framework (like ArrayList, HashMap) can only store objects, not primitive
types.

✅ This won’t work:

ArrayList<int> list = new ArrayList<>(); // ❌ Error

This will work:

ArrayList<Integer> list = new ArrayList<>();

[Link](10); // Autoboxed from int to Integer

Use of Utility Methods

Wrapper classes come with built-in utility methods. For example:

int num = [Link]("123"); // Convert String to int

String s = [Link](3.14); // Convert double to String

These methods make it easy to convert between types or get useful information (like MAX_VALUE,
MIN_VALUE).

Nullability

A primitive variable cannot be null:

int x = null; // ❌ Error

But a wrapper object can:

Integer x = null; // ❌ Allowed

This is useful when you need to represent missing data, like in databases or APIs.
Object-Oriented Features

Sometimes you need primitives to behave like objects:

 To pass them to methods expecting objects


 For use in generic types
 To store in data structures
 To synchronize on them (thread-safe programming)

Integer

This is the wrapper class for the primitive type int. It contains utility methods for working
with integers — like converting Strings to ints.

parseInt("123")

This is a static method of the Integer class. It takes a String as input, and if the string
contains a valid number, it converts it into an int.

[Link]("123")

Examples:
public class TestParse {

public static void main(String[] args) {

String str = "123";

int num = [Link](str);

[Link](num + 10); // Output: 133

Here, we:

1. Take the string "123",


2. Convert it to int → 123,
3. Add 10 → 133
What is an Array in Java?

An array in Java is a collection of elements (all of the same type) stored in contiguous
memory locations.

It allows you to store multiple values in a single variable, instead of declaring separate
variables for each value.

Example:

int[] numbers = {10, 20, 30, 40, 50};

This is an array of 5 integers.

Key Features of Arrays

Feature Description
Fixed Size You must define the size at the time of creation.
Same Data Type All elements must be of the same type (e.g., all int, all String).
Index-based Elements are accessed by their index (starts at 0).
Efficient Access Fast access using index, like array[2].

How to Declare and Use Arrays

1. Declare an Array

int[] arr; // preferred

// or

int arr[]; // also valid

2. Allocate Memory
arr = new int[5]; // array of 5 integers

3. Initialize with Values

arr[0] = 10;

arr[1] = 20;

// and so on...

4. Or do all at once

int[] arr = {10, 20, 30, 40, 50};

Example:

public class ArrayExample {

public static void main(String[] args) {

int[] numbers = {5, 10, 15, 20, 25};

[Link]("Third number: " + numbers[2]); // 15

[Link]("All numbers:");

for (int num : numbers) {

[Link](num);

You might also like