K. R.
MANGALAM UNIVERSITY
School Of Engineering And Tecchnology
LAB MANUAL
Course: Java Programming (ENCS251)
(2025-2026)
Submitted By: Submitted To:
Mohit Sharma Meenu Ma’am
Roll No. – 2401730011
Course – Btech CSE (AI & ML) Section - A
INDEX
Lab No. Title Page No. Signature
1. Create a Student Record Management system that 5
allows the user to input, display, and calculate grades
for students. Implement a class-based structure using
Object- Oriented Programming principles to manage
student data such as roll number, name, course,
marks, and grade. The program should also allow the
display of student records and calculate the grade
based on marks.
2. Java program that counts how many times a specific 10
character appears in a char] array.
3. Create a Java class named Person with the following 11
constructors: 1. A default constructor that initializes
the name to "Unknown" and age to 0. 2. A
parameterized constructor that initializes the name
and age with given values. 3. A copy constructor that
creates a new Person object by copying the details
from another Person object. Include a method to
display the person's details. Write a program to create
and display details of three Person objects: one using
the default constructor, one using the parameterized
constructor, and one using the copy constructor.
4. Create a Java class named Shape with overloaded 13
constructors to initialize attributes for different
shapes: one constructor to set the radius of a circle,
and another to set the length and width of a
rectangle. Implement methods to calculate and
display the area of the circle and the rectangle
separately. Write a program that creates instances of
both shapes using the appropriate constructors and
displays their respective areas.
5. Write a Java program to implement hierarchical 16
inheritance. Create a base class Shape with a method
area. Derive two classes, Circle and Rectangle, from
Shape. Override the area method in both subclasses
to calculate and display the area of a circle and a
rectangle, respectively. Use appropriate constructors
to initialize the attributes (radius for the circle, length,
and width for the rectangle).
6. A software company is developing a vehicle 19
management system. As part of this system, they have
created a class named Car to represent basic car
information. The design of the class uses constructor
overloading. The class includes: • A no-argument
constructor, • A one-argument constructor (brand), •
A three-argument constructor (brand, model, year). •
A method displayinfol) to print the car's details. The
constructors are designed to call each other using the
this keyword
7. Design and implement a Java program to demonstrate 22
multilevel inheritance using Student, Marks, and
Result classes. 1. Create a base class Student to store
basic student details such as rollNo, name, and
course. 2. Derive a subclass Marks from Student to
store marks of three subjects. 3. Create another
subclass Result derived from Marks to calculate the
total marks, percentage, and grade based on the
marks entered. 4. Implement the following
functionalities: o Accept details of a student and their
marks using constructors or methods. o Calculate
total marks and percentage in the Result class. o
Assign a grade based on the percentage using the
following criteria: - 90% and above → Grade A - 75%
to 89% → Grade B - 50% to 74% → Grade C - Below
50% → Grade D 5. Display the complete student
information along with total marks, percentage, and
grade.
8. Create an e-commerce system using method 26
overriding. • Create a base class Product with
attributes like id, name, and price. • Define a method
calculateDiscount) in the Product class. • Create
subclasses like Electronics, Clothing, and Groceries,
each overriding calculateDiscount to implement
category-specific discount logic. • In the main class,
create a list of products using polymorphism, and
calculate the final bill amount.
9. Design a program to manage different types of 30
transportation. • Create an abstract class Transport
with an abstract method calculateFare(distance). •
Create subclasses Bus, Train, and Flight that override
calculatetarel with their own logic. • In the main class,
dynamically select a transport type at runtime using
user input, then calculate the fare for a given distance.
10. Create a library management system where different 33
types of users have different borrowing privileges. •
Create a superclass LibraryUser with attributes like
userid and name, and a method maxBooksAllowed).
• Subclasses Student, Teacher, and Researcher should
override maxBooksAllowed) to specify different
borrowing limits. • In the main program: o Maintain a
collection of library users. o Display the borrowing
limits dynamically using overridden methods. o
Generate a report of issued books and write it to a
text file.
11. Design and implement a multithreaded Java program 37
that performs different numerical tasks concurrently
using multiple threads. The program should: 1. Create
three separate threads, each performing a distinct
task: o Thread 1: Prints even numbers from 1 to 20. o
Thread 2: Prints odd numbers from 1 to 20. o Thread
3: Calculates and displays the sum of numbers from 1
to 20.
12. Discuss the concept of collections in Java. Write a 40
code snippet to sort a List of strings in ascending and
descending order using the Collections class.
13. Explain the use of byte streams in Java with examples 42
of FileInputstream and FileOutputStream. Write a
code snippet to read a binary file and write its
contents to another binary file using these classes.
14. Explain in detail the different types of Java I/0 44
streams. Discuss Byte Streams, Character Streams,
Buffered Streams, and their commonly used classes
with examples.
15. Explain the Java Collections Framework architecture. 47
Describe the core interfaces such as Collection, List,
Set, Queue, and Map with examples of their
implementations.
16. Write a Java program to demonstrate ArrayList 49
operations such as adding, removing, searching, and
updating elements.
17. Design and implement a Student Result Management 51
System that efficiently collects and manages student
details along with their subject marks. The system
should compute the average marks for each student
and determine the result status Pass/Fail based on the
calculated average. The application must demonstrate
robust exception handling by addressing various error
scenarios, such as: • Invalid marks (values less than 0
or greater than 100) - Null or missing data inputs •
Other runtime errors during data entry or processing
The program should incorporate key Java exception-
handling mechanisms, including: • Utilization of built-
in exceptions • Creation and implementation of a
custom exception class.
LAB ASSIGNMENT 01
Create a Student Record Management system that allows the user to input, display, and
calculate grades for students. Implement a class-based structure using Object- Oriented
Programming principles to manage student data such as roll number, name, course, marks,
and grade. The program should also allow the display of student records and calculate the
grade based on marks.
import [Link];
class Student {
private int rollNumber;
private String name;
private String course;
private int marks;
private char grade;
public void inputDetails() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Roll Number: ");
rollNumber = [Link]();
[Link]();
[Link]("Enter Name: ");
name = [Link]();
[Link]("Enter Course: ");
course = [Link]();
[Link]("Enter Marks (0-100): ");
marks = [Link]();
calculateGrade();
private void calculateGrade() {
if (marks >= 90)
grade = 'A';
else if (marks >= 75)
grade = 'B';
else if (marks >= 60)
grade = 'C';
else if (marks >= 40)
grade = 'D';
else
grade = 'F';
public void displayDetails() {
[Link]("\n--- Student Details ---");
[Link]("Roll Number : " + rollNumber);
[Link]("Name : " + name);
[Link]("Course : " + course);
[Link]("Marks : " + marks);
[Link]("Grade : " + grade);
}
}
public class StudentRecordSystem {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Student student = new Student();
int choice;
while (true) {
[Link]("\n==== Student Record Management System ====");
[Link]("1. Enter Student Details");
[Link]("2. Display Student Details");
[Link]("3. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
switch (choice) {
case 1:
[Link]();
break;
case 2:
[Link]();
break;
case 3:
[Link]("Exiting the program...");
return;
default:
[Link]("Invalid choice! Please try again.");
Output –
LAB ASSIGNMENT 02
Java program that counts how many times a specific character appears in a char] array .
public class CountCharacterExample {
public static void main(String[] args) {
char[] letters = {'a', 'b', 'a', 'c', 'd', 'a', 'b'};
char target = 'a';
int count = 0;
for (int i = 0; i < [Link]; i++) {
if (letters[i] == target) {
count++;
}
}
[Link]("Character '" + target + "' appears " + count + " times.");
}
}
Output –
LAB ASSIGNMENT 03
Create a Java class named Person with the following constructors: 1. A default constructor
that initializes the name to "Unknown" and age to 0. 2. A parameterized constructor that
initializes the name and age with given values. 3. A copy constructor that creates a new
Person object by copying the details from another Person object. Include a method to
display the person's details. Write a program to create and display details of three Person
objects: one using the default constructor, one using the parameterized constructor, and one
using the copy constructor.
class Person {
private String name;
private int age;
public Person() {
name = "Unknown";
age = 0;
public Person(String n, int a) {
name = n;
age = a;
public Person(Person other) {
[Link] = [Link];
[Link] = [Link];
public void display() {
[Link]("Name: " + name + ", Age: " + age);
public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person("Rahul", 22);
Person p3 = new Person(p2);
[Link]("Person 1:");
[Link]();
[Link]("\nPerson 2:");
[Link]();
[Link]("\nPerson 3 (Copy of Person 2):");
[Link]();
Output –
LAB ASSIGNMENT 04
Create a Java class named Shape with overloaded constructors to initialize attributes for
different shapes: one constructor to set the radius of a circle, and another to set the length
and width of a rectangle. Implement methods to calculate and display the area of the circle
and the rectangle separately. Write a program that creates instances of both shapes using
the appropriate constructors and displays their respective areas.
class Shape {
private double radius;
private double length;
private double width;
private boolean isCircle;
public Shape(double r) {
radius = r;
isCircle = true;
public Shape(double l, double w) {
length = l;
width = w;
isCircle = false;
public void displayArea() {
if (isCircle) {
double area = 3.14 * radius * radius;
[Link]("Area of Circle: " + area);
} else {
double area = length * width;
[Link]("Area of Rectangle: " + area);
public class ShapeTest {
public static void main(String[] args) {
Shape circle = new Shape(5.0);
Shape rectangle = new Shape(10.0, 4.0);
[Link]("Circle:");
[Link]();
[Link]("Rectangle:");
[Link]();
}
Output –
LAB ASSIGNMENT 05
Write a Java program to implement hierarchical inheritance. Create a base class Shape with
a method area. Derive two classes, Circle and Rectangle, from Shape. Override the area
method in both subclasses to calculate and display the area of a circle and a rectangle,
respectively. Use appropriate constructors to initialize the attributes (radius for the circle,
length, and width for the rectangle).
class Shape {
public void area() {
[Link]("Area of shape is not defined.");
}
}
class Circle extends Shape {
private double radius;
public Circle(double r) {
radius = r;
}
@Override
public void area() {
double a = 3.14 * radius * radius;
[Link]("Area of Circle: " + a);
}
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
@Override
public void area() {
double a = length * width;
[Link]("Area of Rectangle: " + a);
}
}
public class InheritanceTest {
public static void main(String[] args) {
Circle c = new Circle(5.0);
Rectangle r = new Rectangle(10.0, 4.0);
[Link]("Circle:");
[Link]();
[Link]("Rectangle:");
[Link]();
}
}
Output –
LAB ASSIGNMENT 06
A software company is developing a vehicle management system. As part of this system,
they have created a class named Car to represent basic car information. The design of the
class uses constructor overloading. The class includes: • A no-argument constructor, • A one-
argument constructor (brand), • A three-argument constructor (brand, model, year). • A
method displayinfol) to print the car's details. The constructors are designed to call each
other using the this keyword.
class Car {
private String brand;
private String model;
private int year;
public Car() {
this("Unknown");
public Car(String brand) {
this(brand, "Not Specified", 0);
public Car(String brand, String model, int year) {
[Link] = brand;
[Link] = model;
[Link] = year;
}
public void displayInfo() {
[Link]("Brand: " + brand);
[Link]("Model: " + model);
[Link]("Year : " + year);
public class CarTest {
public static void main(String[] args) {
Car c1 = new Car();
Car c2 = new Car("Toyota");
Car c3 = new Car("Honda", "Civic", 2020);
[Link]("Car 1 Details:");
[Link]();
[Link]("\nCar 2 Details:");
[Link]();
[Link]("\nCar 3 Details:");
[Link]();
Output –
LAB ASSIGNMENT 07
Design and implement a Java program to demonstrate multilevel inheritance using Student,
Marks, and Result classes. 1. Create a base class Student to store basic student details such
as rollNo, name, and course. 2. Derive a subclass Marks from Student to store marks of three
subjects. 3. Create another subclass Result derived from Marks to calculate the total marks,
percentage, and grade based on the marks entered. 4. Implement the following
functionalities: o Accept details of a student and their marks using constructors or methods.
o Calculate total marks and percentage in the Result class. o Assign a grade based on the
percentage using the following criteria: - 90% and above → Grade A - 75% to 89% → Grade B
- 50% to 74% → Grade C - Below 50% → Grade D 5. Display the complete student
information along with total marks, percentage, and grade.
import [Link];
class Student {
String name;
int rollNo;
String course;
void inputStudent() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Roll No: ");
rollNo = [Link]();
[Link]();
[Link]("Enter Name: ");
name = [Link]();
[Link]("Enter Course: ");
course = [Link]();
class Marks extends Student {
int m1, m2, m3;
void inputMarks() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Marks of Subject 1: ");
m1 = [Link]();
[Link]("Enter Marks of Subject 2: ");
m2 = [Link]();
[Link]("Enter Marks of Subject 3: ");
m3 = [Link]();
class Result extends Marks {
int total;
double percentage;
String grade;
void calculate() {
total = m1 + m2 + m3;
percentage = total / 3.0;
if (percentage >= 90)
grade = "A";
else if (percentage >= 75)
grade = "B";
else if (percentage >= 50)
grade = "C";
else
grade = "D";
void display() {
[Link]("\n--- Student Result ---");
[Link]("Roll No: " + rollNo);
[Link]("Name: " + name);
[Link]("Course: " + course);
[Link]("Marks: " + m1 + ", " + m2 + ", " + m3);
[Link]("Total Marks: " + total);
[Link]("Percentage: " + percentage);
[Link]("Grade: " + grade);
public class MultilevelTest {
public static void main(String[] args) {
Result r = new Result();
[Link]();
[Link]();
[Link]();
[Link]();
Output –
LAB ASSIGNMENT 08
Create an e-commerce system using method overriding. • Create a base class Product with
attributes like id, name, and price. • Define a method calculateDiscount) in the Product class.
• Create subclasses like Electronics, Clothing, and Groceries, each overriding
calculateDiscount to implement category-specific discount logic. • In the main class, create a
list of products using polymorphism, and calculate the final bill amount.
import [Link];
class Product {
int id;
String name;
double price;
public Product(int id, String name, double price) {
[Link] = id;
[Link] = name;
[Link] = price;
double calculateDiscount() {
return 0;
class Electronics extends Product {
public Electronics(int id, String name, double price) {
super(id, name, price);
}
double calculateDiscount() {
return price * 0.10;
class Clothing extends Product {
public Clothing(int id, String name, double price) {
super(id, name, price);
double calculateDiscount() {
return price * 0.20;
class Groceries extends Product {
public Groceries(int id, String name, double price) {
super(id, name, price);
double calculateDiscount() {
return price * 0.05;
public class EcommerceTest {
public static void main(String[] args) {
ArrayList<Product> cart = new ArrayList<>();
[Link](new Electronics(1, "Mobile Phone", 20000));
[Link](new Clothing(2, "T-Shirt", 800));
[Link](new Groceries(3, "Rice Bag", 1200));
double total = 0;
[Link]("--- Bill Details ---");
for (Product p : cart) {
double discount = [Link]();
double finalPrice = [Link] - discount;
[Link]([Link] + " - Price: " + [Link] +
", Discount: " + discount + ", Final: " + finalPrice);
total += finalPrice;
[Link]("\nTotal Bill Amount: " + total);
Output –
LAB ASSIGNMENT 09
Design a program to manage different types of transportation. • Create an abstract class
Transport with an abstract method calculateFare(distance). • Create subclasses Bus, Train,
and Flight that override calculatetarel with their own logic. • In the main class, dynamically
select a transport type at runtime using user input, then calculate the fare for a given
distance.
import [Link];
abstract class Transport {
abstract double calculateFare(double distance);
class Bus extends Transport {
double calculateFare(double distance) {
return distance * 5;
class Train extends Transport {
double calculateFare(double distance) {
return distance * 3;
class Flight extends Transport {
double calculateFare(double distance) {
return distance * 10;
}
public class TransportTest {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Transport t;
[Link]("Choose Transport Type:");
[Link]("1. Bus");
[Link]("2. Train");
[Link]("3. Flight");
[Link]("Enter choice: ");
int choice = [Link]();
if (choice == 1)
t = new Bus();
else if (choice == 2)
t = new Train();
else
t = new Flight();
[Link]("Enter distance: ");
double dist = [Link]();
double fare = [Link](dist);
[Link]("Total Fare: " + fare);
}
}
Output –
LAB ASSIGNMENT 10
Create a library management system where different types of users have different borrowing
privileges. • Create a superclass LibraryUser with attributes like userid and name, and a
method maxBooksAllowed).
• Subclasses Student, Teacher, and Researcher should override maxBooksAllowed) to specify
different borrowing limits. • In the main program: o Maintain a collection of library users. o
Display the borrowing limits dynamically using overridden methods. o Generate a report of
issued books and write it to a text file.
import [Link];
import [Link];
class LibraryUser {
int userId;
String name;
public LibraryUser(int userId, String name) {
[Link] = userId;
[Link] = name;
int maxBooksAllowed() {
return 0;
class Student extends LibraryUser {
public Student(int userId, String name) {
super(userId, name);
}
int maxBooksAllowed() {
return 3;
class Teacher extends LibraryUser {
public Teacher(int userId, String name) {
super(userId, name);
int maxBooksAllowed() {
return 6;
class Researcher extends LibraryUser {
public Researcher(int userId, String name) {
super(userId, name);
int maxBooksAllowed() {
return 10;
public class LibrarySystem {
public static void main(String[] args) {
ArrayList<LibraryUser> users = new ArrayList<>();
[Link](new Student(101, "Arjun"));
[Link](new Teacher(201, "Meera"));
[Link](new Researcher(301, "Ravi"));
[Link]("--- Borrowing Limits ---");
for (LibraryUser u : users) {
[Link]([Link] + " (User ID: " + [Link] +
") can borrow up to " + [Link]() + " books.");
try {
FileWriter fw = new FileWriter("[Link]");
[Link]("---- Library Borrowing Report ----\n");
for (LibraryUser u : users) {
[Link]([Link] + " (ID: " + [Link] + ") - Allowed Books: "
+ [Link]() + "\n");
[Link]();
[Link]("\nReport generated: [Link]");
} catch (Exception e) {
[Link]("Error writing file.");
Output –
LAB ASSIGNMENT 11
Design and implement a multithreaded Java program that performs different numerical tasks
concurrently using multiple threads. The program should: 1. Create three separate threads,
each performing a distinct task:
Thread 1: Prints even numbers from 1 to 20.
Thread 2: Prints odd numbers from 1 to 20.
Thread 3: Calculates and displays the sum of numbers from 1 to 20.
class EvenThread extends Thread {
public void run() {
[Link]("Even Numbers:");
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0)
[Link](i + " ");
[Link]();
class OddThread extends Thread {
public void run() {
[Link]("Odd Numbers:");
for (int i = 1; i <= 20; i++) {
if (i % 2 != 0)
[Link](i + " ");
[Link]();
}
class SumThread extends Thread {
public void run() {
int sum = 0;
for (int i = 1; i <= 20; i++) {
sum += i;
[Link]("Sum of numbers from 1 to 20: " + sum);
public class MultiThreadTest {
public static void main(String[] args) {
EvenThread t1 = new EvenThread();
OddThread t2 = new OddThread();
SumThread t3 = new SumThread();
[Link]();
[Link]();
[Link]();
Output –
LAB ASSIGNMENT 12
Discuss the concept of collections in Java. Write a code snippet to sort a List of strings in
ascending and descending order using the Collections class
In Java, Collections are used to store and manage groups of objects.
Instead of using arrays (which have fixed size), collections allow:
Dynamic size (you can grow or shrink the structure)
Built-in methods like sorting, searching, adding, removing
Different types of data structures like List, Set, Queue, etc.
The Collections Framework includes:
Interfaces → List, Set, Map, Queue
Classes → ArrayList, HashSet, LinkedList, HashMap, etc.
Utility class → Collections (used for sorting, reversing, etc.)
Code –
import [Link].*;
public class SortStringsExample {
public static void main(String[] args) {
// Creating a simple list of names
List<String> names = new ArrayList<>();
[Link]("Mohit");
[Link]("Aman");
[Link]("Rohit");
[Link]("Sumit");
[Link]("Original List: " + names);
// Sorting in ascending order
[Link](names);
[Link]("Ascending Order: " + names);
// Sorting in descending order
[Link](names, [Link]());
[Link]("Descending Order: " + names);
Output –
LAB ASSIGNMENT 13
Explain the use of byte streams in Java with examples of FileInputStream and
FileOutputStream. Write a code snippet to read a binary file and write its contents to
another binary file using these classes.
Byte streams are used to read and write raw binary data (like images, audio, video, .bin
files).
They work with 8-bit bytes and are ideal for non-text files.
Two main byte stream classes:
FileInputStream → reads bytes from a file
FileOutputStream → writes bytes to a file
Code –
import [Link].*;
public class BinaryCopy {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("[Link]");
FileOutputStream fos = new FileOutputStream("[Link]");
int byteData;
while ((byteData = [Link]()) != -1) {
[Link](byteData);
[Link]();
[Link]();
[Link]("File copied successfully!");
}
catch (IOException e) {
[Link]();
Output –
LAB ASSIGNMENT 14
Explain in detail the different types of Java 1/0 streams. Discuss Byte Streams, Character
Streams, Buffered Streams, and their commonly used classes with examples.
Java I/O streams are used to read and write data. They are mainly divided into:
1. Byte Streams (for binary data)
Used to read/write raw bytes.
Suitable for images, audio, video, .bin files, etc.
Work with 8-bit bytes.
Common Classes
Class Use
FileInputStream Reads bytes from a file
FileOutputStream Writes bytes to a file
2. Character Streams (for text data)
Used to read/write characters (16-bit Unicode).
Suitable for text files.
Common Classes
Class Use
FileReader Reads characters from a file
FileWriter Writes characters to a file
3. Buffered Streams (faster I/O using a buffer)
Buffered streams improve performance by using an internal buffer to reduce the number of
I/O operations.
Types
Buffered Byte Streams
Class Use
BufferedInputStream Faster byte reading
BufferedOutputStream Faster byte writing
LAB ASSIGNMENT 15
Explain the Java Collections Framework architecture. Describe the core interfaces such as
Collection, List, Set, Queue, and Map with examples of their implementations.
The Java Collections Framework provides a unified architecture to store, retrieve, and
manipulate groups of objects.
It contains interfaces, classes, and algorithms (like sorting, searching).
The architecture is mainly built around these core interfaces:
1. Collection Interface (Root interface)
Superinterface for List, Set, and Queue.
Represents a group of objects.
Common Implementations
ArrayList
HashSet
PriorityQueue
2. List Interface
Ordered collection (elements have index).
Allows duplicate elements.
Implementations
ArrayList → dynamic array
LinkedList → doubly linked list
Vector → synchronized list
Example
List<String> list = new ArrayList<>();
3. Set Interface
Unordered collection.
No duplicates allowed.
Implementations
HashSet → fast, no order
LinkedHashSet → maintains insertion order
TreeSet → sorted set
Example
Set<Integer> set = new HashSet<>();
4. Queue Interface
Follows FIFO (First-In First-Out).
Used for processing tasks in order.
Implementations
LinkedList
PriorityQueue (elements sorted by priority)
Example
Queue<String> q = new LinkedList<>();
5. Map Interface (NOT a child of Collection)
Stores data in key–value pairs.
Keys must be unique.
Implementations
HashMap → fast, no order
LinkedHashMap → maintains insertion order
TreeMap → sorted by keys
Example
Map<Integer, String> map = new HashMap<>();
LAB ASSIGNMENT 16
Write a Java program to demonstrate ArrayList operations such as adding, removing,
searching, and updating elements.
import [Link];
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
[Link]("Mohit");
[Link]("Aman");
[Link]("Rahul");
[Link]("Vikas");
[Link]("After Adding: " + names);
[Link]("Aman");
[Link]("After Removing: " + names);
boolean found = [Link]("Rahul");
[Link]("Is Rahul present? " + found);
[Link](1, "Sahil");
[Link]("After Updating: " + names);
[Link]("Element at index 0: " + [Link](0));
Output –
LAB ASSIGNMENT 17
Design and implement a Student Result Management System that efficiently collects and
manages student details along with their subject marks. The system should compute the
average marks for each student and determine the result status Pass/Fail based on the
calculated average. The application must demonstrate robust exception handling by
addressing various error scenarios, such as: • Invalid marks (values less than 0 or greater
than 100) - Null or missing data inputs • Other runtime errors during data entry or
processing The program should incorporate key Java exception-handling mechanisms,
including: • Utilization of built-in exceptions • Creation and implementation of a custom
exception class.
import [Link].*;
class InvalidMarksException extends Exception {
public InvalidMarksException(String msg) {
super(msg);
class Student {
String name;
int roll;
int[] marks;
double average;
String result;
public Student(String name, int roll, int[] marks) throws InvalidMarksException {
for (int m : marks) {
if (m < 0 || m > 100) {
throw new InvalidMarksException("Marks must be between 0 and 100.");
[Link] = name;
[Link] = roll;
[Link] = marks;
calculateResult();
private void calculateResult() {
int total = 0;
for (int m : marks) {
total += m;
average = total / 3.0;
if (average >= 40)
result = "Pass";
else
result = "Fail";
public void display() {
[Link]("\n--- Student Result ---");
[Link]("Name: " + name);
[Link]("Roll No: " + roll);
[Link]("Marks: " + [Link](marks));
[Link]("Average: " + average);
[Link]("Result: " + result);
public class StudentResultSystem {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter Student Name: ");
String name = [Link]();
if (name == null || [Link]().isEmpty()) {
throw new NullPointerException("Name cannot be empty.");
[Link]("Enter Roll Number: ");
int roll = [Link]();
int[] marks = new int[3];
[Link]("Enter marks of 3 subjects:");
for (int i = 0; i < 3; i++) {
[Link]("Subject " + (i + 1) + ": ");
marks[i] = [Link]();
Student s = new Student(name, roll, marks);
[Link]();
} catch (InvalidMarksException e) {
[Link]("Error: " + [Link]());
} catch (InputMismatchException e) {
[Link]("Error: Please enter only numeric values for roll number and
marks.");
} catch (NullPointerException e) {
[Link]("Error: " + [Link]());
} catch (Exception e) {
[Link]("Some error occurred: " + [Link]());
[Link]("\nProgram Finished.");
}
Output –