Table of Contents

    Java Program to Implement a Student Class

    Question: Java Program to Implement a Student Class

    Task:
    Write a Java class to represent a student. Your class should:

    1. Store student details (like name or roll number, optional).

    2. Include a result method that:

      • Takes marks in three subjects as parameters.

      • Calculates total marks and percentage.

      • Displays the result (like total marks, percentage, and pass/fail status).

    Hints / Help Points:

    • You can assume each subject is out of 100.

    • Pass criteria: 40 marks in each subject.

    • Percentage = (total marks / 300) × 100.

    • Use if-else to determine pass/fail.

    Example Usage:

    
    Student s = new Student("Rahul");
    s.result(70, 85, 90);  
    // Output: Total: 245, Percentage: 81.67%, Result: Pass
    
    

    Answer / Solution: Student Class

    
    // Student class
    class Student {
        private String name;
    
        // Constructor
        public Student(String name) {
            this.name = name;
        }
    
        // Method to calculate and display result
        public void result(int marks1, int marks2, int marks3) {
            int total = marks1 + marks2 + marks3;
            double percentage = (total / 300.0) * 100;
    
            System.out.println("Student: " + name);
            System.out.println("Total Marks: " + total);
            System.out.println("Percentage: " + percentage + "%");
    
            // Check pass/fail (pass if marks >= 40 in all subjects)
            if (marks1 >= 40 && marks2 >= 40 && marks3 >= 40) {
                System.out.println("Result: Pass");
            } else {
                System.out.println("Result: Fail");
            }
        }
    }
    
    // Test class
    public class TestStudent {
        public static void main(String[] args) {
            Student s1 = new Student("Rahul");
            Student s2 = new Student("Anjali");
    
            s1.result(70, 85, 90);  // Pass
            System.out.println();
            s2.result(30, 50, 60);  // Fail
        }
    }
    
    

    Explanation:

    1. Student class stores the student name.

    2. result() method takes marks in three subjects.

    3. It calculates total marks and percentage.

    4. It checks if the student has passed in all subjects (marks ≥ 40).

    5. It prints the student name, total, percentage, and result.