Explain it simply
Explain it simply
Think of a school office. Every student has a registration card, and nobody can rub out the student number on it and write a new one. The cards live in a cabinet, and only the office clerk holds the key. To file a new card you hand it to the clerk, who first checks that no card with that number already exists.
In this project the Student class is the card, StudentManager is the clerk and the cabinet, and StudentApp is the main method that opens the office. Part 1 calculates no grades yet. Parts 2 and 3 build on this foundation, so we get its shape right first.
Problem → Why → Solution
The problem: a student record anyone can edit
A quick first draft makes every field public and lets main handle the students list directly. It compiles and runs. But when Mg Mg is added with Su Su's id 102, nothing complains. Nothing stops some other line from setting s.id = -5 or leaving the name empty either.
Later, when code looks up id 102 to record a score, it updates whichever student it finds first, which is Su Su. Mg Mg's marks quietly land on Su Su's record and nobody notices until a report looks wrong.
class Student {
public String name;
public int id;
}
// in main:
List<Student> students = new ArrayList<>();
Student a = new Student(); a.name = "Su Su"; a.id = 102;
Student b = new Student(); b.name = "Mg Mg"; b.id = 102; // duplicate id, accepted
students.add(a);
students.add(b);
b.id = -5; // invalid id, accepted
Student c = new Student(); // name is nullWhy can these bugs get in?
With public fields there is no single place that guards the rules "a student always has a name" and "an id is positive". With the list open to everyone, there is no single place to check "ids are unique" either. The rules only hold if they live in the constructor and the manager's methods, and private closes every other path.
Core concept: make the data model trustworthy first
Before writing features, decide what must always be true whenever a Student object exists. Such a guaranteed fact is called an invariant. For this project we make four decisions.
1. Make the fields private final
private stops code outside the class from reading or writing a field directly. final means the field cannot be given a new value after the constructor finishes, so an id never changes once set. The subjectScores map reference is final too, yet its contents can still grow in Part 2.
2. The constructor is the gatekeeper
Every new object passes through the constructor, so validation placed there means an invalid Student can never exist. A blank name or an id of 0 or less throws IllegalArgumentException. It is unchecked, so callers compile without a try-catch; custom checked exceptions arrive in Part 3.
3. Hide the list inside a manager
"Ids are unique" is a rule about all students, not one, so Student cannot check it. StudentManager keeps the List<Student> private and addStudent() calls findById() first. Because no getter hands the list out, nothing can bypass that check.
4. Keep main in its own class, first
When you run java StudentApp.java with the single-file launcher, JDK 21 looks for main in the first top-level class in the file. That is why StudentApp sits at the top.
Who owns what in Part 1
-----------------------
StudentApp.main()
|
v
StudentManager --- private List<Student> students
addStudent() -> rejects a duplicate id
findById() -> Student or null
printRoster()
|
v
Student --------- private final name, id, subjectScores
constructor -> rejects blank name, id <= 0Read the diagram from top to bottom. main only calls StudentManager and never touches a Student field directly. Each arrow means "this class uses the one below it". Part 2 adds grade methods to Student and Part 3 adds exceptions, but the direction of these arrows never changes.
- Constructor validates each card
- Manager checks the id is unique
- Only the manager touches the list
- main talks only to the manager
Place each rule where the data it needs is visible: one student in Student, all students in the manager.
General pattern
class Entity {
private final int id;
Entity(int id) {
if (id <= 0) throw new IllegalArgumentException("bad id: " + id);
this.id = id;
}
int getId() { return id; }
}
class Registry {
private final List<Entity> items = new ArrayList<>();
boolean add(Entity e) { /* reject duplicate id, then items.add(e) */ }
}Single-object rules go in the constructor; whole-collection rules go in the registry's methods. Both the fields and the list stay private.
Part 1 code: building the roster
In this example main lives in StudentApp at the top of the file, and StudentManager is a real class that owns the list. When you run a single file directly, as in java StudentApp.java, Java looks for main in the first class in the file. If another class such as Student came first, JDK 21 would stop with "error: can't find main(String[]) method in class: Student", so always put the class holding main at the top. Watch the output reject both the duplicate id and the blank name.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class StudentApp {
public static void main(String[] args) {
StudentManager manager = new StudentManager();
manager.addStudent(new Student("Aung Aung", 101));
manager.addStudent(new Student("Su Su", 102));
manager.addStudent(new Student("Ko Ko", 103));
boolean added = manager.addStudent(new Student("Mg Mg", 102));
String result = added ? "added" : "rejected, id taken";
System.out.println("Add Mg Mg as 102: " + result);
try {
manager.addStudent(new Student(" ", 104));
} catch (IllegalArgumentException e) {
System.out.println("Add blank name: rejected, " + e.getMessage());
}
manager.printRoster();
System.out.println("findById(102): " + describe(manager.findById(102)));
System.out.println("findById(999): " + describe(manager.findById(999)));
}
static String describe(Student s) {
return s == null ? "not found" : s.getName();
}
}
class Student {
private final String name;
private final int id;
private final Map<String, Integer> subjectScores;
public Student(String name, int id) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("name must not be blank");
}
if (id <= 0) {
throw new IllegalArgumentException("id must be positive, got " + id);
}
this.name = name.strip();
this.id = id;
this.subjectScores = new LinkedHashMap<>(); // filled in Part 2
}
public String getName() {
return name;
}
public int getId() {
return id;
}
}
class StudentManager {
private final List<Student> students = new ArrayList<>();
public boolean addStudent(Student student) {
if (findById(student.getId()) != null) {
return false; // ids must stay unique
}
students.add(student);
return true;
}
public Student findById(int id) {
for (Student s : students) {
if (s.getId() == id) {
return s;
}
}
return null;
}
public void printRoster() {
System.out.println("Roster: " + students.size() + " students");
for (Student s : students) {
System.out.println("ID: " + s.getId() + " - Name: " + s.getName());
}
}
}Code breakdown
- Fields that cannot be reassigned
private final int id;Code outside the class cannot see id, and nothing can change it after the constructor. There is deliberately no setId() method.
- Validation in the constructor
if (name == null || name.isBlank()) {isBlank() (Java 11+) is true for both "" and whitespace-only strings like " ". Checking null first means isBlank() is never called on null.
- Uniqueness lives in the manager
if (findById(student.getId()) != null) {If the id is already taken it returns false without touching the list; main reads that boolean and prints "rejected, id taken".
- null means not found
return s == null ? "not found" : s.getName();findById() returns null when nothing matches. Every caller has to handle that, so the describe() helper in main turns null into "not found".
- Catching the constructor's refusal
} catch (IllegalArgumentException e) {Building a Student with " " throws inside the constructor, so addStudent() is never even reached. That is why the roster still holds three students.
Add Mg Mg as 102: rejected, id taken
Add blank name: rejected, name must not be blank
Roster: 3 students
ID: 101 - Name: Aung Aung
ID: 102 - Name: Su Su
ID: 103 - Name: Ko Ko
findById(102): Su Su
findById(999): not foundWhy a LinkedHashMap behind a Map type?
subjectScores is declared with the Map<String, Integer> type and holds a LinkedHashMap object. Because the field's type is the interface, switching to another implementation such as TreeMap later is a one-line change. LinkedHashMap is chosen because the Part 3 report should list subjects in the order they were added; Java does not promise any iteration order for a plain HashMap.
Part 1 does not use the map yet, but the constructor already initialises it as an empty map, so addScore() in Part 2 can never meet a null map.
In real projects
In real projects
School management systems, clinic patient records and library member systems all answer the identity question first: how do we tell two records apart? A name is a poor identity, because there can be two students called Su Su. A list index is worse, because deleting one student shifts every index after it. Keeping an id that never changes in a final field is the same idea as a primary key in a database.
The layering you see here also repeats in large applications: a model class like Student, a service or repository class like StudentManager, and an entry point such as a console menu or a web controller. You can swap the entry point without rewriting the model or its rules.
Common mistakes
Common mistakes
Putting the class with main below the others
With java File.java, JDK 21 only looks at the first class. Putting Student on top gives "can't find main(String[]) method in class: Student". Put the class with main first, or split classes into their own files and compile with javac.
Returning the live list from a getter
public List<Student> getStudents() { return students; } lets a caller do getStudents().add(...) and skip the duplicate-id check. The field is private, but handing out the object itself breaks encapsulation anyway. If you must expose it, return a read-only copy such as List.copyOf(students).
Using the list index as the student id
Treating students.get(1) as "student 1" breaks the moment someone earlier in the list is removed: a different person moves into index 1 and receives the wrong marks. Always look students up by their id field with findById().
Forgetting the imports
ArrayList, List, Map and LinkedHashMap live in java.util, so leaving out the imports gives a "cannot find symbol" compile error. Only java.lang classes such as String need no import.
Mini challenge
Add remove and name search
Add two methods to StudentManager. removeStudent(int id) deletes the student with that id and returns true if it removed someone. searchByName(String fragment) returns every student whose name contains the fragment, ignoring upper and lower case.
- removeStudent() returns false for an unknown id and never throws
- Do not call list.remove() inside a for-each loop (use removeIf)
- searchByName("aung") must find both "Aung Aung" and "Aung Min"
- Return an empty list, not null, when nobody matches
import java.util.ArrayList;
import java.util.List;
public class RosterChallenge {
public static void main(String[] args) {
// TODO: add four students (two with "Aung" in the name),
// search for "aung" and "zaw", remove 102 twice, print the count
}
}
// Student from the lesson goes here (name, id, getters).
class StudentManager {
private final List<Student> students = new ArrayList<>();
boolean removeStudent(int id) {
// TODO: remove the matching student, return whether anything changed
return false;
}
List<Student> searchByName(String fragment) {
// TODO: lower-case both sides and use contains()
return new ArrayList<>();
}
}Expected: Searching "aung" prints [101 Aung Aung, 104 Aung Min], "zaw" prints [], removing 102 prints true the first time and false the second, and the final line is students left: 3.
Show hint
students.removeIf(s -> s.getId() == id) already returns true when it removed something. For the search, try s.getName().toLowerCase().contains(fragment.toLowerCase()).
Show solution
import java.util.ArrayList;
import java.util.List;
public class RosterChallenge {
public static void main(String[] args) {
StudentManager manager = new StudentManager();
manager.addStudent(new Student("Aung Aung", 101));
manager.addStudent(new Student("Su Su", 102));
manager.addStudent(new Student("Ko Ko", 103));
manager.addStudent(new Student("Aung Min", 104));
System.out.println("search 'aung': " + names(manager.searchByName("aung")));
System.out.println("search 'zaw': " + names(manager.searchByName("zaw")));
System.out.println("remove 102: " + manager.removeStudent(102));
System.out.println("remove 102 again: " + manager.removeStudent(102));
System.out.println("students left: " + manager.count());
}
static String names(List<Student> list) {
List<String> result = new ArrayList<>();
for (Student s : list) {
result.add(s.getId() + " " + s.getName());
}
return result.toString();
}
}
// Validation from the lesson is left out here to keep the focus on the new methods.
class Student {
private final String name;
private final int id;
Student(String name, int id) {
this.name = name;
this.id = id;
}
String getName() { return name; }
int getId() { return id; }
}
class StudentManager {
private final List<Student> students = new ArrayList<>();
void addStudent(Student student) {
students.add(student);
}
boolean removeStudent(int id) {
return students.removeIf(s -> s.getId() == id);
}
List<Student> searchByName(String fragment) {
String needle = fragment.toLowerCase();
List<Student> matches = new ArrayList<>();
for (Student s : students) {
if (s.getName().toLowerCase().contains(needle)) {
matches.add(s);
}
}
return matches;
}
int count() {
return students.size();
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Student's fields are private final and are read only through getters
- Constructor validation makes an invalid Student impossible to create
- StudentManager hides the list and enforces unique ids in addStudent()
- For the single-file launcher, StudentApp with main goes first in the file