Showing posts with label LLD. Show all posts
Showing posts with label LLD. Show all posts

Student Management System LLD Using Java: Complete Beginner's Guide

Student Management System LLD Using Java: Complete Beginner's Guide

Imagine an interviewer asks you: "Design a Student Management System using Java."

What would you do first? Create a Student class? Write a service? Start adding methods?

Many beginners immediately start writing code without understanding the requirements or deciding which classes are actually needed.

That is exactly what we want to improve through Low-Level Design (LLD).

In this tutorial, we will design a simple Student Management System from scratch. We will identify the requirements, find the main entities, create a UML class diagram, understand class relationships and implement the complete application using Java.

You do not need previous LLD experience. Basic Java knowledge is enough to follow along.

What you will build: A Java application that can add students, search students, update student details, delete students and display all registered students.


1. What Are We Building?

A Student Management System is an application used to manage student information in an educational institution.

For example, a college may need to store the following information:

  • Student ID
  • Student name
  • Email address
  • Age
  • Course name

Instead of maintaining this information manually, we can create an application that manages student records.

Example scenario

Suppose a college has three students:

Student ID Name Email Age Course
101 Rahul rahul@example.com 22 Java
102 Priya priya@example.com 23 Spring Boot
103 Aman aman@example.com 24 Python

Our application should allow an administrator to manage these records through simple operations.

Features we will implement

  1. Add a new student.
  2. Find a student using the student ID.
  3. Display all students.
  4. Update student information.
  5. Delete a student record.

We will first build a console-based Java application. This keeps the focus on LLD instead of introducing web APIs, databases or framework configuration too early.

2. Understand the Requirements Before Writing Code

The first step in any LLD interview problem is understanding what the application should do.

Do not start creating classes immediately. First write down the requirements.

Functional requirements

Functional requirements describe what the application must do.

Operation Description
Add StudentRegister a new student.
Find StudentSearch for a student by ID.
Get All StudentsDisplay all registered students.
Update StudentChange an existing student's details.
Delete StudentRemove a student record.

Basic business rules

Now we need to define a few rules that make the application behave correctly.

  • Student ID must be unique.
  • Student name cannot be empty.
  • Email must not be empty and must have a valid basic email format.
  • Age must be greater than zero.
  • A student must exist before their details can be updated.
  • A student must exist before their record can be deleted.
  • Searching for an unknown ID should return a clear result.

These rules will guide our class design and implementation.

What is outside our initial scope?

To keep the first version beginner-friendly, we will not implement login, role management, attendance, marks, fee payments or database integration.

These can be added later when we extend the design.

3. Identify the Main Classes

Once the requirements are clear, the next step is identifying the main objects and responsibilities.

Read the requirements again and identify the important nouns and actions.

For our Student Management System, the main object is clearly Student.

But should the Student class also handle searching, updating, deleting and storing every student?

No. We should separate these responsibilities.

Classes and their responsibilities

Class Responsibility
Student Stores student information.
StudentRepository Defines operations for storing and retrieving students.
InMemoryStudentRepository Implements student storage using a Java Map.
StudentService Handles student business logic and validation.
Main Starts the application and demonstrates its functionality.

Why do we need separate classes?

Imagine we put all operations inside the Student class:

class Student {

    void addStudent() {
        // Add student
    }

    void updateStudent() {
        // Update student
    }

    void deleteStudent() {
        // Delete student
    }

    void findStudent() {
        // Find student
    }
}

This class now has multiple responsibilities. It represents a student, manages student records and performs business operations.

As the application grows, this approach becomes difficult to maintain.

Instead, we separate data, business logic and storage responsibilities.

4. Understand the Application Architecture

Before implementing the classes, let's understand how they communicate.

When a user wants to add a student, the flow will be:

  1. The Main class creates the required objects.
  2. Main calls StudentService.
  3. StudentService validates the student details.
  4. StudentService calls StudentRepository.
  5. InMemoryStudentRepository stores the student.
Student Management System architecture Main communicates with StudentService. StudentService uses the StudentRepository interface, implemented by InMemoryStudentRepository, which stores Student objects in a map. Main StudentService <<interface>> StudentRepository InMemoryStudentRepository Stores Student objects Student Student information
Figure 1: A simplified architecture showing how the application components interact.

Important: The StudentRepository interface defines the storage contract. The InMemoryStudentRepository class provides one implementation of that contract.

Today, we use a Java Map. Later, we can replace it with a database-backed implementation without changing the business logic significantly.

5. UML Class Diagram for Student Management System

A UML class diagram helps us visualize the classes, their attributes, methods and relationships before writing the code.

Here is a simplified view of our design.

Student Management System UML class diagram StudentService depends on StudentRepository. InMemoryStudentRepository implements StudentRepository and stores Student records. Student has ID, name, email and age attributes. StudentService - repository + addStudent() + findStudent() / updateStudent() <<interface>> StudentRepository + save() + findById() / findAll() InMemoryStudentRepository - students: Map + save() + findById() / deleteById() Student - id: int - name: String - email: String - age: int Uses Student
Figure 2: Simplified UML class diagram of the Student Management System.

Understand the relationships

  • StudentService depends on StudentRepository: It uses the repository to store and retrieve records.
  • InMemoryStudentRepository implements StudentRepository: It provides the actual storage operations.
  • Repository works with Student objects: It stores and retrieves student records.

This design separates business logic from the way student data is stored.

6. Create the Java Project Structure

Now let's organize our application into packages.

You can create a simple Java project in IntelliJ IDEA, Eclipse or any other Java IDE.

Recommended project structure

student-management-system
    |
    +--- src
         |
         +--- main
              |
              +--- java
                   |
                   +--- com
                        |
                        +--- example
                             |
                             +--- student
                                  |
                                  +--- model
                                  |    |
                                  |    +--- Student.java
                                  |
                                  +--- repository
                                  |    |
                                  |    +--- StudentRepository.java
                                  |    +--- InMemoryStudentRepository.java
                                  |
                                  +--- service
                                  |    |
                                  |    +--- StudentService.java
                                  |
                                  +--- Main.java

Why do we use packages?

Packages help organize related classes and make the project easier to navigate.

  • model: Contains the Student class.
  • repository: Contains storage contracts and implementations.
  • service: Contains application business logic.
  • Main.java: Starts the application.

For this example, no external library or database dependency is required. A Java 17 JDK is sufficient.

7. Complete Java Implementation

Let's implement each class one by one.

Step 1: Create Student.java

The Student class represents a student record. It contains the student's ID, name, email and age.

We keep the fields private to protect the internal state and use a constructor to create valid student objects.

package com.example.student.model;

public class Student {

    private final int id;
    private String name;
    private String email;
    private int age;

    public Student(
            int id,
            String name,
            String email,
            int age) {

        if (id <= 0) {
            throw new IllegalArgumentException(
                "Student ID must be positive"
            );
        }

        this.id = id;
        setName(name);
        setEmail(email);
        setAge(age);
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {

        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException(
                "Student name cannot be empty"
            );
        }

        this.name = name.trim();
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {

        if (email == null ||
                !email.matches("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$")) {

            throw new IllegalArgumentException(
                "Invalid email address"
            );
        }

        this.email = email.trim();
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {

        if (age <= 0) {
            throw new IllegalArgumentException(
                "Age must be greater than zero"
            );
        }

        this.age = age;
    }

    @Override
    public String toString() {

        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

Why is the ID final? In this example, the student ID is assigned when the object is created and cannot be changed later. This avoids accidental modification of the record's identity.

Why do we validate inside the class? The Student object should not be created with invalid basic data. These checks protect the object's state regardless of which class creates it.

The email check is intentionally basic. Production applications should use appropriate validation rules and verify email ownership where required.

Step 2: Create StudentRepository.java

Now we need a way to store and retrieve student information.

Instead of directly connecting StudentService to a Java Map, we define an interface.

package com.example.student.repository;

import com.example.student.model.Student;

import java.util.List;
import java.util.Optional;

public interface StudentRepository {

    Student save(Student student);

    Optional<Student> findById(int id);

    List<Student> findAll();

    boolean existsById(int id);

    boolean deleteById(int id);
}

This interface defines the operations required by our application.

Notice that findById() returns an Optional. This makes the possibility of a missing student explicit instead of returning null.

Step 3: Create InMemoryStudentRepository.java

Now we implement the repository using a Java HashMap.

A Map stores data as key-value pairs. We will use the student ID as the key and the Student object as the value.

package com.example.student.repository;

import com.example.student.model.Student;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class InMemoryStudentRepository
        implements StudentRepository {

    private final Map<Integer, Student> students =
            new HashMap<>();

    @Override
    public Student save(Student student) {

        students.put(student.getId(), student);

        return student;
    }

    @Override
    public Optional<Student> findById(int id) {

        return Optional.ofNullable(students.get(id));
    }

    @Override
    public List<Student> findAll() {

        return new ArrayList<>(students.values());
    }

    @Override
    public boolean existsById(int id) {

        return students.containsKey(id);
    }

    @Override
    public boolean deleteById(int id) {

        return students.remove(id) != null;
    }
}

Why use HashMap?

  • It stores student records using a unique ID as the key.
  • It provides convenient lookup by ID.
  • It keeps the example simple without requiring database configuration.

For this beginner example, we assume the application runs in a single thread. HashMap is not a thread-safe storage solution. A real multi-user application needs suitable persistence and concurrency handling.

Step 4: Create StudentService.java

This is where the main business logic lives.

StudentService uses the repository to manage student records. It checks business rules before performing operations.

package com.example.student.service;

import com.example.student.model.Student;
import com.example.student.repository.StudentRepository;

import java.util.List;

public class StudentService {

    private final StudentRepository studentRepository;

    public StudentService(
            StudentRepository studentRepository) {

        this.studentRepository = studentRepository;
    }

    public Student addStudent(Student student) {

        if (studentRepository.existsById(student.getId())) {

            throw new IllegalArgumentException(
                "Student ID already exists: " + student.getId()
            );
        }

        return studentRepository.save(student);
    }

    public Student getStudentById(int id) {

        return studentRepository.findById(id)
                .orElseThrow(() ->
                    new IllegalArgumentException(
                        "Student not found with ID: " + id
                    )
                );
    }

    public List<Student> getAllStudents() {

        return studentRepository.findAll();
    }

    public Student updateStudent(
            int id,
            String name,
            String email,
            int age) {

        Student student = getStudentById(id);

        student.setName(name);
        student.setEmail(email);
        student.setAge(age);

        return studentRepository.save(student);
    }

    public void deleteStudent(int id) {

        boolean deleted = studentRepository.deleteById(id);

        if (!deleted) {

            throw new IllegalArgumentException(
                "Student not found with ID: " + id
            );
        }
    }
}

Understand the important methods

addStudent(): Checks whether the student ID already exists before saving the student.

getStudentById(): Finds a student and throws a clear exception when the ID does not exist.

getAllStudents(): Returns all registered students.

updateStudent(): Finds the existing student, validates the new values through the Student setters and saves the updated object.

deleteStudent(): Removes the student record and reports an error if no record exists.

Notice that StudentService does not know whether the records are stored in a HashMap, MySQL or another storage system. It only depends on the StudentRepository interface.

Step 5: Create Main.java

Finally, we need an entry point to create our objects and execute the application.

package com.example.student;

import com.example.student.model.Student;
import com.example.student.repository.InMemoryStudentRepository;
import com.example.student.repository.StudentRepository;
import com.example.student.service.StudentService;

public class Main {

    public static void main(String[] args) {

        StudentRepository repository =
                new InMemoryStudentRepository();

        StudentService studentService =
                new StudentService(repository);

        // Add students
        studentService.addStudent(
                new Student(
                    101,
                    "Rahul",
                    "rahul@example.com",
                    22
                )
        );

        studentService.addStudent(
                new Student(
                    102,
                    "Priya",
                    "priya@example.com",
                    21
                )
        );

        // Display all students
        System.out.println("All Students:");

        studentService.getAllStudents()
                .forEach(System.out::println);

        // Find student
        System.out.println("\nFind Student:");

        System.out.println(
                studentService.getStudentById(101)
        );

        // Update student
        System.out.println("\nUpdate Student:");

        studentService.updateStudent(
                101,
                "Rahul Singh",
                "rahul.singh@example.com",
                23
        );

        System.out.println(
                studentService.getStudentById(101)
        );

        // Delete student
        System.out.println("\nDelete Student:");

        studentService.deleteStudent(102);

        // Display remaining students
        System.out.println("\nRemaining Students:");

        studentService.getAllStudents()
                .forEach(System.out::println);
    }
}

We have now implemented the complete basic Student Management System.

8. Run the Application and Check the Output

Run the Main class from your IDE or compile and execute the project from the command line.

For a simple project, you can compile all Java files using your IDE. The application's entry point is com.example.student.Main.

Expected output

All Students:
Student{id=101, name='Rahul', email='rahul@example.com', age=22}
Student{id=102, name='Priya', email='priya@example.com', age=21}

Find Student:
Student{id=101, name='Rahul', email='rahul@example.com', age=22}

Update Student:
Student{id=101, name='Rahul Singh', email='rahul.singh@example.com', age=23}

Delete Student:

Remaining Students:
Student{id=101, name='Rahul Singh', email='rahul.singh@example.com', age=23}

Note: The records are stored in memory. When the application stops, the data is lost. We will discuss how to replace this storage with a database later.

What happens if we add the same ID twice?

Our StudentService checks whether the ID already exists.

studentService.addStudent(
    new Student(101, "Rahul", "rahul@example.com", 22)
);

studentService.addStudent(
    new Student(101, "Aman", "aman@example.com", 23)
);

The second operation throws:

IllegalArgumentException:
Student ID already exists: 101

This demonstrates why business validation should be performed before saving a record.

9. Understand the LLD Decisions Behind This Project

Now that the code works, let's understand the design decisions. This is the most important part of an LLD exercise.

Why did we create a Student class?

Because a student is an important domain object in our application. The class represents student information and protects its basic state through validation.

Why did we create StudentRepository?

Because the service should not be tightly coupled to a specific storage implementation.

Today, we use InMemoryStudentRepository. Later, we could create a database implementation that uses JDBC or Spring Data JPA.

Why did we create StudentService?

Because business rules should not be mixed with storage operations or the application's entry point.

Why did we use constructor injection?

public StudentService(
        StudentRepository studentRepository) {

    this.studentRepository = studentRepository;
}

The service receives its dependency from outside instead of creating the repository internally.

This makes the service easier to test and allows us to replace the repository implementation.

Why did we use Optional?

A student may not exist for a requested ID. Optional makes this possibility explicit and allows the service to handle the missing result.

What is the advantage of this design?

Imagine the college now wants to store student records in MySQL instead of a HashMap.

We can create another class called MySqlStudentRepository that implements StudentRepository. The service can then receive that implementation instead.

The business operations do not need to be rewritten simply because the storage mechanism changes.

10. SOLID Principles Used in This Project

Let's connect our Student Management System to the SOLID principles introduced in the previous LLD article.

1. Single Responsibility Principle (SRP)

Each class has a focused responsibility:

  • Student manages student information.
  • StudentService handles business operations.
  • StudentRepository defines storage operations.
  • InMemoryStudentRepository implements storage.

2. Open/Closed Principle (OCP)

We can introduce another StudentRepository implementation without rewriting StudentService, as long as the new implementation follows the same contract.

3. Liskov Substitution Principle (LSP)

Any implementation of StudentRepository should correctly support the behavior promised by its interface. A replacement should not unexpectedly break the service's expected behavior.

4. Interface Segregation Principle (ISP)

Our repository interface contains a small set of operations relevant to student storage. We do not force unrelated functionality into it.

5. Dependency Inversion Principle (DIP)

StudentService depends on StudentRepository, an abstraction, rather than depending directly on InMemoryStudentRepository.

These principles help us keep the application organized and easier to extend.

11. How Can We Convert This Design into a Spring Boot Application?

In a real Java backend project, we may expose Student Management operations through REST APIs and store records in a database.

The same basic design can be used in Spring Boot.

Possible Spring Boot architecture

student-management
    |
    +--- controller
    |       |
    |       +--- StudentController.java
    |
    +--- service
    |       |
    |       +--- StudentService.java
    |
    +--- repository
    |       |
    |       +--- StudentRepository.java
    |
    +--- entity
    |       |
    |       +--- Student.java
    |
    +--- dto
    |       |
    |       +--- StudentRequest.java
    |       +--- StudentResponse.java
    |
    +--- exception
            |
            +--- GlobalExceptionHandler.java

Example REST API endpoints

HTTP Method Endpoint Purpose
POST/api/studentsAdd a student
GET/api/studentsGet all students
GET/api/students/{id}Find a student
PUT/api/students/{id}Update a student
DELETE/api/students/{id}Delete a student

In Spring Boot, the controller receives HTTP requests, the service handles business rules and the repository communicates with the database.

For database persistence, we could use Spring Data JPA and MySQL. We would also normally introduce request and response DTOs so that API contracts are separate from database entities.

Important: This is the next extension of our design. Our current console application intentionally uses in-memory storage so that beginners can first understand the LLD fundamentals.

12. Possible Future Improvements

Our current implementation covers the basic requirements. But a real Student Management System may need many more features.

Here are some improvements you can introduce as you become more comfortable with LLD.

Beginner improvements

  • Add a search option by student name.
  • Prevent duplicate email addresses.
  • Add course information.
  • Display students sorted by name.
  • Add a menu-driven console interface.

Intermediate improvements

  • Replace HashMap storage with MySQL.
  • Add Spring Boot REST APIs.
  • Introduce request and response DTOs.
  • Add pagination and sorting.
  • Add unit tests using JUnit and Mockito.
  • Add centralized exception handling.

Advanced improvements

  • Add student enrollment and course management.
  • Add role-based access control.
  • Introduce audit history for student updates.
  • Handle concurrent updates correctly.
  • Add attendance and examination modules.

Do not implement all these features immediately. Add them gradually and observe how the design changes when new requirements arrive.

13. Student Management System LLD Interview Questions

After implementing the project, try answering these questions without looking at the code.

Q1. Why did we create separate Student and StudentService classes?

Answer: Student represents student data, while StudentService handles business operations. Separating them keeps responsibilities clear.

Q2. Why did we create a StudentRepository interface?

Answer: It separates business logic from storage implementation and allows different storage implementations to be introduced.

Q3. Why did we use HashMap?

Answer: HashMap stores key-value pairs. Using student ID as the key makes it convenient to find a student by ID in this small in-memory example.

Q4. Why is student ID unique?

Answer: The ID identifies an individual student record. Duplicate IDs would make it impossible to distinguish records reliably.

Q5. What is dependency injection in this example?

Answer: StudentService receives a StudentRepository through its constructor rather than creating the repository internally.

Q6. How does this design follow the Single Responsibility Principle?

Answer: Student, StudentService and the repository implementation each have separate responsibilities.

Q7. How would you replace HashMap with MySQL?

Answer: Create a new database-backed repository implementation that follows the StudentRepository contract, then inject it into StudentService.

Q8. Why did we use Optional in findById()?

Answer: Optional makes it clear that a requested student may not exist and encourages explicit handling of that situation.

Q9. Is HashMap suitable for a production student management application?

Answer: Not as the main persistent storage. Its data is lost when the application stops, and a plain HashMap is not thread-safe. A real application would generally use a database and suitable transaction and concurrency controls.

Q10. What would you change if two students could have the same email?

Answer: First clarify the business requirement. If email must be unique, enforce the rule in the service and also use a database unique constraint in a persistent implementation.

Q11. How would you write unit tests for StudentService?

Answer: Use a test implementation or mock of StudentRepository to test adding, searching, updating, deleting and error scenarios independently of the storage layer.

Q12. How would you support multiple courses?

Answer: Introduce a Course entity and define the required relationship between Student and Course based on the business rules. For example, a student may enroll in multiple courses.

14. Practice Exercises: Test Your LLD Knowledge

Now it is your turn. Try completing these tasks without copying the implementation.

Exercise 1: Add student search by name

Create a method that searches students by name.

Think about:

  • Should the search be case-sensitive?
  • Should partial name matching be supported?
  • What should happen when no student matches?

Exercise 2: Prevent duplicate email addresses

Currently, we prevent duplicate student IDs. Extend the application to prevent duplicate emails.

Exercise 3: Add course management

Create a Course class with the following attributes:

  • Course ID
  • Course name
  • Course duration

Now decide whether a Student should have one Course or multiple Courses. Explain why you selected that relationship.

Exercise 4: Replace in-memory storage

Create a new repository implementation using a database. Keep the StudentService dependent on the repository abstraction.

Exercise 5: Write unit tests

Write tests for:

  • Adding a valid student.
  • Rejecting duplicate IDs.
  • Finding an existing student.
  • Handling a missing student.
  • Updating student details.
  • Deleting a student.

15. Final Thoughts

We started with a simple requirement: manage student records. From there, we identified the main classes, separated responsibilities, created a UML diagram and implemented a working Java application.

The most important lesson is not the number of classes we created. It is understanding why each class exists and how the classes communicate.

When you solve an LLD problem in an interview, remember this order:

  1. Understand the requirements.
  2. Identify the main entities.
  3. Assign responsibilities.
  4. Define class relationships.
  5. Create a UML diagram.
  6. Write clean Java code.
  7. Test normal and exceptional scenarios.

My advice: Do not stop after reading this article. Build the application yourself, add a new feature and see whether your existing design can support it without unnecessary changes.

That is how you start thinking like a software designer rather than only writing code.