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:
-
Store student details (like name or roll number, optional).
-
Include a
resultmethod 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-elseto 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:
-
Studentclass stores the student name. -
result()method takes marks in three subjects. -
It calculates total marks and percentage.
-
It checks if the student has passed in all subjects (marks ≥ 40).
-
It prints the student name, total, percentage, and result.