Java Student Manager
A Java student manager is a console program that stores student records and lets you add, find, update, delete, rank and save them. It is the classic CRUD (Create, Read, Update, Delete) project, and almost every business application, from school portals to ERP systems, is built on the same pattern. This project brings together records, collections, streams, comparators and file handling.
It follows the Java Number Guess Game. You start with a single Student record and finish with student-manager.jar, a command-driven app that ranks students, prints grade statistics and keeps its data in a CSV file between runs. All examples were run on JDK 21.
Model a Student With a Java Record
A student has an id, a name and marks. A record is ideal for this kind of data class: Java generates the constructor, getters, equals, hashCode and toString for you, as explained in Java Records.
public class StudentRecord {
record Student(int id, String name, int marks) {
// compact constructor: runs before the fields are set
Student {
if (id <= 0) throw new IllegalArgumentException("id must be positive");
if (name == null || name.isBlank()) throw new IllegalArgumentException("name is required");
if (marks < 0 || marks > 100) throw new IllegalArgumentException("marks must be 0-100, got " + marks);
name = name.strip();
}
String grade() {
if (marks >= 90) return "A";
if (marks >= 75) return "B";
if (marks >= 60) return "C";
if (marks >= 40) return "D";
return "F";
}
Student withMarks(int newMarks) {
return new Student(id, name, newMarks); // records are immutable, so return a copy
}
}
public static void main(String[] args) {
Student asha = new Student(1, " Asha Kumar ", 92);
System.out.println(asha);
System.out.println(asha.name() + " has grade " + asha.grade());
Student updated = asha.withMarks(74);
System.out.println("Updated: " + updated + ", grade " + updated.grade());
System.out.println("Original unchanged: " + asha.marks());
System.out.println("Equal by value: " + asha.equals(new Student(1, "Asha Kumar", 92)));
try {
new Student(2, "Ravi", 105);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Student[id=1, name=Asha Kumar, marks=92]
Asha Kumar has grade A
Updated: Student[id=1, name=Asha Kumar, marks=74], grade C
Original unchanged: 92
Equal by value: true
Rejected: marks must be 0-100, got 105
How it works:
- The compact constructor
Student { ... }runs before the fields are assigned. It rejects bad data and cleans the name, so" Asha Kumar "is stored as"Asha Kumar". - Because every
Studentpasses through these checks, the rest of the program never meets a student with marks of 105 or an empty name. - Record fields are
final. To "change" marks,withMarksreturns a newStudentand the original stays the same. This makes records safe to share. grade()is calculated frommarkseach time, so the grade can never get out of step with the marks.
| Marks | Grade |
|---|---|
| 90-100 | A |
| 75-89 | B |
| 60-74 | C |
| 40-59 | D |
| 0-39 | F |
Store Students in a Repository (CRUD Operations)
A repository is a class that owns the data and offers simple methods to work with it. The final app uses this class, so the student manager's storage logic lives in one place.
package com.gocourse.students;
/** One student. Records give us the constructor, getters, equals, hashCode and toString. */
public record Student(int id, String name, int marks) {
public Student {
if (id <= 0) throw new IllegalArgumentException("id must be positive");
if (name == null || name.isBlank()) throw new IllegalArgumentException("name is required");
if (name.contains(",")) throw new IllegalArgumentException("name cannot contain a comma");
if (marks < 0 || marks > 100) throw new IllegalArgumentException("marks must be 0-100, got " + marks);
name = name.strip();
}
public String grade() {
if (marks >= 90) return "A";
if (marks >= 75) return "B";
if (marks >= 60) return "C";
if (marks >= 40) return "D";
return "F";
}
public Student withMarks(int newMarks) {
return new Student(id, name, newMarks);
}
public Student withName(String newName) {
return new Student(id, newName, marks);
}
}
The Student record used by the app is the same as before, with one more rule (no commas in names, because the save file uses commas) and a withName method.
package com.gocourse.students;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;
/** Keeps students in memory, keyed by id, in the order they were added. */
public class StudentRepository {
private final Map<Integer, Student> students = new LinkedHashMap<>();
private int nextId = 1;
/** Creates a student with the next free id. */
public Student add(String name, int marks) {
Student student = new Student(nextId, name, marks);
students.put(student.id(), student);
nextId++;
return student;
}
/** Adds a student that already has an id, for example one loaded from a file. */
public void put(Student student) {
students.put(student.id(), student);
nextId = Math.max(nextId, student.id() + 1);
}
public Optional<Student> findById(int id) {
return Optional.ofNullable(students.get(id));
}
public Student update(Student changed) {
if (!students.containsKey(changed.id())) {
throw new IllegalArgumentException("No student with id " + changed.id());
}
students.put(changed.id(), changed);
return changed;
}
public boolean remove(int id) {
return students.remove(id) != null;
}
public List<Student> findAll() {
return List.copyOf(students.values());
}
public List<Student> searchByName(String text) {
String needle = text.toLowerCase();
return students.values().stream()
.filter(s -> s.name().toLowerCase().contains(needle))
.toList();
}
public List<Student> sorted(Comparator<Student> order) {
List<Student> copy = new ArrayList<>(students.values());
copy.sort(order);
return copy;
}
public IntSummaryStatistics statistics() {
return students.values().stream().mapToInt(Student::marks).summaryStatistics();
}
public Map<String, List<String>> namesByGrade() {
return students.values().stream().collect(Collectors.groupingBy(
Student::grade,
TreeMap::new,
Collectors.mapping(Student::name, Collectors.toList())));
}
public int size() {
return students.size();
}
}
How it works:
- A
LinkedHashMap<Integer, Student>gives fast lookup by id and remembers the order in which students were added. A plainHashMapwould list them in an unpredictable order. addbuilds theStudentbefore increasingnextId. If validation fails, the exception is thrown and the id is not wasted.findByIdreturnsOptional<Student>instead ofnull, which forces the caller to handle "not found". See the Java Optional Class lesson.findAllandsortedreturn copies, so code outside the repository cannot change the stored map by accident.
Try the CRUD Methods
package com.gocourse.students;
public class CrudDemo {
public static void main(String[] args) {
StudentRepository repo = new StudentRepository();
// Create
repo.add("Asha Kumar", 92);
repo.add("Ravi Shankar", 67);
repo.add("Meena Iyer", 78);
System.out.println("After adding: " + repo.findAll());
// Read
System.out.println("Find 2: " + repo.findById(2).orElse(null));
System.out.println("Find 9: " + repo.findById(9).map(Student::name).orElse("not found"));
// Update (records are immutable, so we store a changed copy)
repo.findById(2).ifPresent(s -> repo.update(s.withMarks(71)));
System.out.println("After update: " + repo.findById(2).get());
// Delete
System.out.println("Removed 1? " + repo.remove(1));
System.out.println("Removed 1 again? " + repo.remove(1));
// ids are never reused
Student newest = repo.add("Karthik Raj", 55);
System.out.println("New student gets id " + newest.id() + ", total " + repo.size());
}
}
After adding: [Student[id=1, name=Asha Kumar, marks=92], Student[id=2, name=Ravi Shankar, marks=67], Student[id=3, name=Meena Iyer, marks=78]]
Find 2: Student[id=2, name=Ravi Shankar, marks=67]
Find 9: not found
After update: Student[id=2, name=Ravi Shankar, marks=71]
Removed 1? true
Removed 1 again? false
New student gets id 4, total 3
How it works:
findById(9).map(Student::name).orElse("not found")reads as a sentence: find the student, take the name, otherwise use a default.ifPresentruns the update only when the student exists, so there is noNullPointerExceptionrisk.removereturnsfalsethe second time, which the app uses to show an error message.- The new student gets id
4, not1. Reusing a deleted id could mix up the records of two different students.
Search and Sort Students With Comparator
Streams filter the students, and a Comparator decides the order. Comparators can be chained, as covered in Java Comparator.
package com.gocourse.students;
import java.util.Comparator;
public class SearchSortDemo {
public static void main(String[] args) {
StudentRepository repo = new StudentRepository();
repo.add("Asha Kumar", 92);
repo.add("Ravi Shankar", 67);
repo.add("Meena Iyer", 78);
repo.add("Arjun Kumar", 78);
repo.add("Divya Nair", 35);
System.out.println("Search 'kumar': " + repo.searchByName("kumar"));
System.out.println("By name:");
repo.sorted(Comparator.comparing(Student::name))
.forEach(s -> System.out.println(" " + s.name()));
System.out.println("Rank list (marks high to low, then name):");
Comparator<Student> rank = Comparator.comparingInt(Student::marks).reversed()
.thenComparing(Student::name);
int position = 1;
for (Student s : repo.sorted(rank)) {
System.out.printf(" %d. %-13s %3d %s%n", position++, s.name(), s.marks(), s.grade());
}
}
}
Search 'kumar': [Student[id=1, name=Asha Kumar, marks=92], Student[id=4, name=Arjun Kumar, marks=78]]
By name:
Arjun Kumar
Asha Kumar
Divya Nair
Meena Iyer
Ravi Shankar
Rank list (marks high to low, then name):
1. Asha Kumar 92 A
2. Arjun Kumar 78 B
3. Meena Iyer 78 B
4. Ravi Shankar 67 C
5. Divya Nair 35 F
| Comparator | Order |
|---|---|
Comparator.comparing(Student::name) | Name, A to Z |
Comparator.comparingInt(Student::marks) | Marks, low to high |
...comparingInt(Student::marks).reversed() | Marks, high to low |
.thenComparing(Student::name) | Breaks ties by name |
How it works:
searchByNamelowercases both the name and the search text, sokumarfindsKumar.- Arjun and Meena both have 78. Without
thenComparing, their order would depend on insertion order. With it, ties are broken alphabetically, so the rank list is always the same. %-13sinprintfpads the name to 13 characters on the left, and%3dright-aligns the marks, which lines up the columns.
Calculate Class Statistics With Streams
Teachers want averages, pass rates and grade groups. IntSummaryStatistics computes count, sum, minimum, maximum and average in one pass.
package com.gocourse.students;
import java.util.IntSummaryStatistics;
public class StatsDemo {
public static void main(String[] args) {
StudentRepository repo = new StudentRepository();
repo.add("Asha Kumar", 92);
repo.add("Ravi Shankar", 67);
repo.add("Meena Iyer", 78);
repo.add("Arjun Kumar", 78);
repo.add("Divya Nair", 35);
IntSummaryStatistics stats = repo.statistics();
System.out.println("Students: " + stats.getCount());
System.out.printf("Average : %.2f%n", stats.getAverage());
System.out.println("Highest : " + stats.getMax());
System.out.println("Lowest : " + stats.getMin());
long passed = repo.findAll().stream().filter(s -> s.marks() >= 40).count();
System.out.printf("Pass rate: %d of %d (%.0f%%)%n", passed, repo.size(), 100.0 * passed / repo.size());
System.out.println("Names by grade: " + repo.namesByGrade());
}
}
Students: 5
Average : 70.00
Highest : 92
Lowest : 35
Pass rate: 4 of 5 (80%)
Names by grade: {A=[Asha Kumar], B=[Meena Iyer, Arjun Kumar], C=[Ravi Shankar], F=[Divya Nair]}
How it works:
mapToInt(Student::marks).summaryStatistics()turns the students into anIntStreamof marks and collects all five numbers at once.groupingBy(Student::grade, TreeMap::new, mapping(Student::name, toList()))groups students by grade, keeps the grades sorted (A,B,C, ...) with aTreeMap, and stores only the names.100.0 * passed / repo.size()uses100.0so the division is done with decimals.%%prints a literal percent sign.- Grade
Dis missing from the output because no student scored 40-59.groupingByonly creates groups that have members.
Save and Load Students in a CSV File
Without saving, every record disappears when the program ends. A CSV (comma-separated values) file is simple, readable and opens in Excel. The Java Files API lesson covers the methods used here.
package com.gocourse.students;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
/** Saves students to a CSV file (id,name,marks) and loads them back. */
public class StudentFileStore {
private static final String HEADER = "id,name,marks";
private final Path file;
public StudentFileStore(Path file) {
this.file = file;
}
public void save(List<Student> students) throws IOException {
List<String> lines = new ArrayList<>();
lines.add(HEADER);
for (Student s : students) {
lines.add(s.id() + "," + s.name() + "," + s.marks());
}
Path temp = file.resolveSibling(file.getFileName() + ".tmp");
Files.write(temp, lines); // write everything to a temp file first
Files.move(temp, file, StandardCopyOption.REPLACE_EXISTING);
}
public List<Student> load() throws IOException {
if (Files.notExists(file)) {
return List.of(); // first run: nothing saved yet
}
List<Student> students = new ArrayList<>();
List<String> lines = Files.readAllLines(file);
for (int i = 1; i < lines.size(); i++) { // skip the header line
String line = lines.get(i).strip();
if (line.isEmpty()) continue;
String[] parts = line.split(",");
try {
students.add(new Student(Integer.parseInt(parts[0]), parts[1], Integer.parseInt(parts[2])));
} catch (RuntimeException e) {
System.err.println("Skipping line " + (i + 1) + " (" + line + "): " + e.getMessage());
}
}
return students;
}
}
package com.gocourse.students;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileDemo {
public static void main(String[] args) throws IOException {
Path file = Path.of("students.csv");
StudentFileStore store = new StudentFileStore(file);
StudentRepository repo = new StudentRepository();
repo.add("Asha Kumar", 92);
repo.add("Ravi Shankar", 67);
repo.add("Meena Iyer", 78);
store.save(repo.findAll());
System.out.println("Saved file:");
System.out.print(Files.readString(file));
// simulate a hand-edited file with one broken line
Files.writeString(file, "id,name,marks\n1,Asha Kumar,92\n2,Ravi Shankar,abc\n5,Meena Iyer,78\n");
StudentRepository loaded = new StudentRepository();
store.load().forEach(loaded::put);
System.out.println("Loaded: " + loaded.findAll());
System.out.println("Next new id: " + loaded.add("Karthik Raj", 55).id());
}
}
Saved file:
id,name,marks
1,Asha Kumar,92
2,Ravi Shankar,67
3,Meena Iyer,78
Skipping line 3 (2,Ravi Shankar,abc): For input string: "abc"
Loaded: [Student[id=1, name=Asha Kumar, marks=92], Student[id=5, name=Meena Iyer, marks=78]]
Next new id: 6
How it works:
savewrites tostudents.csv.tmpfirst and then moves it over the real file. If the program crashes halfway through writing, the old file is still complete.loadreturns an empty list when the file does not exist yet, so the first run works without special setup.- A broken line (
abcinstead of marks) is reported and skipped. One bad line does not stop the other students from loading. putupdatesnextIdto one more than the largest id loaded, so the next new student gets6and never clashes with the existing5.
Note: This simple CSV format cannot store commas inside a name, which is why the
Studentrecord rejects them. Real CSV libraries handle quoted values, but for a learning project a clear rule is better than a half-working parser.
Build the Java Student Manager Console App
The app reads commands such as add 92 Asha Kumar, calls the repository, and saves to the file on exit.
package com.gocourse.students;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Scanner;
/** Console student manager: java -jar student-manager.jar [file.csv] */
public class StudentManagerApp {
private final StudentRepository repo = new StudentRepository();
private final StudentFileStore store;
private boolean unsavedChanges = false;
StudentManagerApp(Path file) {
this.store = new StudentFileStore(file);
}
public static void main(String[] args) throws IOException {
Path file = Path.of(args.length > 0 ? args[0] : "students.csv");
new StudentManagerApp(file).run();
}
void run() throws IOException {
store.load().forEach(repo::put);
System.out.println("Student Manager - " + repo.size() + " students loaded. Type 'help'.");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("students> ");
if (!scanner.hasNextLine()) break;
String line = scanner.nextLine().strip();
if (line.isEmpty()) continue;
String[] parts = line.split("\\s+", 3); // command, then at most two arguments
String command = parts[0].toLowerCase();
try {
switch (command) {
case "add" -> add(parts);
case "list" -> print(repo.findAll());
case "rank" -> print(repo.sorted(Comparator.comparingInt(Student::marks).reversed()
.thenComparing(Student::name)));
case "find" -> print(repo.searchByName(argument(parts, 1, "find <name>")));
case "update" -> update(parts);
case "delete" -> delete(parts);
case "stats" -> stats();
case "save" -> save();
case "help" -> help();
case "exit", "quit" -> {
if (unsavedChanges) save();
System.out.println("Bye!");
return;
}
default -> System.out.println("Unknown command '" + command + "'. Type 'help'.");
}
} catch (NumberFormatException e) {
System.out.println("Error: expected a number");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
// add <marks> <full name>
private void add(String[] parts) {
int marks = Integer.parseInt(argument(parts, 1, "add <marks> <name>"));
String name = argument(parts, 2, "add <marks> <name>");
Student student = repo.add(name, marks);
unsavedChanges = true;
System.out.println("Added " + student.name() + " with id " + student.id());
}
// update <id> <marks>
private void update(String[] parts) {
int id = Integer.parseInt(argument(parts, 1, "update <id> <marks>"));
int marks = Integer.parseInt(argument(parts, 2, "update <id> <marks>"));
Student student = repo.findById(id)
.orElseThrow(() -> new IllegalArgumentException("No student with id " + id));
repo.update(student.withMarks(marks));
unsavedChanges = true;
System.out.println("Updated " + student.name() + ": " + student.marks() + " -> " + marks);
}
private void delete(String[] parts) {
int id = Integer.parseInt(argument(parts, 1, "delete <id>"));
if (!repo.remove(id)) throw new IllegalArgumentException("No student with id " + id);
unsavedChanges = true;
System.out.println("Deleted student " + id);
}
private void stats() {
if (repo.size() == 0) {
System.out.println("No students yet.");
return;
}
IntSummaryStatistics s = repo.statistics();
System.out.printf("Count %d | Average %.1f | Highest %d | Lowest %d%n",
s.getCount(), s.getAverage(), s.getMax(), s.getMin());
repo.namesByGrade().forEach((grade, names) ->
System.out.println(" " + grade + ": " + String.join(", ", names)));
}
private void save() throws IOException {
store.save(repo.findAll());
unsavedChanges = false;
System.out.println("Saved " + repo.size() + " students.");
}
private static String argument(String[] parts, int index, String usage) {
if (parts.length <= index) throw new IllegalArgumentException("Usage: " + usage);
return parts[index];
}
private static void print(List<Student> students) {
if (students.isEmpty()) {
System.out.println("No students found.");
return;
}
System.out.println(" ID Name Marks Grade");
for (Student s : students) {
System.out.printf("%3d %-15s %5d %s%n", s.id(), s.name(), s.marks(), s.grade());
}
}
private static void help() {
System.out.println("""
add <marks> <name> add a student
list | rank show all, or ranked by marks
find <name> search by part of a name
update <id> <marks> change marks
delete <id> remove a student
stats | save | exit""");
}
}
How it works:
line.split(" 0 s+", 3)splits into at most three parts. Foradd 92 Asha Kumar, the parts areadd,92andAsha Kumar, so names with spaces stay whole.- The
switchmaps each command to a small method. Adding a new command means one newcaseand one method. - Every error becomes an exception with a clear message.
NumberFormatExceptionis caught first because it is a subclass ofIllegalArgumentException. unsavedChangestracks edits.exitsaves automatically only when something changed.argumentchecks that the user typed enough words and shows the correct usage if not.
Real-World Example: Manage a Class With student-manager.jar
student-manager/
└── src/
└── com/
└── gocourse/
└── students/
├── Student.java
├── StudentFileStore.java
├── StudentManagerApp.java
└── StudentRepository.java
cd student-manager
javac -d out src/com/gocourse/students/*.java
jar --create --file student-manager.jar --main-class com.gocourse.students.StudentManagerApp -C out .
java -jar student-manager.jar class10.csv
First session, starting with no file:
Student Manager - 0 students loaded. Type 'help'.
students> help
add <marks> <name> add a student
list | rank show all, or ranked by marks
find <name> search by part of a name
update <id> <marks> change marks
delete <id> remove a student
stats | save | exit
students> add 92 Asha Kumar
Added Asha Kumar with id 1
students> add 67 Ravi Shankar
Added Ravi Shankar with id 2
students> add 78 Meena Iyer
Added Meena Iyer with id 3
students> add 105 Arjun
Error: marks must be 0-100, got 105
students> add 78 Arjun Kumar
Added Arjun Kumar with id 4
students> add 35 Divya Nair
Added Divya Nair with id 5
students> list
ID Name Marks Grade
1 Asha Kumar 92 A
2 Ravi Shankar 67 C
3 Meena Iyer 78 B
4 Arjun Kumar 78 B
5 Divya Nair 35 F
students> update 2 71
Updated Ravi Shankar: 67 -> 71
students> update 9 50
Error: No student with id 9
students> find kumar
ID Name Marks Grade
1 Asha Kumar 92 A
4 Arjun Kumar 78 B
students> rank
ID Name Marks Grade
1 Asha Kumar 92 A
4 Arjun Kumar 78 B
3 Meena Iyer 78 B
2 Ravi Shankar 71 C
5 Divya Nair 35 F
students> delete 5
Deleted student 5
students> stats
Count 4 | Average 79.8 | Highest 92 | Lowest 71
A: Asha Kumar
B: Meena Iyer, Arjun Kumar
C: Ravi Shankar
students> rename 1
Unknown command 'rename'. Type 'help'.
students> exit
Saved 4 students.
Bye!
The saved file, class10.csv:
id,name,marks
1,Asha Kumar,92
2,Ravi Shankar,71
3,Meena Iyer,78
4,Arjun Kumar,78
Second session, the next day:
Student Manager - 4 students loaded. Type 'help'.
students> list
ID Name Marks Grade
1 Asha Kumar 92 A
2 Ravi Shankar 71 C
3 Meena Iyer 78 B
4 Arjun Kumar 78 B
students> add 88 Karthik Raj
Added Karthik Raj with id 5
students> exit
Saved 5 students.
Bye!
How it works:
- Validation at the source.
add 105 Arjunwas rejected by the record's compact constructor, and no id was used up: the next valid student still got id4. - Ranking with tie-breaks.
rankplaced Arjun before Meena (both 78) because ofthenComparing(Student::name). - Live statistics. After deleting Divya, the average rose to 79.8 (79.75 rounded) and grade
Fdisappeared from the groups. - Persistence.
exitsaved the four students, and the next session loaded them. Divya's old id5was free again after the restart, because ids continue from the highest id in the file. - One file per class. The file name is an argument, so
class10.csvandclass12.csvcan be managed separately with the same JAR.
The next project, the Java Library System, extends this design with several related classes (books, members and loans), due dates and fines.