Student Grade Calculator in Java: Solution, Explanation & Practice

Create a class to manage student grades

Problem summary

Create a Student class that stores marks in 3 subjects and calculates average and grade.

Starter code

// Create Student class with:
// - String name
// - int[] marks (3 subjects)
// - double getAverage()
// - char getGrade() based on average

public class Main {
    public static void main(String[] args) {
        // Test case 1: marks = {85, 90, 78}
        // Print: Average: <avg>, Grade: <grade>
    }
}

Expected output and test cases

  • Marks 85, 90, 78
    Average: 84.33, Grade: B
  • High marks
    Average: 95.00, Grade: A
  • Low marks
    Average: 55.00, Grade: D

Hints

  1. Sum all marks and divide by count
  2. Use if-else chain for grades
  3. Format average to 2 decimal places

Validated solution

Reveal Java solution
class Student {
    private final int first, second, third;
    Student(int first, int second, int third) { this.first = first; this.second = second; this.third = third; }
    double average() { return (first + second + third) / 3.0; }
    String grade() {
        double average = average();
        if (average >= 90) return "A";
        if (average >= 75) return "B";
        if (average >= 60) return "C";
        return "D";
    }
}
public class Main {
    public static void main(String[] args) {
        Student student = new Student(85, 90, 78);
        System.out.printf("Average: %.2f, Grade: %s%n", student.average(), student.grade());
    }
}

How to approach the problem

The Student owns both its marks and the rules for deriving an average and grade. Dividing by 3.0 rather than 3 preserves the fractional part before formatting to two decimal places.

Approach

  1. Store the three marks in one object.
  2. Calculate the average as floating point.
  3. Test thresholds from highest to lowest.

Time and space complexity

Time: O(1). Space: O(1).

Edge cases to test

  • Scores at 75, 90, and 60 prove the inclusive boundaries.
  • Production code should validate the permitted mark range.

Common mistakes

  • Using integer division for the average.
  • Writing independent if statements that can assign more than one grade.

Follow-up challenge

Replace three fields with a validated list of marks and calculate a weighted average.

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler