Java Memory Management Explained
Java Memory Management Explained
Dig deeper into memory areas used by the Java Virtual Machine.
• Introduction to Packages
• Built-in Packages (e.g., [Link], [Link])
• User-defined Packages
JAVA
JVM defines various runtime data areas used during the execution of a
program. Some of the areas are created by the JVM, whereas some are
created by the threads that are used in a program. However, the memory
area created by the JVM is destroyed only when the JVM exits. The data
areas of a thread are created during instantiation and destroyed when
the thread exits. These areas include:
• Heap Area
• Method Area
• JVM Stacks
• Native Method Stacks
• Program Counter (PC) Registers
JVM defines various runtime data areas used during the execution of a
program. Some of the areas are created by the JVM, whereas some are
created by the threads that are used in a program. However, the memory
area created by the JVM is destroyed only when the JVM exits. The data
areas of a thread are created during instantiation and destroyed when
the thread exits. These areas include:
• Heap Area
• Method Area
• JVM Stacks
• Native Method Stacks
• Program Counter (PC) Registers
1. Heap Area
• Heap is a shared runtime data area where objects and arrays are
stored. It is created when the JVM starts.
• JVM allows user to adjust the heap size. When the new keyword is
used the object is allocated in the heap and its reference is stored
in the stack.
• There exists one and only one heap for a running JVM process.
Scanner sc = new Scanner([Link])
Here, the Scanner object is stored in the heap and the reference sc is
stored in the stack
JAVA
2. Method Area
• Method area is a logical part of the heap and it is created when the
JVM starts.
• Method area is used to store class-level information such as class
structures, Method bytecode, Static variables, Constant pool,
Interfaces.
• Method area can be of fixed or dynamic size depending on the
system's configuration.
• Static variables in Java are stored in the Method Area.
• Garbage collection of the method area is not guaranteed and
depends on JVM implementation.
Note: Method area is logically a part of heap, many JVM like HotSpot
uses a separate space known as Metaspace outside the heap to store it.
Example: Java Program to demonstrate how java variables are stored in
the different memory areas
jvm-memory
1. Heap Area
• Heap is a shared runtime data area where objects and arrays are
stored. It is created when the JVM starts.
• JVM allows user to adjust the heap size. When the new keyword is
used the object is allocated in the heap and its reference is stored
in the stack.
• There exists one and only one heap for a running JVM process.
JAVA
2. Method Area
• Method area is a logical part of the heap and it is created when the
JVM starts.
• Method area is used to store class-level information such as class
structures, Method bytecode, Static variables, Constant pool,
Interfaces.
• Method area can be of fixed or dynamic size depending on the
system's configuration.
• Static variables in Java are stored in the Method Area.
• Garbage collection of the method area is not guaranteed and
depends on JVM implementation.
Note: Method area is logically a part of heap, many JVM like HotSpot
uses a separate space known as Metaspace outside the heap to store it.
Example: Java Program to demonstrate how java variables are stored in
the different memory areas
import [Link].*;
class Geeks {
[Link](v);
[Link](s);
}
}
Output
100
20
Note:
3. JVM Stacks
Heap vs Stack
Heap Stack
Allocation is manual (using 'new' keyword), but Allocation and deallocation both
deallocation is automatic. are automatic.
The Garbage collector automatically removes the unused objects that are
no longer needed. It runs in the background to free up memory.
JAVA
The Java Virtual Machine is responsible for running Java applications, and
it manages various memory areas, one of which is the Stack Area. In this
article, we are going to discuss about JVM Stack Area in depth.
In Java, each thread has its own stack called the Run-Time Stack, created
when the thread starts. This stack holds the data for method execution
within that thread. The memory for a Java Virtual Machine stack does not
need to be contiguous. JVM implementations can allocate and manage
stack memory dynamically, depending on the platform.
When a method is called, a new stack frame is created and pushed onto
the thread's JVM stack, this stack frame contains all the information
needed for the method execution. The JVM executes the method's code,
using the local variables and parameters stored in the stack frame. Once
the method execution is complete, the stack frame is popped off the
stack, and control returns to the calling method.
Note: This process will repeat for every method call, including recursive
and nested calls.
Example: Here, the example demonstrates how the stack actually works.
class Geeks {
public static int add(int a, int b) {
return a + b;
}
JAVA
Output
Answer: 10
Explanation:
• When main method is called, the stack frame for the main is created.
• Inside the main, the add method is called with the parameters, now the new stack
frame for the add is created.
• The add method executes using the provided parameters
• After the add method returns, its stack frame is popped off and control returns to
main.
The image below demonstrates the stack area of JVM:
The stack frame basically consists of three parts. The three parts are
• The local variables part of the stack frame is organized as a zero-based array of words.
• It contains all parameters and local variables of the method.
• Each slot or entry in the array is of 4 Bytes.
• Values of type int, float, and reference occupy 1 entry or slot in the array i.e. 4 bytes.
• Values of double and long occupy 2 consecutive entries in the array i.e. 8 bytes total.
• Byte, short, and char values will be converted to int type before storing and occupy 1
slot i.e. 4 Bytes.
• But the way of storing Boolean values is varied from JVM to JVM. But most of the JVM
gives 1 slot for Boolean values in the local variable array.
• The parameters are placed into the local variable array first, in the order in which they
are declared.
Example: Let us consider a class Example having a method bike() then the local variable
array will be as shown in the below diagram:
// Class Declaration
class Example
}
JAVA
So, here first two instructions iload_0 and iload_1 will push the values in the operand stack
from a local variable array. And instruction isub will subtract these two values and store the
result back to the operand stack and after istore_2 the result will pop out from the operand
stack and will store into a local variable array at position 2.
• It contains all symbolic references (constant pool resolution) and normal method
returns related to that particular method.
• It also contains a reference to the Exception table which provides the corresponding
catch block information in the case of exceptions.
In Java JVM divides memory into several regions for efficient program execution. One of the
most important among them is the Heap Area. The heap is a place in memory where objects
and class instances are stored during runtime. It is shared among all threads and ma naged
by the Garbage Collector.
3. Managed by Garbage Collector (GC): Java automatically manages heap memory using
the Garbage Collector. When an object is no longer referenced, it becomes eligible for
garbage collection.
4. Divided into Generation: To optimize GC, the heap is divided into parts:
• Young Generation: The area within the heap where new objects are generally
allocated.
• Old Generation: The area within the heap where long lived objects are stored after
surviving multiple garbage collection cycle.
• Permanent Generation: It stores meta data about classes and methods.
• Survivor space: It is a part of heap memory Young Generation where objects that
survive garbage collection in the Eden Space are moved.
• Code cache: It is the special memory outside the heap where JVM stores optimized
code to make programs run faster.
1. Object Header: Stores metadata such as identity hash code, garbage collection (GC) age
and synchronization (lock) information. It helps the JVM manage the object internally.
JAVA
3. Instance Variable: Includes all primitive fields (like int, char) and references to other
objects. This is the part of the object that stores the actual data defined in your class.
Note: The exact layout depends on the JVM implementation and underlying architecture (32-
bit vs 64-bit, compressed oops enabled, etc.).
Example
Below image illustrates how Java allocates memory for objects using the stack and heap
areas. It shows reference variables stored in the stack pointing to actual objects in the heap.
// Constructor
Geeks(String name) {
[Link] = name;
}
// Call static method using the class name and pass name
[Link]([Link]);
[Link]([Link]);
}
}
OutputAlice
Bob
Explanation:
1. Unreachable Objects
An object becomes unreachable if it does not contain any reference to it.
Even though the programmer is not responsible for destroying useless objects but it is highly
recommended to make an object unreachable(thus eligible for GC) if it is no longer required.
There are generally four ways to make an object eligible for garbage collection.
@Override
protected void finalize() throws Throwable {
[Link]("GC cleaning up...");
}
Note:
Problem Statement: Suppose you go for the internship at GeeksForGeeks and you were
told to write a program to count the number of employees working in the company(excluding
interns). To make this program, you have to use the concept of a garbage collector.
This is the actual task you were given at the company: Write a program to create a class
called Employee having the following data members.
class Employee {
[Link] = name;
[Link] = age;
[Link] = nextId++;
}
class UseEmployee {
public static void main(String[] args) {
Output:
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
JAVA
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=6
Now garbage collector will see 2 objects free. Now to decrement nextId,
garbage collector will call method to finalize() only when we programmers
have overridden it in our class. And as mentioned previously, we have to
request garbage collector and for this, we have to write the following 3
steps before closing brace of sub-block.
class Employee {
[Link] = name;
[Link] = age;
[Link] = nextId++;
}
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
{
// It is sub block to keep all those interns.
Employee X = new Employee("GFG4", 23);
Employee Y = new Employee("GFG5", 21);
[Link]();
[Link]();
[Link]();
[Link]();
X = Y = null;
[Link]();
[Link]();
}
[Link]();
}
}
Output:
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
JAVA
Example:
import [Link];
import [Link];
while (true) {
[Link](obj);
references of all the objects and because of this memory usage keeps on
growing and causes OutOfMemoryError.
There are multiple tools that help us to detect memory leaks by showing
which object is using the most memory, and the list of such tools are
listed below:
If our program keep on leaking memory it means the program will use up
all the memory as much as it can use. After some time, the program will
stop working and will show an error like this:
We can avoid memory leaks by keeping few things in our mind which is
listed below:
• Strong References
• Weak References
• Soft References
• Phantom References
Prerequisite: Basic understanding of Garbage Collection
JAVA
1. Strong References
This is the default type/class of Reference Object. Any object which has an active strong
reference are not eligible for garbage collection. The object is garbage collected only when
the variable which was strongly referenced points to null.
obj = null; //'obj' object is no longer referencing to the instance. So the 'MyClass type object
is now available for garbage collection.
2. Weak References
Weak Reference Objects are not the default type/class of Reference Object and they should
be explicitly specified while using them.
g.x();
}
}
OutputGeeksforGeeks
GeeksforGeeks
Note: The object may be garbage collected anytime after the strong reference is removed.
3. Soft References
In Soft reference, even if the object is free for garbage collection then also its not garbage
collected, until JVM is in need of memory [Link] objects gets cleared from the memory
when JVM runs out of [Link] create such references [Link] class
is used.
JAVA
g.x();
}
}
Output
GeeksforGeeks
GeeksforGeeks
4. Phantom References
The objects which are being referenced by phantom references are eligible
for garbage collection. But, before removing them from the memory, JVM
puts them in a queue called ‘reference queue’ . They are put in a
reference queue after calling finalize() method on [Link] create such
references [Link] class is used.
Example:
class Gfg
{
//code
public void x()
{
[Link]("GeeksforGeeks");
}
}
Output:
JAVA
Java Packages
Packages in Java are a mechanism that encapsulates a group of classes, sub-packages and
interfaces. Packages are used for:
• Prevent naming conflicts by allowing classes with the same name to exist in different
packages, like [Link] and [Link].
• Make it easier to organize, locate and use classes, interfaces and other components.
• Provide controlled access for Protected members that are accessible within the
same package and by subclasses. Default members (no access specifier) are
accessible only within the same package.
By grouping related classes into packages, Java promotes data encapsulation, making code
reusable and easier to manage. Simply import the desired class from a package to use it in
your program.
mkdir PROGRAMMING
Step 2: Now, change the directory and create another folder inside the main folder
cd PROGRAMMING
mkdir JavaProgramming
cd JavaProgramming
mkdir arrays
Step 3: Now create an empty text file and write the below Java code and don't forget to save
it with the same name as the class with .java extension ([Link])
TwoPointers Class.
package [Link];
Note: Do not forget to add the package name inside the program file.
Step 4: Now run the program with the define folder path
javac src\JavaProgramming\arrays\[Link]
java src\JavaProgramming\arrays\[Link]
Output:
Folder Structure:
This is the visual representation of a custom package in Java in the below image. First, we
create a folder named Progamming and inside it we create a package Javaprogramming and
then create another subpackage, which is called arrays. Then, we create a Java class file
inside it, which is shown in the image below:
JAVA
Directory Structure: Package names and directory structures are closely related. For
example, if a package name is [Link], then three directories are, college, staff and
cse, where cse is inside staff and staff is inside the college.
Naming Conventions: Package names are written in reverse order of domain names, e.g.,
[Link]. In a college, the convention might be:
• [Link]
• [Link]
• [Link]
Example:
import [Link].*;
Here, util is a sub-package created inside the java package.
In Java, we can import classes from a package using either of the following methods:
import [Link];
JAVA
This imports only the Vector class from the [Link] package.
import [Link].*;
This imports all classes and interfaces from the [Link] package but does not include sub-
packages.
import [Link];
public Geeks() {
[Link](l);
}
new Geeks();
}
}
Output
[3, 5, 7]
Note:
JAVA
• Using import package.*; imports all classes in a package, but not classes from its
sub-packages.
• When two packages have classes with the same name (e.g., [Link] and
[Link]), use the fully qualified name to avoid conflicts:
import [Link];
import [Link];
• Built-in Packages
• User-defined Packages
1. Built-in Packages
These packages consist of a large number of classes which are a part of Java [Link] of
the commonly used built-in packages are:
2. User-defined Packages
First we create a directory myPackage (name should be same as the name of the package).
Then create the MyClass inside the directory with the first statement being the package
names.
Example:
JAVA
package myPackage;
import [Link];
[Link](s);
}
}
Note: [Link] must be saved inside the myPackage directory since it is a part of the
package.
Static Import in Java is about simplifying access to static members and separates it from the
broader discussion of user-defined packages.
JAVA
Static import is a feature introduced in Java programming language (versions 5 and above)
that allows members (fields and methods) defined in a class as public static to be used in
Java code without specifying the class in which the field is defined.
Example:
class Geeks {
public static void main(String args[]) {
Output
GeeksforGeeks
When two packages contain a class with the same name (e.g.,
[Link] and [Link]), specify the full package name to avoid
conflicts.
import [Link].*;
import [Link].*;
//And then use Date class, then we will get a compile-time error :
Date today ; //ERROR-- [Link] or [Link]?
The compiler will not be able to figure out which Date class do we want.
This problem can be solved by using a specific import statement:
import [Link];
import [Link].*;
If we need both Date classes then, we need to use a full package name
every time we declare a new object of that class. For Example:
$BASE_DIR/com/zzz/project1/subproject2/[Link]
• Here $BASE_DIR represents the base directory of the package.
• The "dot" in the package name corresponds to a sub-directory of
the file system.
• The base directory ($BASE_DIR) could be located anywhere in the
file system.
• Hence, the Java compiler and runtime must be informed about the
location of the $BASE_DIR so as to locate the classes.
• It is is accomplished by an environment variable called CLASSPATH.
• CLASSPATH is similar to another environment variable PATH, which
is used by the command shell to search for the executable programs.
Setting CLASSPATH
package package_name;
package package_one;
import package_name.ClassOne;
import package_one.ClassTwo;
Now having a look at the directory structure of both the packages and
the testing class file:
• Public: Members with the public modifier are accessible from anywhere, regardless
of whether the accessing class is in the same package or not.
• Protected: Members with the protected modifier are accessible within the same
package, In subclasses
• Default: Members with no modifier are accessible only within the same package
• Private: Members with the private modifier are accessible only within the same
class. They cannot be accessed by classes in the same package, subclasses, or
different packages.
JAVA
• [Link]: Provides the classes for accessing and processing data stored in a
database. Classes like Connection, DriverManager, PreparedStatement, ResultSet,
Statement, etc. are part of this package.
• [Link]: Contains classes and interfaces that are fundamental to the design of the
Java programming language. Classes like String, StringBuffer, System, Math, Integer,
etc. are part of this package.
JAVA
1. [Link] Package
This package provides APIs for database operations using JDBC (Java Database
Connectivity).
Example:
import [Link].*;
while ([Link]()) {
// Retrieving data from column name
[Link]("ID: " + [Link]("id"));
[Link](",NAME: " + [Link]("name"));
[Link](",ADDRESS: " + [Link]("address"));
}
} catch (SQLException e) {
[Link]();
}
}
}
Output
Explanation:
2. [Link] Package
This package contains the core classes that are fundamental to the Java
language. This package is automatically imported to each program, which
means we can directly use classes of this package in our program.
Let's have an example of the Math class of lang package which provides
various functions or methods for mathematical operation.
Example:
JAVA
OutputMaximum is = 200
Explanation:
• We use the lang package and Math class to find the maximum of two -
digit using the "max" function.
• First, we created a three integer variable named "a" and "b" and
maxi. where a = 100 and b = 200 and maxi will store the maximum
value from a or b.
• After assigning values to the variable we used the max function to
find the maximum and stored it in maxi.
• So, in desired output, we can see a maximum of two numbers and that
is 200.
3. [Link] Package
Example:
import [Link];
[Link](arr);
[Link]("Sorted Array is = " + [Link](arr));
}
}
Output:
Explanation:
4. [Link] Package
Example:
import [Link];
Output
• We use the [Link] package and Console class to take input from
users to perform some task or operations on it and then finally
display the result on the console.
• As code said first we display the message "Enter your favorite
color" which asks a user to enter color.
• Then user system read that line using [Link]() and stored
it in string type variable then finally display that line.
5. [Link] Package
This package contains the classes and interfaces for networking like
Socket class, ServerSocket class, URLConnection class, DatagramSocket,
MulticastSocket, etc. Java supports the two network protocols such as
TCP (Transmission control protocol) and UDP (User Datagram Protocol which
is a connection-less protocol).
Example:
import [Link];
import [Link];
import [Link];
DatagramPacket DpReceive;
while (true) {
JAVA
Output:
Explanation:
6. [Link] Package
This package is the main package of the abstract window kit. it includes
the classes for graphics, containing the java 2D graphics and it also
defines the graphical user interface (GUI) framework for java. this
package had several heavy GUI objects which come under [Link] package.
Example:
import [Link].*;
JAVA
Output:
Explanation: Here, we created a frame of size 200 x 200 by using an awt package and then
print a message "Welcome to the Java graphics GEEKSFORGEEKS.
In Java, it is good practice to name classes, variables and methods name as what they are
supposed to do instead of naming them randomly. Below are some naming conventions
of the Java programming language. They must be followed while developing software in
Java for good maintenance and readability of code. Java uses CamelCase as a practice for
writing names of methods, variables, classes, packages and constants.
Camel's case in Java programming consists of compound words or phrases such that
each word or abbreviation begins with a capital letter or first word with a lowercase letter,
rest all with capital. Here in simpler terms, it means if there are two
Note:
• In package, everything is small even while we are combining two or more words in
java
• In constants, we do use everything as uppercase and only '_' character is used even
if we are combining two or more words in java
In Java, we follow certain rules for naming things like classes, methods, variables and more.
These rules make the code more easier to read and understand. One important rule is
called CamelCase. This means that when we have a long name made up of several words,
we start with a small letter for the first word and use capital letters for the following words.
For example:
myVariableName
This way of naming helps keep the code clean and organized, especially when the project
gets bigger.
• Class names should be nouns, in mixed cases with the first letter of each internal
word capitalized. Interfaces names should also be capitalized just like class names.
Classes: class Student { }
JAVA
class Integer {}
class Scanner {}
• Use whole words and must avoid acronyms and abbreviations.
Interfaces: Runnable
Remote
Serializable
2. Methods
Methods should be verbs, in mixed case with the first letter lowercase and with the first
letter of each internal word capitalized.
3. Variables
Variable names should not start with underscore _ or dollar sign $ characters, even though
both are allowed.
• Should be mnemonic i.e, designed to indicate to the casual observer the intent of
its use.
• One-character variable names should be avoided except for temporary variables.
• Common names for temporary variables are i, j, k, m and n for integers; c, d and e
for characters.
int[] marks;
4. Constant variables
5. Packages
Note:
• For class, interfaces and constants, the first letter has to be uppercase.
• For method , variable and package_name, the first letter has to be lowercase.
Syntax:
package package-name;
JAVA
package example1;
Step 2: Include the class in a Java package, but remember that a class only has one package
declaration.
package example1;
class Geeks {
public static void main(String[] args){
-------function--------
}
}
Step 3: Now the user-defined package is successfully created, we can import it into other
packages and use it's functions.
Note: If we do not specify any package for a class, it is placed in the default package.
In the below-mentioned examples, in the first example we'll create a user-defined package
name "example" under that we've class named "Geeks" which has a function to print
message. In the second example, we will import our user-defined package name "example"
and use a function present in that package.
Example 1: In this example, we will create a user-defined package and function to print a
message for the users.
package example;
// Class
public class Geeks {
Output:
import [Link];
Output:
Project Structure
The image below demonstrates the project structure.
We will organize the code into these parts which are listed below:
• Interface: This will define what a quiz should do(like when to submit the answer,
when to start the quiz and when to show the result).
JAVA
• Model class: This class will represent a list of questions, options and the correct
answer.
• Service class: This class implements the Quiz interface and contains the quiz logic.
• Main class: It is the main class that contains the program entry point to run the quiz.
Let's now try to implement the code.
package [Link];
[Link]:
package [Link];
}
public String getQuestionText() {
return questionText;
}
return options;
}
package [Link];
import [Link];
import [Link];
import [Link];
@Override
public void start() {
Scanner scanner = new Scanner([Link]);
int answerIndex;
try {
answerIndex = [Link](input);
if (answerIndex < 1 || answerIndex > [Link]) {
[Link]("Invalid option, answer recorded as blank.");
userAnswers[i] = "";
} else {
userAnswers[i] = options[answerIndex - 1];
}
} catch (NumberFormatException e) {
[Link]("Invalid input, answer recorded as blank.");
userAnswers[i] = "";
}
}
}
@Override
public void submitAnswer(int questionIndex, String answer) {
if (questionIndex >= 0 && questionIndex < [Link]) {
userAnswers[questionIndex] = answer;
}
}
@Override
public void showResults() {
score = 0;
for (int i = 0; i < [Link]; i++) {
if (questions[i].getCorrectAnswer().equalsIgnoreCase(userAnswers[i])) {
score++;
}
}
[Link]("\nQuiz Completed!");
[Link]("Your score: " + score + " out of " + [Link]);
}
}
JAVA
[Link]:
package quiz;
import [Link];
import [Link];
[Link]();
[Link]();
}
}
Output:
JAVA
Notes:
• If the user inputs something invalid (like "five" or "0"), it will record a blank answer and
skip scoring that question.
• The answers you enter correspond to the index of the correct option (1-based).