0% found this document useful (0 votes)
11 views66 pages

Java Memory Management Explained

The document provides an overview of Java memory management, detailing how the Java Virtual Machine (JVM) allocates and deallocates memory, including the concepts of stack and heap memory, garbage collection, and memory leaks. It explains the structure of JVM memory areas, including the heap, method area, and JVM stacks, as well as the role of garbage collection in managing memory. Additionally, it covers best practices for organizing code with packages and naming conventions.

Uploaded by

guptabhai903
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)
11 views66 pages

Java Memory Management Explained

The document provides an overview of Java memory management, detailing how the Java Virtual Machine (JVM) allocates and deallocates memory, including the concepts of stack and heap memory, garbage collection, and memory leaks. It explains the structure of JVM memory areas, including the heap, method area, and JVM stacks, as well as the role of garbage collection in managing memory. Additionally, it covers best practices for organizing code with packages and naming conventions.

Uploaded by

guptabhai903
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

JAVA

Day 22 : Java Memory Management

Understand how Java handles memory behind the scenes.

• What is Memory Management


• How are Java Objects Stored in Memory

Day 23 : Stack vs Heap & JVM Memory

Dig deeper into memory areas used by the Java Virtual Machine.

• Stack vs Heap memory


• Java Virtual Machine (JVM) Stack Area
• Types of Memory Areas Allocated by JVM

Day 24 : Garbage Collection in Java

Learn how Java automatically clears unused memory.


JAVA

• What is Garbage Collection?


• The finalize() method (deprecated in recent versions)
• Garbage Collection algorithms: Mark & Sweep (overview)

Day 25 : Memory Leaks and Reference Types

Avoid common pitfalls in Java memory handling.

• What is a Memory Leak in Java?


• Reference Types in Java

Day 26 : Java Packages Overview

Organize your code better with packages.

• Introduction to Packages
• Built-in Packages (e.g., [Link], [Link])
• User-defined Packages
JAVA

Day 27 : Importing Packages & Naming Conventions

Follow best practices in modular coding.

• How to Import Packages


• Java Naming Conventions (packages, classes, constants, variables)

Java Memory Management


JAVA

Java memory management is the process by which the Java Virtual


Machine (JVM) automatically handles the allocation and deallocation of
memory. It uses a garbage collector to reclaim memory by removing
unused objects, eliminating the need for manual memory management

JVM Memory Structure

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

Java Virtual Machine (JVM) Memory Areas

The image below demonstrates the Java Memory Area parts:

Java memory management is the process by which the Java Virtual


Machine (JVM) automatically handles the allocation and deallocation of
memory. It uses a garbage collector to reclaim memory by removing
unused objects, eliminating the need for manual memory management
JAVA

JVM Memory Structure

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

Java Virtual Machine (JVM) Memory Areas

The image below demonstrates the Java Memory Area parts:


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.
Scanner sc = new Scanner([Link])
Here, the Scanner object is stored in the heap and the reference sc is
stored in the stack
JAVA

Note: Garbage collection in heap area is mandatory.

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

Scanner sc = new Scanner([Link])


Here, the Scanner object is stored in the heap and the reference sc is
stored in the stack

Note: Garbage collection in heap area is mandatory.

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 {

// static variables are stored in the Method Area


static int v = 100;
JAVA

// instance variables are stored in the Heap


int i = 10;

public void Display()


{
// local variables are stored in the Stack
int s = 20;

[Link](v);
[Link](s);
}
}

public class Main {


public static void main(String[] args) {
Geeks g = new Geeks();

// Calling the Display method


[Link]();
}
}
JAVA

Output
100
20

Note:

• Static variables are stored in the Method Area.


• Instance variables are stored in the Heap.
• Local Variables are stored Stack.

3. JVM Stacks

• A stack is created when a thread is created and the JVM stack is


used to store method execution data, including local variables,
method arguments and return addresses.
• Each Thread has its own stack, ensuring thread safety.
• Stacks size can be either fixed or dynamic and it can be set when the
stack is created.
• The memory for stack needs not to be contiguous.
• Once a method completes execution, its associated stack frame is
removed automatically.

4. Native Method Stacks

• Native method stack is also known as C stacks.


• Native method stacks are not written in Java language.
• This memory is allocated for each thread when it is created and can
have either a fixed or dynamic size.
• Native method stacks handle the execution of native methods that
interact with the Java code.
JAVA

5. Program Counter (PC) Registers

• Each JVM thread has a Program Counter (PC) register.


• For non-native methods, it stores the address of the current JVM
instruction.
• For native methods, the PC value is undefined.
• On some platforms, the PC can also store a return address or native
pointer.

Heap vs Stack

Heap Stack

Stores method calls and local


Stores objects and instance variables.
variables.

Larger but slower. Smaller but faster.

Random access. LIFO (Last-In-First-Out).

Allocation is manual (using 'new' keyword), but Allocation and deallocation both
deallocation is automatic. are automatic.

Long-lived. Short-lived (method duration).

Each thread has its own stack


Shared among all threads (needs synchronization).
(thread safe).

Garbage Collector in java

The Garbage collector automatically removes the unused objects that are
no longer needed. It runs in the background to free up memory.
JAVA

• Garbage collector finds objects that are no longer needed by the


program.
• It removes those unused objects to free up the memory and making
space for new objects.
• Java uses generational garbage collection so that new objects are
collected more frequently in the young generation than older
objects which survive longer in the old generation, this helps
improve efficiency.
• You can request garbage collection using [Link](), but the JVM
ultimately decides when it should run.
Note: You can request GC with [Link]() or [Link](), but JVM
decides when it runs.

Java Virtual Machine (JVM) Stack Area

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.

JVM Stack Area

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.

Components of a Stack Frame

The main components of a stack frame are listed below:


JAVA

• Method call information: Stores details about the method being


executed.
• Local variables: Stores local variables defined within the method.
• Method parameters: Stores parameters passed to the method.
• Return address: Tracks where to return once the method completes.
After all method calls are completed, the stack is emptied and destroyed
by the JVM. The stack data is thread-specific, ensuring thread safety for
local variables. Each entry in the stack is called a Stack Frame or
Activation Record.

How the JVM Stack Works?

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.

// Java Program to Demonstrate the working of stack


import [Link].*;

class Geeks {
public static int add(int a, int b) {
return a + b;
}
JAVA

public static void main (String[] args) {


int ans = add(5, 5);
[Link]("Answer: " + ans);
}
}
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:

Stack Frame Structure

The stack frame basically consists of three parts. The three parts are

• Local Variable Array


• Operand Stack
• Frame Data
When JVM invokes a Java method, first it checks the class data to determine the number of
words (size of the local variable array and operand stack, which is measured in words for
each individual method) required by the method in the local variables array and operand
stack. It creates a stack frame of the proper size for invoked method and pushes it onto the
Java stack.
JAVA

1. Local Variable Array (LVA)

• 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

public void bike(int i, long l, float f, double d, Object o, byte b)

}
JAVA

2. Operand Stack (OS)

• The JVM uses an operand stack as a workspace for temporary calculations.


• Unlike the local variable array, which you access using an index, the operand stack
works with special instructions. These instructions can push values onto the stack,
pop values off, and perform operations using those values.
Example: Here is how a JVM will use this below code that would subtract two local variables
that contain two ints and store the int result in a third local variable:

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.

3. Frame Data (FD)

• 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.

JVM Heap Area


JAVA

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.

Characteristics of Heap Area


1. Runtime Memory Allocation: The heap is used for dynamic memory allocation.
Whenever you create an object using new, memory is allocated from the heap.

Student s = new Student(); // Memory for Student is allocated in Heap


2. Shared Among All Threads: Heap memory is shared among all threads in the JVM. This
makes synchronization important when multiple threads access shared objects.

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.

Component of Objects in Heap


When an object is created in the heap, it's not just the instance variables that consume
memory. Each object has an internal structure managed by the JVM. Here's what each
object typically contains:

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.

4. Padding / Alignment: JVM adds padding to maintain proper memory alignment,


improving access speed and ensuring that object sizes are aligned to machine-word
boundaries (like 8 or 16 bytes).

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.

Implementation: Object Allocation in Heap


public class Geeks {
String name;

// Constructor
Geeks(String name) {
[Link] = name;
}

// Static method to print a name


static void Print(String name) {
[Link](name);
}

public static void main(String[] args) {


JAVA

Geeks obj1 = new Geeks("Alice");


Geeks obj2 = new Geeks("Bob");

// Call static method using the class name and pass name
[Link]([Link]);
[Link]([Link]);
}
}

OutputAlice
Bob

Explanation:

• obj1 and obj2 are objects created in the heap.


• Their reference variables are stored in the stack.
• The Print() method is static, so it belongs to the class, not the objects.
• [Link] and [Link] are passed to the method for printing.

Garbage Collection in Java


Garbage collection in Java is an automatic memory management process that helps Java
programs run efficiently.

• Objects are created on the heap area.


• Eventually, some objects will no longer be needed.
• Garbage collection is an automatic process that removes unused objects from heap.

Working of Garbage Collection


• It identifies which objects are still in use (referenced) and which are not in use
(unreferenced).
• It removes the objects that are unreachable (no longer referenced).
• The programmer does not need to mark objects to be deleted explicitly. Garbage
collection is implemented within the JVM.
JAVA

Types of Activities in Java Garbage Collection


Java heap is divided into generations:

• Young Generation: In this new objects are allocated.


• Old Generation: In this long-lived objects are stored.
Two types of garbage collection activities usually happen in Java. These are:

• Minor or incremental Garbage Collection (GC): This occurs when unreachable


objects in the Young Generation heap memory are removed.
• Major or Full Garbage Collection (GC): This happens when objects that survived
minor garbage collection are removed from the Old Generation heap memory. It
occurs less frequently than minor garbage collection.

Key Concepts on Garbage Collection

1. Unreachable Objects
An object becomes unreachable if it does not contain any reference to it.

Integer i = new Integer(4);


// the new Integer object is reachable via the reference in 'i'
i = null;
// the Integer object is no longer reachable.

2. Making Objects Eligible for GC


An object is said to be eligible for garbage collection if it is unreachable. After i = null, integer
object 4 in the heap area is suitable for garbage collection in the above image.

How to Make an Object Eligible for Garbage Collection?

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.

• Nullifying the reference variable (obj = null).


• Re-assigning the reference variable (obj = new Object()).
JAVA

• An object created inside the method (eligible after method execution).


• Island of Isolation (Objects that are isolated and not referenced by any reachable
objects).

3. Requesting Garbage Collection


• Once an object is eligible for garbage collection, it may not be destroyed
[Link] garbage collector runs at the JVM's discretion and you cannot
predict when it will occur.
• We can also request JVM to run Garbage Collector. There are two ways to do it. fiest
using [Link]() and second using [Link]().gc():
• Using [Link](): This static method requests the JVM to perform garbage
collection.
• Using [Link]().gc(): This method also requests garbage collection
through the Runtime class.
[Link]();
// OR
[Link]().gc();

4. The finalize() Method (Deprecated in Java 9+)


Before destroying an object, the garbage collector calls the finalize() method to perform
cleanup activities. The method is defined in the Object class as follows:

@Override
protected void finalize() throws Throwable {
[Link]("GC cleaning up...");
}
Note:

• finalize() method is deprecated since Java 9 because it is unpredictable and can


cause performance issues.
• Alternatives like try-with-resources or explicit cleanup methods are preferred.
• The garbage collector calls finalize() at most once per object.
• Exceptions thrown in finalize() are ignored.
JAVA

Employee Management System Using Garbage Collection Concept


Let's take a real-life example, where we use the concept of the garbage collector.

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.

1. An ID for storing unique id allocated to every employee.


2. Name of employee.
3. Age of an employee.

Also, provide the following methods:

• A parameterized constructor to initialize name and age. The ID should be initialized


in this constructor.
• A method show() to display ID, name and age.
• A method showNextId() to display the ID of the next employee.

Common Beginner Approach (Without Garbage Collection)


Now any beginner, who does not know Garbage Collector in Java will code like this:

class Employee {

private int ID;


private String name;
private int age;
private static int nextId = 1;
// it is made static because it is keep common among all and shared by
all objects

public Employee(String name, int age) {


JAVA

[Link] = name;
[Link] = age;
[Link] = nextId++;
}

public void show()


{
[Link]("Id=" + ID + "\nName=" + name
+ "\nAge=" + age);
}

public void showNextId()


{
[Link]("Next employee id will be="
+ nextId);
}
}

class UseEmployee {
public static void main(String[] args) {

Employee E = new Employee("GFG1", 56);


Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
JAVA

{ // 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]();
}
// Output of this line
[Link]();
// should be 4 but it will give 6 as output.
}
}

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

Improved Approach Using Garbage Collection and finalize()

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.

1. Set references to null(i.e X = Y = null;)


2. Call, [Link]();
3. Call, [Link]();
Now the correct code for counting the number of employees (excluding
interns):

class Employee {

private int ID;


private String name;
private int age;
private static int nextId = 1;
// it is made static because it is keep common among all and shared by
all objects

public Employee(String name, int age) {


JAVA

[Link] = name;
[Link] = age;
[Link] = nextId++;
}

public void show()


{
[Link]("Id=" + ID + "\nName=" + name
+ "\nAge=" + age);
}

public void showNextId()


{
[Link]("Next employee id will be="
+ nextId);
}

protected void finalize()


{
--nextId;
// In this case, gc will call finalize() for 2 times for 2 objects.
}
}

public class UseEmployee {


public static void main(String[] args) {

Employee E = new Employee("GFG1", 56);


Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
JAVA

[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

Next employee id will be=4


Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=4

Advantages of Garbage Collection


The advantages of Garbage Collection in Java are:

• It makes java memory-efficient because the garbage collector removes the


unreferenced objects from heap memory.
• It is automatically done by the garbage collector (a part of JVM), so we don't need
extra effort.

Memory Leaks in Java


In programming, a memory leak happens when a program keeps using memory but does not
give it back when it's done. It simply means the program slowly uses more and more memory,
which can make things slow and even stop working.

Working of Memory Management in Java


• Java has automatic garbage collection, which simply means that Java can
automatically free up memory for objects that are no longer in use or no longer
needed.
• But if our program creates many objects but keeps references to them even if they
are not needed, the garbage collector cannot destroy those objects. If memory use
grows beyond the allowed limit, the program will crash.
Note: If an object is no longer needed, it is important to remove references to it so the
garbage collector can free its memory.
JAVA

Why Do Memory Leaks Happen in Java?


We know that Java cleans up memory automatically with the help of garbage collector but
still memory leaks can happen, this happens because our program keep holding onto things
that are no longer needed. Our Java program still remembers these objects and thinks they
are important and that's why it does not remove them and this wastes memory cause the
problems.

Example:

// Demonstrating memory leaks in Java

import [Link];

import [Link];

public class Geeks {

public static void main(String[] args) {

List<Object> list = new ArrayList<>();

while (true) {

Object obj = new Object();

// The list keeps growing and holds references to all objects

[Link](obj);

Explanation: In the above example, the program keep on creating new


object and each object is added to the list because list stores the
JAVA

references of all the objects and because of this memory usage keeps on
growing and causes OutOfMemoryError.

Tools to Find Memory Leaks

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:

• VisualVM (comes with JDK)


• Eclipse Memory Analyzer (MAT)
• Java Mission Control
• YourKit Java Profiler
What Happens If Memory Keeps Leaking?

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:

[Link]: Java heap space


This means Java ran out of memory to create new things it needs.

How to Avoid Memory Leaks?

We can avoid memory leaks by keeping few things in our mind which is
listed below:

• Stop keeing things that we do not need in our program do not


initialize unnecessary variables and list items to null.
• Do not let lists or caches keep growing forever without removing old
stuff.
JAVA

• It is always recommended to close files and database connections


when we are done with them.

Memory Management in C vs Java

The main difference between memory management in c and memory


management in Java is listed below:

• In C language, programmers manually allocate and free memory. If


a programmer forgets to free memory then it causes a memory leak.
• In Java language, memory is managed automatically with the help of
a garbage collector. The task of garbage collector is to find objects
that are no longer used and free up their memory.

Types of References in Java


One of the important parts of memory management in Java is, how it handles references to
objects and decides when to remove those objects that are no longer needed. Java offers
several types of references, and it is important to understand that all references are not the
same.

Java References Types


In Java, there are four types of references differentiated by the way in which they are garbage
collected.

• 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.

MyClass obj = new MyClass ();


Here 'obj' object is strong reference to newly created instance of MyClass, currently obj is
active object so can't be garbage collected.

obj = null; //'obj' object is no longer referencing to the instance. So the 'MyClass type object
is now available for garbage collection.

// Java program to illustrate Strong reference


class Geeks
{
//Code..
}
public class Example
{
public static void main(String[] args)
{
//Strong Reference - by default
Geeks g = new Geeks();

//Now, object to which 'g' was pointing earlier is


//eligible for garbage collection.
g = null;
}
}
JAVA

2. Weak References

Weak Reference Objects are not the default type/class of Reference Object and they should
be explicitly specified while using them.

//Java Code to illustrate Weak reference


import [Link];
class Gfg
{
//code
public void x()
{
[Link]("GeeksforGeeks");
}
}

public class Geeks


{
public static void main(String[] args)
{
// Strong Reference
JAVA

Gfg g = new Gfg();


g.x();

// Creating Weak Reference to Gfg-type object to which 'g'


// is also pointing.
WeakReference<Gfg> weakref = new WeakReference<Gfg>(g);

//Now, Gfg-type object to which 'g' was pointing earlier


//is available for garbage collection.
//But, it will be garbage collected only when JVM needs memory.
g = null;

// You can retrieve back the object which


// has been weakly referenced.
// It successfully calls the method.
g = [Link]();

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

//Code to illustrate Soft reference


import [Link];
class Gfg
{
public void x()
{
[Link]("GeeksforGeeks");
}
}

public class Geeks


{
public static void main(String[] args)
{
// Strong Reference
Gfg g = new Gfg();
g.x();

// Creating Soft Reference to Gfg-type object to which 'g'


// is also pointing.
SoftReference<Gfg> softref = new SoftReference<Gfg>(g);

// Now, Gfg-type object to which 'g' was pointing


// earlier is available for garbage collection.
g = null;
JAVA

// You can retrieve back the object which


// has been weakly referenced.
// It successfully calls the method.
g = [Link]();

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:

//Code to illustrate Phantom reference


import [Link].*;

class Gfg
{
//code
public void x()
{
[Link]("GeeksforGeeks");
}
}

public class Geeks


{
JAVA

public static void main(String[] args)


{
//Strong Reference
Gfg g = new Gfg();
g.x();

//Creating reference queue


ReferenceQueue<Gfg> refQueue = new ReferenceQueue<Gfg>();

//Creating Phantom Reference to Gfg-type object to which 'g'


//is also pointing.
PhantomReference<Gfg> phantomRef = null;

phantomRef = new PhantomReference<Gfg>(g,refQueue);

//Now, Gfg-type object to which 'g' was pointing


//earlier is available for garbage collection.
//But, this object is kept in 'refQueue' before
//removing it from the memory.
g = null;

//It always returns null.


g = [Link]();

//It shows NullPointerException.


g.x();
}
}

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.

Creating Custom Packages


Step 1: Create a directory in which we create our packages and Java files.

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];

// Main class present inside the package


public class TwoPointers {

public static void main(String[] args) {


JAVA

[Link]("Inside the package");


}
}

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

Working of Java Packages

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.

Accessing Classes Inside a Package

In Java, we can import classes from a package using either of the following methods:

1. Import a specific class:

import [Link];
JAVA

This imports only the Vector class from the [Link] package.

2. Import all classes from a package:

import [Link].*;
This imports all classes and interfaces from the [Link] package but does not include sub-
packages.

Example: Import the Vector class

import [Link];

public class Geeks {

public Geeks() {

// [Link] is imported, We are able to access it directly in our code.


Vector v = new Vector();

[Link] l = new [Link]();


[Link](3);
[Link](5);
[Link](7);

[Link](l);
}

public static void main(String[] args) {

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];

Types of Java Packages

• 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:

• [Link]: Contains language support classes(e.g classes which defines primitive


data types, math operations). This package is automatically imported.
• [Link]: Contains classes for supporting input / output operations.
• [Link]: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
• [Link]: Contains classes for creating Applets.
• [Link]: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc). 6)
• [Link]: Contain classes for supporting networking operations.

2. User-defined Packages

These are the packages that are defined by the user.

1. Create the Package:

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;

public class MyClass


{
public void getNames(String s)
{
[Link](s);
}
}

2. Use the Class in Program:

Now we will use the MyClass class in our program.

import [Link];

public class Geeks {


public static void main(String args[]) {

// Initializing the String variable with a value


String s = "GeeksforGeeks";

// Creating an instance of class MyClass in the package.


MyClass o = new MyClass();

[Link](s);
}
}

Note: [Link] must be saved inside the myPackage directory since it is a part of the
package.

Static Import In Java

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:

import static [Link].*;

class Geeks {
public static void main(String args[]) {

// We don't need to use '[Link]' as imported using static.


[Link]("GeeksforGeeks");
}
}

Output
GeeksforGeeks

Handling Name Conflicts

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:

[Link] deadLine = new [Link]();


[Link] today = new [Link]();
JAVA

Directory Structure and CLASSPATH

Package names correspond to a directory structure. For example, a class


Circle in package [Link].project1.subproject2 is stored as:

$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

CLASSPATH can be set by any of the following ways:

• CLASSPATH can be set permanently in the environment the steps In


Windows is
Go to Control Panel -> System -> Advanced -> Environment Variables.
• Select "System Variables" to apply the CLASSPATH for all users on
the system.
• Select "User Variables" to apply it only for the currently logged -
in user.
• Edit or Create CLASSPATH : If CLASSPATH already exists, select it
and click "Edit" or If it doesn't exist, click "New"
• Enter CLASSPATH Details: In the "Variable name" field, enter:
"CLASSPATH", In the "Variable value" field, enter the directories
and JAR files separated by semicolons.
• In the "Variable value" field, enter the directories and JAR files
separated by semicolons. Example:
.c:\javaproject\classes;d:\tomcat\lib\[Link]
• The dot (.) represents the current working directory.
• To check the current setting of the CLASSPATH, issue the following
command:
JAVA

> SET CLASSPATH


CLASSPATH can be set temporarily for that particular CMD shell session
by issuing the following command:

> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\[Link]


Instead of using the CLASSPATH environment variable, you can also use
the command-line option -classpath or -cp of the javac and java commands,
for example,

> java –classpath c:\javaproject\classes


[Link].project1.subproject2.MyClass3
Illustration of user-defined packages: Creating our first package: File
name – [Link]

package package_name;

public class ClassOne {


public void methodClassOne()
{
[Link]("Hello there its ClassOne");
}
}

Creating our second package: File name – [Link]

package package_one;

public class ClassTwo {


public void methodClassTwo()
{
[Link]("Hello there i am ClassTwo");
}
}

Making use of both the created packages: File name – [Link]

import package_name.ClassOne;
import package_one.ClassTwo;

public class Testing {


JAVA

public static void main(String[] args)


{
ClassTwo a = new ClassTwo();
ClassOne b = new ClassOne();
[Link]();
[Link]();
}
}

Now having a look at the directory structure of both the packages and
the testing class file:

Access Modifiers in the Context of Packages

• 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

Built-in Packages in Java


In Java, Built-in packages are predefined libraries provided by the Java Development Kit (JDK)
that contain a wide range of classes and interfaces to perform common tasks such as
input/output operations, data structures, networking, database connectivity a nd more.
These packages help developers avoid writing code from scratch by offering ready-to-use
functionalities and are organized under the java and javax namespaces.

Hierarchical Structure of Java Packages


The image below demonstrates the hierarchical structure of Java packages and their related
class files.

Examples of Built-in Packages

• [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

• [Link]: Contains the collections framework, some internationalization support


classes, properties, random number generation classes. Classes like ArrayList,
LinkedList, HashMap, Calendar, Date, Time Zone, etc. are part of this package.
• [Link]: Provides classes for implementing networking applications. Classes like
Authenticator, HTTP Cookie, Socket, URL, URLConnection, URLEncoder,
URLDecoder, etc. are part of this package.
• [Link]: Provides classes for system input/output operations. Classes like
BufferedReader, BufferedWriter, File, InputStream, OutputStream, PrintStream,
Serializable, etc. are part of this package.
• [Link]: Contains classes for creating user interfaces and for painting graphics and
images. Classes like Button, Color, Event, Font, Graphics, Image, etc. are part of this
package.
Now, we are going to discuss each one with particula example in detail.

1. [Link] Package

This package provides APIs for database operations using JDBC (Java Database
Connectivity).

Example:

import [Link].*;

public class Geeks {

static final String URL = "jdbc:mysql://localhost/Geeksforgeeks";


static final String USER = "user";
static final String PASSWORD = "123";
static final String QUERY = "SELECT ID, NAME, ADDRESS FROM STUDENTS";

public static void main(String[] args) {


// Open a connection
try(
Connection con = [Link](URL, USER, PASSWORD);
Statement stm = [Link]();
ResultSet rs = [Link](QUERY);) {
JAVA

while ([Link]()) {
// Retrieving data from column name
[Link]("ID: " + [Link]("id"));
[Link](",NAME: " + [Link]("name"));
[Link](",ADDRESS: " + [Link]("address"));
}
} catch (SQLException e) {
[Link]();
}
}
}

Output

ID: 1, NAME: Harry, ADDRESS: India


ID: 2, NAME: Jhon, ADDRESS: USA
ID: 3, NAME: Kim, ADDRESS: USA
ID: 4, NAME: Bob, ADDRESS: India

Explanation:

• We can see that first, we imported the package name [Link].*,


• In the main method, we initialize the string variable name URL,
USER, PASSWORD, QUERY.
• And then use DriverManager to get a connection to the database and
finally, we use the executeQuery method to execute the query of
selecting the data from the database.

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

public class Geeks {


public static void main(String[] args) {
int a = 100, b = 200;
int maxi = [Link](a, b);
[Link]("Maximum is = %d%n", maxi);
}
}

OutputMaximum is = 200
Explanation:

In the above-mentioned example,

• 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

This package provides utility classes such as collections, date/time and


array manipulation tools. The most common class in this package is Arrays
which is generally used by programmers in various cases. We can say that
it is the most useful package for java because it helps to achieve
different types of requirements easily by using pre -written classes.

Let's see the example of Arrays class.

Example:

import [Link];

public class Geeks {


public static void main(String[] args) {
int[] arr = { 40, 30, 20, 70, 80 };
JAVA

[Link](arr);
[Link]("Sorted Array is = " + [Link](arr));
}
}

Output:

Sorted Array is = [20, 30, 40, 70, 80]

Explanation:

• We used [Link] package and Arrays class to sort the integer


array.
• First, we created an integer type array that consists of elements
40,30,20,70,80 and sort the array using the "sort" function of the
Arrays class.
• After sorting an array it prints the sorted array.

4. [Link] Package

This package provides classes and an interface for handling the


system(input/output). Using these classes programmer can take the input
from the user and do operations on that and then display the output to
the user. Other than this we can also perform file handling read or write
using classes of this package.

Example:

import [Link];

public class Geeks {


public static void main(String[] args) {
Console cons = [Link]();
if (cons != null) {
[Link]("Enter your favorite color:");
String colour = [Link]();
[Link]("Favorite colour is " + colour);
} else {
[Link]("Console not available.");
}
}
JAVA

Output

Enter your favorite color


RED
Favorite color is RED

Explanation: In the above-mentioned example,

• 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];

public class Geeks {


public static void main(String[] args) throws IOException {
int port_no = 4567;
DatagramSocket ds = new DatagramSocket(port_no);
byte[] receive = new byte[65535];

DatagramPacket DpReceive;
while (true) {
JAVA

DpReceive = new DatagramPacket(receive, [Link]);


[Link](DpReceive);
[Link]("DATA:- " + data(receive));
receive = new byte[65535];
}
}
public static String data(byte[] a) {
if (a == null) return null;
StringBuilder ret = new StringBuilder();
int i = 0;
while (a[i] != 0) {
[Link]((char) a[i]);
i++;
}
return [Link]();
}
}

Output:

DATA:- //whatever to get from server

Explanation:

• Here we have implemented a UDP socket receiver that receives data


from the server-side through port no.
• First, we created a socket using the DatagramSocket method to
listen on port no 4567, second, we created a datagram packet to
receive the data in byte buffer and then finally after getting the
data we printed it.

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

public class Geeks {


AWTExample() {
Frame fr1 = new Frame();
Label la = new Label("Welcome to Java Graphics - GEEKSFORGEEKS");
[Link](la);
[Link](300, 200);
[Link](true);
}

public static void main(String[] args) {


new AWTExample();
}
}

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.

Naming Conventions in Java


Writing clean, readable and maintainable code is essential, especially in large projects.
Naming conventions play a key role by making the purpose of variables, classes, methods
and constants clear. This article covers best practices for naming conventions in Java.
JAVA

Why Naming Conventions are Important

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

Types of Java Naming Conventions

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.

1. Classes and Interfaces

• 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.

public static void main(String [] args) {}


Note: As the name suggests the method is supposed to be primarily method which
indeed it is as main() method in java is the method from where the program begins its
execution.

3. Variables

Variable names should be short yet meaningful.

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;

double double answer,


Note: As the name suggests one stands for marks while the other for an answer be it of
any e do not mind.
JAVA

4. Constant variables

• Should be written in all uppercase, with words separated by underscores (e.g.,


MAX_SIZE, PI_VALUE)
• Common constants are found in classes like Float, Long, String, etc.
final double PI = 3.14159;
double num = PI;

5. Packages

• The prefix of a unique package name is always written in all-lowercase ASCII


letters and should be one of the top-level domain names, like com, edu, gov, mil,
net, org.
• Subsequent components of the package name vary according to an organization's
own internal naming conventions.
[Link] ;
[Link].*;
As the name suggests in the first case we are trying to access the Scanner class from the
[Link] package and in other all classes(* standing for all) input-output classes making it
so easy for another programmer to identify.

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.

User-Defined Packages in Java


User-defined packages are those packages that are designed or created by the developer to
categorize classes and packages. It can be imported into other classes and used in the same
way as we use built-in packages. But if we omit the package statement, the class names are
put into the default package, which has no name.

To create a package, we're supposed to use the package keyword.

Syntax:

package package-name;
JAVA

Steps to Create User-defined Packages


Step 1: Creating a package in a Java class. The format is very simple and easy. Just write a
package by following its name.

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 {

public void show()


{
[Link]("Hello geeks!! How are you?");
}
JAVA

public static void main(String args[])


{
Geeks obj = new Geeks();
[Link]();
}
}

Output:

Hello geeks!! How are you?


Example 2: In the below-mentioned example, we will import the user-defined package
"example" created in the above example. And use the function to print messages.

import [Link];

public class Test {


public static void main(String args[])
{
Geeks obj = new Geeks();
[Link]();
}
}

Output:

Hello geeks!! How are you?


Explanation:

• A user-defined package example contains a class Geeks.


• Geeks class has a show() method that prints "Hello geeks!! How are you?".
• Another program imports the example package and calls the show() method.
• Both programs display the same greeting, showing successful package reuse
JAVA

Online Quiz System in Java


Before moving further, let's first understand how this system is going to work.

• The quiz contains multiple-choice questions.


• Each question has four options.
• The user is going to select an option as their answer.
• The program will record the answer and check, if it is correct or not and then
accordingly calculate the score.
• In the end, it will show the total score.

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];

public interface Quiz {


void start();
void submitAnswer(int questionIndex, String answer);
void showResults();
}

2. Question Model Class

This class holds the question data.

[Link]:

package [Link];

public class Question {


private String questionText;
private String[] options;
private String correctAnswer;

public Question(String questionText, String[] options, String correctAnswer) {


[Link] = questionText;
[Link] = options;
[Link] = correctAnswer;

}
public String getQuestionText() {
return questionText;
}

public String[] getOptions() {


JAVA

return options;
}

public String getCorrectAnswer() {


return correctAnswer;
}
}

package [Link];

import [Link];
import [Link];

import [Link];

public class QuizService implements Quiz {


private Question[] questions;
private String[] userAnswers;
private int score = 0;

public QuizService(Question[] questions) {


[Link] = questions;
[Link] = new String[[Link]];
}

@Override
public void start() {
Scanner scanner = new Scanner([Link]);

[Link]("Welcome to the Online Quiz!");


for (int i = 0; i < [Link]; i++) {
[Link]("\nQ" + (i + 1) + ": " + questions[i].getQuestionText());

String[] options = questions[i].getOptions();


for (int j = 0; j < [Link]; j++) {
[Link]((j + 1) + ". " + options[j]);
}
JAVA

[Link]("Enter your answer (1-" + [Link] + "): ");


String input = [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];

public class Main {


public static void main(String[] args) {

Question[] questions = new Question[] {


new Question("What is the size of an int data type in Java??",
new String[] {"8 bit", "16 bit", "32 bit", "64 bit"}, "32 bit"),

new Question("Which method is the entry point of a Java program?",


new String[] {"start()", "main()", "run()", "init()"}, "main()"),

new Question("Which of these is NOT a valid access modifier in Java?",


new String[] {"public", "private", "protected", "package"}, "package"),
};

QuizService quiz = new QuizService(questions);

[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).

You might also like