Thuta Learning
Java
AdvancedProgrammingBeginner

Mini Project

JavaLesson 3130 min

What you'll walk away with

  • Store ordered data in an ArrayList and keyed lookups in a HashMap
  • Pull the grading rule into a static method that returns a value instead of printing
  • Explain why marks.get() returning null crashes when it is unboxed into an int
  • Guard lookups with containsKey() and compute an average without integer division

Explain it simply

Explain it simply

Picture a teacher's register. The first page lists the students in the order they enrolled. The second page pairs each name with a mark, like "Aung → 85". To produce grades, the teacher takes each name from page one, looks up the mark on page two, and checks it against a rule such as "80 or more is an A".

In Java, page one is an ArrayList, page two is a HashMap, and the rule is a getGrade() method. The real lesson of this project is what happens when a name on page one has no entry on page two yet.

Problem → Why → Solution

The problem: one student without a mark stops the whole program

Kyaw enrolled today, so he is in the students list but has no entry in the marks map yet. The first draft stores marks.get(student) straight into an int without checking whether the key exists. Aung's line prints normally. When the loop reaches Kyaw, the program stops with a NullPointerException, and every student after him never gets a grade at all.

The message JDK 21 prints is precise about the cause: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.HashMap.get(Object)" is null.

Main.java
ArrayList<String> students = new ArrayList<>();
students.add("Aung");
students.add("Kyaw");                 // enrolled today, no mark yet

HashMap<String, Integer> marks = new HashMap<>();
marks.put("Aung", 85);

for (String student : students) {
  int mark = marks.get(student);      // NullPointerException for "Kyaw"
  System.out.println(student + " - Mark: " + mark);
}

Why does it crash?

A HashMap<String, Integer> does not store primitive ints; it stores Integer objects. When a key is missing, get() returns null rather than throwing. Assigning that null to an int makes Java auto-unbox it by calling intValue() behind the scenes, and calling a method on null is exactly what throws.

Core concept: two collections, one rule, one loop

Even in a tiny project, code is easier to change and to test when three questions get separate answers: where does the data live, where does the rule live, and where is output produced? Look at this grade manager as four separate pieces, each with one job.

1. ArrayList for order

The report should follow enrolment order, so names go into an ArrayList<String>. A list guarantees insertion order, and it also allows the same name twice, which is worth remembering later.

2. HashMap for lookup

To answer "what did Mya score?" without scanning a list, marks live in a HashMap<String, Integer>. Each key has exactly one value, and calling put() with an existing key replaces the old value. A HashMap does not promise any iteration order, which is why the list, not the map, drives the report.

3. The rule in a method

getGrade(int mark) only returns a String; it never prints. That means you can check getGrade(80) is "A" on its own, without the loop, and reuse it for a report or a file export later. The conditions must run from the highest threshold down.

4. The loop ties it together

For each student the loop checks containsKey() first, calls get() only when a mark exists, and updates the total and the graded counter. When computing the average, the (double) cast must happen before the division; otherwise 190 / 3 is the int 63. The counter matters too: dividing by students.size() would count Kyaw, who has no mark, and pull the average down for no reason.

CollectionGood atUsed here for
ArrayList<String>Keeping order, access by indexReport order
HashMap<String, Integer>Fast lookup by keyName → mark
Mental model: walk the list, look up, apply the rule
  1. Take the next name from the list
  2. Check the map has that key
  3. Pass the mark to getGrade()
  4. Print a line, update the total

A map only promises "if it is there, here it is". Never assume a key cannot be missing.

General pattern

java
static String classify(int value) {
  if (value >= HIGH) return "TOP";
  else if (value >= LOW) return "MID";
  return "BOTTOM";
}

for (String key : orderedKeys) {
  if (!lookup.containsKey(key)) { /* report the gap */ continue; }
  int value = lookup.get(key);
  System.out.println(key + " -> " + classify(value));
}

The list decides the order, the map supplies the value, and a pure method applies the rule. Handle the gap with containsKey() before calling get().

The complete grade manager

This example has Aung, Mya and Htet, who all have marks, plus Kyaw, who has no mark yet, and it uses a containsKey() guard and a class average. Notice in the output that Kyaw's line says "no mark recorded" instead of crashing, and that the average uses only the three students who were actually graded. If every student in your test data has a mark, a missing-key bug like this never shows up, so always test with at least one incomplete record.

Main.java
import java.util.ArrayList;
import java.util.HashMap;

public class Main {
  static String getGrade(int mark) {
    if (mark >= 80) {
      return "A";
    } else if (mark >= 60) {
      return "B";
    } else if (mark >= 40) {
      return "C";
    } else {
      return "Fail";
    }
  }

  public static void main(String[] args) {
    ArrayList<String> students = new ArrayList<>();
    students.add("Aung");
    students.add("Mya");
    students.add("Htet");
    students.add("Kyaw"); // enrolled, but no mark recorded yet

    HashMap<String, Integer> marks = new HashMap<>();
    marks.put("Aung", 85);
    marks.put("Mya", 67);
    marks.put("Htet", 38);

    int total = 0;
    int graded = 0;
    for (String student : students) {
      if (!marks.containsKey(student)) {
        System.out.println(student + " - no mark recorded");
        continue;
      }
      int mark = marks.get(student);
      total += mark;
      graded++;
      System.out.println(student + " - Mark: " + mark + ", Grade: " + getGrade(mark));
    }

    double average = (double) total / graded;
    System.out.println("Graded " + graded + " of " + students.size() + " students");
    System.out.printf("Class average: %.1f%n", average);
  }
}

Code breakdown

  1. Highest threshold firstif (mark >= 80) {

    85 satisfies >= 80, >= 60 and >= 40. An if-else chain runs only the first branch that is true, so the highest threshold must come first for 85 to earn an A.

  2. Order comes from the liststudents.add("Kyaw"); // enrolled, but no mark recorded yet

    Kyaw is in the list but deliberately not in the map. In real apps, two data sources being out of step like this happens all the time.

  3. Guard before get()if (!marks.containsKey(student)) {

    When the key is missing, it prints a message and continue moves on to the next student, so Kyaw no longer stops the whole loop.

  4. Safe unboxingint mark = marks.get(student);

    This line is only reached after the guard, so get() cannot return null here and unboxing the Integer into an int is safe.

  5. Cast before dividingdouble average = (double) total / graded;

    The cast turns total into a double first, so 190.0 / 3 gives 63.33..., and printf's %.1f shows it as 63.3 with one decimal place.

You should see
Aung - Mark: 85, Grade: A
Mya - Mark: 67, Grade: B
Htet - Mark: 38, Grade: Fail
Kyaw - no mark recorded
Graded 3 of 4 students
Class average: 63.3

Edge case: nobody has a mark yet

If nobody in the list has a mark yet, graded is 0. (double) 0 / 0 does not throw; it produces NaN (Not a Number) and the program prints "Class average: NaN". Without the cast, the int division 0 / 0 throws an ArithmeticException instead.

Neither is something a user should see. Check graded == 0 before computing the average and print a message such as "no marks yet".

When getOrDefault() fits

marks.getOrDefault(student, 0) avoids the null, but it erases the difference between "no mark yet" and "scored 0": Kyaw would get Fail and drag the average down. Use a default only where it truly means something, such as a count.

In real projects

In real projects

In school and HR systems, the list of people and the computed values usually come from two different sources: enrolment from a registration system, marks from an exam system. If a nightly report job crashes on one missing record, hundreds of other students get no report either. Production code therefore skips the missing record, logs it, and ends with a summary such as "Graded 3 of 4" so someone can follow up.

Business rules like the grade scale change from year to year, for example moving the A threshold from 80 to 85. With the rule inside one method there is exactly one place to edit, and the boundary values (79, 80, 39, 40) can be unit-tested on their own. When you later split this project into Student, Course and GradeService classes, getGrade() moves into GradeService almost unchanged.

Common mistakes

Common mistakes

Unboxing get() straight into an int

int mark = marks.get(name) works as long as every key exists, so it never fails with three tidy test names. It fails the first day a key is missing. Check containsKey() first, or read into an Integer and test mark != null.

Checking thresholds from the bottom up

Putting if (mark >= 40) first sends Aung's 85 into that branch, and he gets a C. Nothing fails to compile, so you only notice by testing getGrade() at the boundaries 80, 60 and 40.

Casting after the division

Writing (double) (total / graded) does the int division first and merely turns 63 into 63.0, so the decimals vanish without any warning. Cast one operand instead: (double) total / graded.

Mixing I/O, rules and data inside main

Writing the grade if-else directly inside main's loop means the rule cannot be tested alone and gets copy-pasted when an export feature arrives. Extract a method that returns the grade.

Mini challenge

Add three reports

Extend the grade manager with three reports, each in its own method: the student with the highest mark, how many students got each grade, and the list of students who failed. Every method must skip students who have no mark.

  • topStudent() returns the name with the highest mark, or "nobody" when there are no marks
  • countGrades() returns a Map with counts in the order A, B, C, Fail, including grades with 0
  • failing() returns the names of students whose grade is Fail as a List
  • A student without a mark must never cause a NullPointerException
Main.java
import java.util.*;

public class Main {
  // Reuse getGrade(int mark) from the lesson.

  static String topStudent(List<String> students, Map<String, Integer> marks) {
    // TODO: track the best name and mark; skip names with no mark
    return "nobody";
  }

  static Map<String, Integer> countGrades(List<String> students,
                                          Map<String, Integer> marks) {
    // TODO: LinkedHashMap pre-filled with A, B, C, Fail = 0, then count
    return null;
  }

  static List<String> failing(List<String> students, Map<String, Integer> marks) {
    // TODO: collect names whose grade is "Fail"
    return null;
  }

  public static void main(String[] args) {
    // TODO: five students (one without a mark) and print all three reports
  }
}

Expected: With Aung 85, Mya 67, Htet 38, Kyaw (no mark) and Su 92 you get three lines: Top student: Su, Grade counts: {A=2, B=1, C=0, Fail=1}, and Needs support: [Htet].

Show hint

Reading marks.get(name) into an Integer cannot crash; just test mark != null. For a stable order in the counts, use a LinkedHashMap and put all four grades with 0 before counting.

Show solution
Main.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
  static String getGrade(int mark) {
    if (mark >= 80) return "A";
    if (mark >= 60) return "B";
    if (mark >= 40) return "C";
    return "Fail";
  }

  // Name of the student with the highest mark, or "nobody" if no marks exist.
  static String topStudent(List<String> students, Map<String, Integer> marks) {
    String best = "nobody";
    int bestMark = -1;
    for (String name : students) {
      Integer mark = marks.get(name); // Integer, so a missing key is just null
      if (mark != null && mark > bestMark) {
        best = name;
        bestMark = mark;
      }
    }
    return best;
  }

  static Map<String, Integer> countGrades(List<String> students,
                                          Map<String, Integer> marks) {
    Map<String, Integer> counts = new LinkedHashMap<>();
    for (String grade : List.of("A", "B", "C", "Fail")) {
      counts.put(grade, 0);
    }
    for (String name : students) {
      if (marks.containsKey(name)) {
        String grade = getGrade(marks.get(name));
        counts.put(grade, counts.get(grade) + 1);
      }
    }
    return counts;
  }

  static List<String> failing(List<String> students, Map<String, Integer> marks) {
    List<String> result = new ArrayList<>();
    for (String name : students) {
      if (marks.containsKey(name) && getGrade(marks.get(name)).equals("Fail")) {
        result.add(name);
      }
    }
    return result;
  }

  public static void main(String[] args) {
    List<String> students = List.of("Aung", "Mya", "Htet", "Kyaw", "Su");
    Map<String, Integer> marks = new HashMap<>();
    marks.put("Aung", 85);
    marks.put("Mya", 67);
    marks.put("Htet", 38);
    marks.put("Su", 92);

    System.out.println("Top student: " + topStudent(students, marks));
    System.out.println("Grade counts: " + countGrades(students, marks));
    System.out.println("Needs support: " + failing(students, marks));
  }
}

Quick quiz 1 / 3

marks is a HashMap<String, Integer> with no "Kyaw" key. What happens with Integer m = marks.get("Kyaw"); System.out.println(m);?

Quick quiz 2 / 3

If getGrade() checks if (mark >= 40) first, then >= 60 and >= 80 as else-if branches, what does getGrade(85) return?

Quick quiz 3 / 3

With total = 190 and graded = 3, which expression gives 63.333...?

What to remember

  • The ArrayList decides report order; the HashMap answers name → mark lookups
  • get() returns null for a missing key, and unboxing that null into an int throws
  • Check containsKey() before get(), skip missing data, and report it in a summary
  • Keep the grade rule in a method that returns a value, checking the highest threshold first
  • Cast to double before dividing when computing an average

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Mini Project | Thuta Learning