DEV Community

SILAMBARASAN A
SILAMBARASAN A

Posted on

Pojo in Java

POJO in Java – What and Why?

In Java, POJO stands for Plain Old Java Object.

A POJO is a simple Java class that is not dependent on any special framework, API, or technology.

It is mainly used to store and manage data in a clean and organized way.


What is a POJO?

A POJO class usually contains:

  • Private variables (fields)
  • Getter and Setter methods
  • Constructors
  • Optional business methods

Example of a POJO Class

public class Student {

    private int id;
    private String name;

    // Default Constructor
    public Student() {
    }

    // Parameterized Constructor
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getter
    public int getId() {
        return id;
    }

    // Setter
    public void setId(int id) {
        this.id = id;
    }

    // Getter
    public String getName() {
        return name;
    }

    // Setter
    public void setName(String name) {
        this.name = name;
    }
}
Enter fullscreen mode Exit fullscreen mode

This is called a POJO class because:

  • It is a normal Java object
  • No framework dependency
  • Used mainly for storing data

Why Do We Use POJO?

1. To Store Data Properly

Instead of using many separate variables:

int id = 1;
String name = "Silambu";
Enter fullscreen mode Exit fullscreen mode

We group them into one object:

Student s = new Student();
Enter fullscreen mode Exit fullscreen mode

This makes code cleaner and easier to manage.


2. Improves Code Readability

POJO helps organize related data together.

Without POJO:

id, name, age, address
Enter fullscreen mode Exit fullscreen mode

With POJO:

Student object
Enter fullscreen mode Exit fullscreen mode

Easy to understand.


3. Reusability

One POJO class can be reused in:

  • Controllers
  • Services
  • Database operations
  • APIs
  • JSON conversion

4. Easy Database Mapping

Frameworks like:

  • Hibernate
  • JPA
  • Spring Boot

use POJO classes to map database tables into Java objects.

Example:

Database Column POJO Field
student_id id
student_name name

5. Easy JSON Conversion

POJO objects can easily convert to:

  • JSON
  • XML

Example:

{
  "id": 1,
  "name": "Silambu"
}
Enter fullscreen mode Exit fullscreen mode

Real-Life Example

Think of a POJO like a student form.

A form contains:

  • Name
  • Age
  • Roll Number

Similarly, a POJO stores related data together inside one class.


Important Characteristics of POJO

A POJO:

  • Does not extend special classes
  • Does not implement unnecessary interfaces
  • Has private fields
  • Uses getters/setters
  • Is simple and independent

POJO vs Normal Variable

Normal Variables

String name;
int age;
Enter fullscreen mode Exit fullscreen mode

Data is separate.


POJO

Student s;
Enter fullscreen mode Exit fullscreen mode

All related data is grouped together.

Top comments (0)