0% found this document useful (0 votes)
1 views32 pages

Introduction To Java LAB MANUAL

The document is a lab manual for an Introduction to Java course, covering three main experiments: salary calculation using method overloading, inheritance and method overriding with a university management system, and implementing multiple inheritance through interfaces in an online learning platform. Each experiment includes a description of the task, core Java concepts, pseudo code, and Java code examples to demonstrate the implementation. The manual emphasizes key object-oriented programming principles such as polymorphism, inheritance, and interface usage.

Uploaded by

24ug1bycs608
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views32 pages

Introduction To Java LAB MANUAL

The document is a lab manual for an Introduction to Java course, covering three main experiments: salary calculation using method overloading, inheritance and method overriding with a university management system, and implementing multiple inheritance through interfaces in an online learning platform. Each experiment includes a description of the task, core Java concepts, pseudo code, and Java code examples to demonstrate the implementation. The manual emphasizes key object-oriented programming principles such as polymorphism, inheritance, and interface usage.

Uploaded by

24ug1bycs608
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

​Introduction to Java LAB MANUAL​

​(BCS456F: Introduction to Java)​


​Experiment 1​​:​
​ ​ ​company​ ​wants​ ​to​ ​calculate​ ​salaries​ ​for​ ​its​ ​employees.​ ​The​ ​salary​ ​calculation​ ​varies​ ​depending​ ​on​ ​the​
A
​employee type:​
​• For a regular employee, the salary is just the basic salary.​
​• For employees who receive a bonus, the salary is basic salary + bonus.​
​• For employees who receive bonus and allowance, the salary is basic salary + bonus + allowance.​
​Create a class​​Salary Calculator​​with a method​​calculateSalary(​​)​​overloaded to handle all three cases.​
​Write a main method to demonstrate the calculation of salary for:​
​• A regular employee​
​• An employee with bonus​
​• An employee with a bonus and allowance.​
​Use​ ​method​ ​overloading​ ​to​ ​implement​ ​calculateSalary().​ ​Display​ ​the​ ​calculated​ ​salary​ ​for​ ​each​ ​type​ ​of​
​employee.​

​Solution :​

​Method overloading​

​Polymorphism in Java is a core concept of Object-Oriented Programming (OOP) that allows a single​
​action to be performed in different ways.​

​In Java, it typically involves a superclass reference variable referring to a subclass object, enabling flexibility​
​and code reusability.​

​Types of Polymorphism​

​Java primarily supports two types of polymorphism:​

​1. Compile-Time Polymorphism (Static Polymorphism)​

​This is resolved by the compiler during the compilation of the program.​

​Method Overloading​​: Occurs when multiple methods in​​the same class have the​​same name but different​

​parameters​​(different count, type, or order).​


​Example​​: A sum() method that can add two integers, three integers, or two double values.​

​•​​Note​​: Java also has internal​​operator overloading​​(e.g., the​​+​​o​perator for both addition and string​

​concatenation), but it does not support user-defined operator overloading.​

​2. Runtime Polymorphism (Dynamic Polymorphism)​

​This is resolved by the Java Virtual Machine (JVM) at runtime through a process called​

​Dynamic Method Dispatch​​.​

​Method​​Overriding​​:​​when​​a​​method​​or​​function​​declared​​in​​derived​​class​​which​​has​​the​​same​​name​​and​​type​

​signature​​as​​method​​declared​​in​​based​​class,​​then​​the​​method​​in​​the​​derived​​class​​set​​to​​override​​a​​method​​in​​the​

​base class This mechanism is called as Method Overriding.​

​Pseudo Code​​:​

​ TART​
S
​1. Create SalaryCalculator class​
​2. Overload calculateSalary() for three cases with appropriate parameters:​
​●​ ​basicSalary only​
​●​ ​basicSalary + bonus​
​●​ ​basicSalary + bonus + allowance​
​3. Create a class for the main​
​4. In main():​
​Declare three variables​
​Create an object of the class​
​Take input for Case1​
​• Call the appropriate function​
​• Print formatted results for Case1​
​Take input for Case2​
​• Call the appropriate function​
​• Print formatted results for Case2​
​Take input for Case3​
​• Call the appropriate function​
​• Print formatted results for Case3​
​STOP​
​Java Code:​
​class Salary Calculator {​
​// Case 1: Regular Employee - Basic Salary only​
​double calculateSalary(double basicSalary) {​
​return basicSalary;​
​}​

​// Case 2: Employee with Bonus - Basic Salary + Bonus​


​double calculateSalary(double basicSalary, double bonus) {​
​return basicSalary + bonus;​
​}​

​// Case 3: Employee with Bonus and Allowance - Basic Salary + Bonus + Allowance​
​double calculateSalary(double basicSalary, double bonus, double allowance) {​
​return basicSalary + bonus + allowance;​
​}​

​public static void main(String[] args) {​


​SalaryCalculator calculator = new SalaryCalculator();​

​// 1. Regular Employee​


​double regularSalary = [Link](50000);​
​[Link]("Regular Employee Salary: " + regularSalary);​

​// 2. Employee with Bonus​


​double bonusSalary = [Link](50000, 5000);​
​[Link]("Employee with Bonus Salary: " + bonusSalary);​

​// 3. Employee with Bonus and Allowance​


​double totalSalary = [Link](50000, 5000, 2000);​
​[Link]("Employee with Bonus and Allowance Salary: " + totalSalary);​
​}​
​}​
​Experiment 2: Inheritance & Method Overriding​
​A​​university​​needs​​to​​manage​​information​​about​​various​​individuals​​associated​​with​​it.​​Create​​a​​class​​hierarchy​
​in​​which​​a​​base​​class​​Person​​contains​​common​​attributes​​such​​as​​name,​​age,and​​address.​​Derive​​two​​subclasses,​
​Student​​and​​Faculty,​​where​​Student​​includes​​additional​​attributes​​rollNumber​​and​​course,​​and​​Faculty​​includes​
​employeeId​ ​and​ ​department.​ ​Design​ ​the​ ​above​​class​​hierarchy​​using​​inheritance​​and​​write​​a​​Java​​program​​to​
​demonstrate​ ​single​ ​inheritance​ ​and​ ​method​ ​overriding,​ ​where​ ​both​ ​Student​ ​and​ ​Faculty​ ​override​ ​a​ ​common​
​method display Details() to display their respective information.​

​Inheritance in Java​

​Inheritance​ ​in​ ​Java​ ​is​ ​a​ ​core​ ​principle​ ​of​ ​Object-Oriented​ ​Programming​ ​(OOP)​ ​that​ ​allows​ ​a​ ​new​ ​class​
​(subclass​​or​​child​​class)​​to​​inherit​​properties​​(fields)​​and​​behaviors​​(methods)​​from​​an​​existing​​class​​(superclass​
​or parent class)​​.​

​•​​subclass​​(child) - the class that inherits from​​another class​


​•​​superclass​​(parent) - the class being inherited​​from​

​To inherit from a class, use the​​extends​​keyword.​

​Pseudo Code:​

​START​
​Create a base class Person​

​Declare variables: name, age, address​


​Define method displayDetails()​

​Create subclass Student that extends Person​


​Declare variables: rollNumber, course​
​Override displayDetails()​
​Display name, age, address, rollNumber, course​

​Create subclass Faculty that extends Person​


​Declare variables: employeeId, department​
​Override displayDetails()​
​Display name, age, address, employeeId, department​
​In main method​
​Create Student object​
​Assign values to Student attributes​
​Call displayDetails()​

​Create Faculty object​


​Assign values to Faculty attributes​
​Call displayDetails()​
​STOP​

​Java Code:​

​// Base class​


​class Person {​
​String name;​
​int age;​
​String address;​

​Person(String name, int age, String address) {​


​[Link] = name;​
​[Link] = age;​
​[Link] = address;​
​}​

​// Common method to be overridden​


​void displayDetails() {​
​[Link]("Name: " + name);​
​[Link]("Age: " + age);​
​[Link]("Address: " + address);​
​}​
​}​

​// Subclass Student inheriting from Person​


​class Student extends Person {​
​String rollNumber;​
​String course;​

​Student(String name, int age, String address, String rollNumber, String course) {​
​super(name, age, address); // Calling parent constructor​
​[Link] = rollNumber;​
​[Link] = course;​
​}​

​@Override​
​void displayDetails() {​
​[Link]("--- Student Details ---");​
​[Link](); // Calling parent display method​
​[Link]("Roll Number: " + rollNumber);​
​[Link]("Course: " + course);​
​[Link]();​
​}​
​}​

​// Subclass Faculty inheriting from Person​


​class Faculty extends Person {​
​String employeeId;​
​String department;​

​Faculty(String name, int age, String address, String employeeId, String department) {​
​super(name, age, address); // Calling parent constructor​
​[Link] = employeeId;​
​[Link] = department;​
​}​

​@Override​
​void displayDetails() {​
​[Link]("--- Faculty Details ---");​
​[Link](); // Calling parent display method​
​[Link]("Employee ID: " + employeeId);​
​[Link]("Department: " + department);​
​[Link]();​
​}​
​}​

​public class University Management {​


​public static void main(String[] args) {​
​// Creating instances of Student and Faculty​
​Student s1 = new Student("Alice Johnson", 20, "123 Maple St", "S101", "Computer Science");​
​Faculty f1 = new Faculty("Dr. Robert Smith", 45, "456 Oak Ave", "F202", "Physics");​

​// Demonstrating method overriding​


​[Link]();​
​[Link]();​
​}​
​}​
​Experiment 3: Interfaces​
​An​ ​online​ ​learning​ ​platform​ ​offers​ ​courses​ ​that​ ​include​ ​both​ ​video-based​ ​instruction​ ​and​ ​assignment-based​
​evaluation.​​Define​​an​​interface​​VideoContentwith​​a​​method​​playVideo()​​and​​another​​interface​​Assessment​​with​
​a​​method​​submitAssignment().​​Create​​a​​class​​OnlineCourse​​that​​implements​​both​​interfaces.​​Design​​the​​system​
​and​ ​write​ ​a​ ​Java​ ​program​ ​to​ ​demonstrate​ ​multiple​ ​inheritance​ ​using​ ​interfaces​​,​ ​showing​ ​how​ ​the​ ​class​
​OnlineCourse​​implements​​the​​interfaces​​and​​how​​the​​methods​​are​​invoked​​using​​an​​object​​of​​the​​OnlineCourse​
​class.​

​Multiple Inheritance using Interfaces in Java​

​While​ ​Java​ ​does​ ​not​ ​support​ ​multiple​ ​inheritance​ ​with​ ​classes,​ ​it​ ​achieves​ ​multiple​ ​inheritance​ ​of​ ​type​ ​and​
​behavior​ ​(since​ ​Java​ ​8)​ ​through​ ​the​​use​​of​​interfaces​​.​​A​​single​​Java​​class​​can​​implement​​multiple​​interfaces,​
​allowing it to act as multiple different types and adhere to multiple contracts.​

​How It Works​

​Java​ ​restricts​ ​class​ ​inheritance​ ​to​ ​a​ ​single​ ​parent​ ​class​ ​to​ ​avoid​ ​complexity​ ​and​ ​ambiguity​ ​issues​ ​like​ ​the​

​"diamond​ ​problem".​ ​Interfaces​ ​resolve​ ​this​ ​problem​ ​because​ ​traditionally​ ​they​ ​only​ ​contained​ ​method​

​declarations (signatures) but no implementations.​

​The​​class​​that​​implements​​the​​interfaces​​is​​responsible​​for​​providing​​the​​concrete​​implementation​​for​​all​​abstract​

​methods, eliminating any ambiguity about which method to call.​

​Interface in Java​

​An Interface in Java is an abstract type that defines a set of methods a class must implement.​
•​ ​​An​​interface​​acts​​as​​a​​contract​​that​​specifies​​what​​a​​class​​should​​do,​​but​​not​​how​​it​​should​​do​​it.​​It​​is​​used​​to​
​achieve abstraction and​​multiple inheritance​​in Java.​
​•​ ​A​ ​class​ ​that​ ​implements​ ​an​ ​interface​ ​must​ ​implement​ ​all​ ​the​ ​methods​ ​of​ ​the​ ​interface.​ ​Only​ ​variables​ ​are​
​public static final by default.​

•​ ​ ​Before​ ​Java​ ​8,​ ​interfaces​ ​could​ ​only​ ​have​ ​abstract​ ​methods​​(no​​bodies).​​Since​​Java​​8,​​they​​can​​also​​include​


​default​​and​​static​​methods (with implementation) and​​since Java 9,​​private methods​​are allowed.​
​When to Use Class and Interface?​

​ se a Class when​​:​
U
​• Use a class when you need to represent a real-world entity with attributes (fields) and behaviors (methods).​
​• Use a class when you need to create objects that hold state and perform actions​
​• Classes are used for defining templates for objects with specific functionality and properties.​
​Use an Interface when:​
​• Use an interface when you need to define a contract for behavior that multiple classes can implement.​
​• Interface is ideal for achieving abstraction and multiple inheritance.​
​Implementation:​​To implement an interface, we use​​the keyword​​implements​

​Syntax​
​[access_modifier] interface InterfaceName {​
​// declare constants (implicitly public static final)​
​int CONSTANT_NAME = 10;​

​// declare abstract methods (implicitly public abstract)​


​void abstractMethod();​

​// declare default methods (Java 8+)​


​default void defaultMethod() {​
​// method body here​
​}​

​// declare static methods (Java 8+)​


​static void staticMethod() {​
​// method body here​
​}​

​// declare private methods (Java 9+)​


​private void privateMethod() {​
​// method body here, only callable within the interface​
​}​
​}​
​Pseudo Code:​
​// 1. Define the first interface: VideoContent​
​interface VideoContent {​
​method playVideo()​
​}​

​// 2. Define the second interface: Assessment​


​interface Assessment {​
​method submitAssignment()​
​}​

​// 3. Create a class that implements both interfaces​


​class OnlineCourse implements VideoContent, Assessment {​

​// Implementation of the playVideo method from VideoContent interface​


​method playVideo() {​
​print "Playing the course video..."​
​// Add specific video playback logic here​
​}​

​// Implementation of the submitAssignment method from Assessment interface​


​method submitAssignment() {​
​print "Submitting the course assignment..."​
​// Add specific assignment submission logic here​
​}​
​}​

​// 4. Create a separate main function/class to demonstrate the implementation​


​class Main {​
​method main() {​
​// Create an object of the OnlineCourse class​
​object course = new OnlineCourse()​
​// Invoke methods from both interfaces using the OnlineCourse object​
​[Link]()​
​[Link]()​
​}​
​}​

​Java code​

​// Define the first interface for video-based instruction​


​interface VideoContent {​
​void playVideo();​
​}​

​// Define the second interface for assignment-based evaluation​


​interface Assessment {​
​void submitAssignment();​
​}​

​// The class OnlineCourse implements both interfaces, achieving a form of multiple inheritance​
​class OnlineCourse implements VideoContent, Assessment {​
​private String courseTitle;​

​public OnlineCourse(String title) {​


​[Link] = title;​
​}​

​// Implementation of the playVideo() method from the VideoContent interface​


​@Override​
​public void playVideo() {​
​[Link]("Playing video instruction for: " + courseTitle);​
​}​

​// Implementation of the submitAssignment() method from the Assessment interface​


​@Override​
​public void submitAssignment() {​
​[Link]("Submitting assignment for: " + courseTitle);​
​}​
​}​

​// Main class to demonstrate the system​


​public class CourseDemo {​
​public static void main(String[] args) {​
​// Create an object of the OnlineCourse class​
​OnlineCourse javaCourse = new OnlineCourse("Introduction to Java Programming");​

​// Invoke methods from both interfaces using the OnlineCourse object​
​[Link]();​
​[Link]();​

​// An object of OnlineCourse can also be referred to by either interface type​


​VideoContent videoRef = javaCourse;​
​[Link]();​

​Assessment assessmentRef = javaCourse;​


​[Link]();​
​}​
​}​
​Experiment 4:​
​Consider​ ​a​ ​scenario​ ​where​ ​a​ ​system​ ​continuously​ ​monitors​ ​randomly​ ​generated​ ​numbers​ ​and​​processes​​them​
​based​ ​on​​their​​nature.​​The​​application​​is​​designed​​using​​multithreading​​and​​consists​​of​​three​​threads.​​The​​first​
​thread​​acts​​as​​a​​number​​generator,​​producing​​a​​random​​integer​​every​​one​​second.​​Once​​a​​number​​is​​generated,​​it​
​is​​evaluated​​for​​parity.​​If​​the​​number​​is​​even,​​the​​second​​thread​​is​​triggered​​to​​compute​​and​​display​​its​​square.​​If​
​the​ ​number​ ​is​ ​odd,​ ​the​ ​third​ ​thread​ ​takes​ ​over​ ​and​ ​computes​ ​and​ ​displays​ ​its​ ​cube.​ ​This​ ​coordinated​
​multithreaded approach ensures simultaneous number generation and conditional processing.​

​Thread Lifecycle​

​A thread goes through several states during its lifetime, managed by the JVM:​

​•​​New​​: The thread has been created but not yet started.​

​•​​Runnable​​: The thread is ready to run and is waiting​​for CPU time from the thread scheduler.​

​•​​Running​​: The thread is actively executing its code​​on the CPU.​

​•​​Blocked/Waiting/Timed Waiting​​: The thread is temporarily​​inactive, waiting for a resource (like a lock) or​

​for a specified duration (e.g., via sleep() or join()).​

​•​​Terminated (Dead)​​: The thread has completed its​​execution.​

​Multithreading​

​Multithreading​ ​in​ ​Java​ ​is​ ​a​ ​feature​ ​that​ ​allows​ ​multiple​ ​threads​ ​of​ ​execution​​to​​run​​concurrently​​within​​a​
​single​ ​program​​,​ ​maximizing​ ​CPU​ ​utilization​ ​and​ ​improving​ ​performance.​ ​Threads​ ​are​ ​lightweight​
​sub-processes​ ​that​ ​share​ ​the​ ​same​​memory​​space,​​enabling​​efficient​​communication​​and​​allowing​​applications​
​to remain responsive while performing background tasks.​

​Creating Threads​

​Threads in Java can be created using two primary methods:​

​Extending​​the​​Thread​​class​​:​​A​​class​​can​​inherit​​from​​the​​Thread​​class​​and​​override​​its​​run()​​method​​to​​define​
​the​​task​​the​​thread​​will​​execute.​​An​​instance​​is​​then​​created​​and​​started​​using​​the​​start()​​method,​​which​​calls​​the​
​run() method in a new thread.​
​Implementing​ ​the​ ​Runnable​ ​interface​​:​ ​This​ ​approach​ ​is​ ​often​ ​preferred​ ​as​ ​Java​ ​does​ ​not​ ​support​ ​multiple​
​inheritance,​​so​​implementing​​Runnable​​allows​​the​​class​​to​​extend​​another​​class​​if​​needed.​​The​​run()​​method​​is​
​implemented, and a​​Thread​​object is instantiated with​​the​​Runnable​​instance and started with start().​

​Synchronization and Concurrency Control​

​When multiple threads access shared data, issues like​​race conditions​​and data inconsistency can arise.​​Java​

​provides mechanisms to manage this:​

​• synchronized​​Keyword​​: Ensures that only one thread​​can execute a synchronized method or block of code on​

​a given object instance at a time, providing a lock (monitor) on the object.​

​•​​volatile Keyword​​: Ensures that changes to a variable​​are immediately visible to all threads by reading its​

​latest value from main memory.​

​•​​wait(), notify(), notifyAll()​​: These methods (part​​of the​​Object​​class) enable inter-thread communication​

​within synchronized blocks, allowing threads to coordinate actions and signal each other when conditions are​

​met.​

​Example:​

​public class MyRunnable implements Runnable {​

​public void run() {​

​[Link]("Thread is running...");​

​}​

​public static void main(String[] args) {​

​MyRunnable runnable = new MyRunnable();​

​Thread t1 = new Thread(runnable);​


​[Link](); // Starts the thread and executes the run method​

​}​

​}​

​Note:​

​To prevent race conditions and ensure thread-safe processing of the random numbers, synchronization is​

​required (e.g., using shared variables, semaphores, or a thread-safe queue). The generator thread notifies the​

​appropriate consumer thread to process the new data immediately after generation​​.​

​Java Code:​

​import [Link];​
​// Shared class for communication​
​class SharedData {​
​int n;​
​boolean isEven;​
​boolean isSet = false;​

​// Synchronized method for producer to put data​


​synchronized void put(int n, boolean isEven) {​
​while (isSet) { // Wait if previous number is not processed​
​try { wait(); } catch (InterruptedException e) {}​
​}​
​this.n = n;​
​[Link] = isEven;​
​isSet = true;​
​[Link]("Generated: " + n);​
​notifyAll(); // Wake up consumers​
​}​

​// Synchronized method for consumers to get data​


​synchronized void get() {​
​while (!isSet) { // Wait if no new data​
​try { wait(); } catch (InterruptedException e) {}​
​}​
​if (isEven) {​
​[Link]("Even Handler -> Square: " + (n * n));​
​} else {​
​[Link]("Odd Handler -> Cube: " + (n * n * n));​
​}​
​isSet = false;​
​notifyAll(); // Wake up producer​
​}​
​}​
​// Thread 1: Generator​
​class Producer extends Thread {​
​SharedData sd;​
​Producer(SharedData sd) { [Link] = sd; }​
​public void run() {​
​Random rand = new Random();​
​for (int i = 0; i < 5; i++) {​
​int num = [Link](10);​
​[Link](num, num % 2 == 0);​
​try { [Link](1000); } catch (InterruptedException e) {}​
​}​
​}​
​}​

​// Thread 2/3: Consumers​


​class Consumer extends Thread {​
​SharedData sd;​
​Consumer(SharedData sd) { [Link] = sd; }​
​public void run() {​
​for (int i = 0; i < 5; i++) {​
​[Link]();​
​}​
​}​
​}​
​public class ThreadDemo {​
​public static void main(String[] args) {​
​SharedData sd = new SharedData();​
​new Producer(sd).start();​
​new Consumer(sd).start();​
​}​
​}​
​Experiment 5​
​ nalyze the given scenario A university system manages student grades and file storage:​
A
​Reads student names and marks from user input.​
​• Throws InvalidGradeException if marks are not in 0–100.​
​• Handles NumberFormatException for invalid numeric input.​
​• Handles ArithmeticException while calculating average marks (division by zero).​
​• Handles ArrayIndexOutOfBoundsException when accessing a student in the array.​
​• Handles NullPointerException if a student object is null.​
​• Writes the grades to a file and handles IOException.​
​Write a Java Program to implement the above Exceptions.​

​ his program simulates a simple university system that manages student records and​
T
​demonstrates how different types of exceptions are handled in Java.​
​1. Input Handling​
​The program takes student name and marks from the user.​
​Marks are entered as a string and converted into an integer.​
​If conversion fails, a NumberFormatException is handled.​
​2. Custom Exception (InvalidGradeException)​
​A user-defined exception is created.​
​It is thrown when marks are outside the valid range (0–100).​
​This ensures data integrity.​
​3. Storing Data​
​Student objects are stored in an array.​
​Each object contains:​
​o Name​
​o Marks​
​4. Average Calculation​
​The program calculates the average marks.​
​If no valid students exist, division by zero may occur.​
​This is handled using ArithmeticException.​
​5. Array Access​
​The program intentionally accesses an invalid index.​
​This demonstrates handling of ArrayIndexOutOfBoundsException.​
​6. Null Handling​
​If any student object is null, accessing its fields causes a NullPointerException.​
​This is caught and handled safely.​
​7. File Handling​

​Student details are written to a file ([Link]).​


​ ny file-related errors are handled using IOException.​
A
​8. Finally Block​
​The finally block ensures file-writing logic runs regardless of exceptions.​

​Algorithm​
​ tep-by-step procedure:​
S
​1. Start​
​2. Create a Student class with:​
​Name​
​marks​
​3. Define a custom exception:​
​InvalidGradeException​
​4. Create an array to store student objects.​
​5. Repeat for each student:​
​Input student name​
​Input marks as string​
​Convert string to integer​
​If invalid → handle NumberFormatException​
​Check marks range:​
​If not between 0–100 → throw InvalidGradeException​
​Store student object in array​
​6. Initialize variables:​
​sum = 0​
​count = 0​
​7. Traverse student array:​
​If student is not null:​
​Add marks to sum​
​Increment count​
​8. Calculate average:​
​average = sum / count​
​Handle ArithmeticException (if count = 0)​
​9. Access an invalid index in array:​
​Handle ArrayIndexOutOfBoundsException​
​10. Access student object:​
​Handle NullPointerException​
​11. Write student data to file:​
​Open file​
​Write each student's details​
​Close file​
​Handle IOException​
​12. End program​

​ ode:​
C
​import [Link].*;​
​import [Link].*;​
​// Custom Exception​
​class InvalidGradeException extends Exception {​
​public InvalidGradeException(String message) {​
​super(message);​
​}​
​}​
​// Student Class​
​class Student {​
​String name;​
​int marks;​
​Student(String name, int marks) {​
​[Link] = name;​
​[Link] = marks;​
​}​
​}​
​public class UniversitySystem {​
​public static void main(String[] args) {​
​Scanner sc = new Scanner([Link]);​
​Student[] students = new Student[3];​
​try {​
​// Input student data​
​for (int i = 0; i < [Link]; i++) {​
​[Link]("Enter student name: ");​
​String name = [Link]();​
​[Link]("Enter marks: ");​
​String input = [Link]();​
​int marks;​
​// Handle NumberFormatException​
​try {​
​marks = [Link](input);​
​} catch (NumberFormatException e) {​
​[Link]("Invalid number format! Setting marks to 0.");​
​marks = 0;​
​}​
​// Validate marks (Custom Exception)​
i​f (marks < 0 || marks > 100) {​
​throw new InvalidGradeException("Marks should be between 0 and 100.");​
​}​
​students[i] = new Student(name, marks);​
​}​

/​/ Calculate average (ArithmeticException)​


​int sum = 0;​
​int count = 0;​
​for (Student s : students) {​
​if (s != null) {​
​sum += [Link];​
​count++;​
​}​
​}​
​int average = sum / count; // may throw ArithmeticException​
​[Link]("Average Marks: " + average);​
​// Access array element (ArrayIndexOutOfBoundsException)​
​[Link]("Accessing 5th student:");​
​[Link](students[4].name);​
​} catch (InvalidGradeException e) {​
​[Link]("InvalidGradeException: " + [Link]());​
​} catch (ArithmeticException e) {​
​[Link]("ArithmeticException: Cannot divide by zero.");​
​} catch (ArrayIndexOutOfBoundsException e) {​
​[Link]("ArrayIndexOutOfBoundsException: Invalid index.");​
​} catch (NullPointerException e) {​
​[Link]("NullPointerException: Student object is null.");​
​} finally {​
​// File writing with IOException handling​
​try {​
​FileWriter fw = new FileWriter("[Link]");​
​for (Student s : students) {​
​if (s != null) {​
​[Link]([Link] + " - " + [Link] + "\n");​
​}​
​}​
​[Link]();​
​[Link]("Grades written to file successfully.");​
​} catch (IOException e) {​
​ [Link]("IOException: Error writing to file.");​
S
​}​
​}​
​[Link]();​
​}​
​}​

​ lternate Version :​
A
​import [Link].*;​
​import [Link].*;​
​// Custom Exception​
​class InvalidGradeException extends Exception {​
​public InvalidGradeException(String msg) {​
​super(msg);​
​}​
​}​
​// Student Class​
​class Student {​
​String name;​
​int marks;​
​Student(String name, int marks) {​
​[Link] = name;​
​[Link] = marks;​
​}​
​}​
​public class UniversitySystemAlt {​
​// Method to read student data​
​public static Student readStudent(Scanner sc) {​
​try {​
​[Link]("Enter name: ");​
​String name = [Link]();​
​[Link]("Enter marks: ");​
​int marks = [Link]([Link]());​
​if (marks < 0 || marks > 100) {​
​throw new InvalidGradeException("Marks must be 0–100");​
​}​
​return new Student(name, marks);​
​} catch (NumberFormatException e) {​
​[Link]("Invalid number! Default marks = 0");​
​return new Student("Unknown", 0);​
}​ catch (InvalidGradeException e) {​
​[Link]([Link]());​
​return new Student("Invalid", 0);​
​}​
​}​
​// Method to calculate average​
​public static double calculateAverage(List<Student> list) {​
​int sum = 0;​
​for (Student s : list) {​
​if (s == null) {​

t​hrow new NullPointerException("Student is null");​


​}​
​sum += [Link];​
​}​
​return sum / [Link](); // may throw ArithmeticException​
​}​
​// Method to write file​
​public static void writeToFile(List<Student> list) {​
​try (FileWriter fw = new FileWriter("[Link]")) {​
​for (Student s : list) {​
​[Link]([Link] + " - " + [Link] + "\n");​
​}​
​[Link]("File written successfully");​
​} catch (IOException e) {​
​[Link]("Error writing file");​
​}​
​}​
​public static void main(String[] args) {​
​Scanner sc = new Scanner([Link]);​
​List<Student> students = new ArrayList<>();​
​// Input​
​for (int i = 0; i < 3; i++) {​
​[Link](readStudent(sc));​
​}​
​// Average Calculation​
​try {​
​double avg = calculateAverage(students);​
​[Link]("Average = " + avg);​
​} catch (ArithmeticException e) {​
​ [Link]("Cannot divide by zero");​
S
​} catch (NullPointerException e) {​
​[Link]([Link]());​
​}​
​// Demonstrate Index Exception​
​try {​
​[Link]([Link](5).name);​
​} catch (IndexOutOfBoundsException e) {​
​[Link]("Invalid index access");​
​}​
​// File Writing​
​writeToFile(students);​
​[Link](); } }​
​Experiment 6​

​ rite​​a​​java​​program​​to​​create​​an​​abstract​​class​​named​​shape​​that​​contains​​an​​empty​​method​​named​​number​​of​
W
​sides​​().​​Provide​​three​​classes​​named​​trapezoid,​​triangle​​and​​Hexagon​​such​​that​​each​​one​​of​​the​​classes​​extends​
​the​ ​class​ ​shape.​ ​Each​ ​one​ ​of​ ​the​ ​class​ ​contains​ ​only​​the​​method​​number​​of​​sides​​()​​that​​shows​​the​​number​​of​
​sides in the given geometrical figures.​

​ bstract Class: Shape​


A
​Declared using the keyword abstract.​
​Contains an abstract method numberOfSides().​
​This method has no body (only declaration).​
​It forces all child classes to implement it.​
​Derived Classes​
​Three classes extend the abstract class:​
​1. Trapezoid​
​o Implements numberOfSides()​
​o Prints → 4 sides​
​2. Triangle​
​o Implements numberOfSides()​
​o Prints → 3 sides​
​3. Hexagon​
​o Implements numberOfSides()​
​o Prints → 6 sides​

​ ey Concept​
K
​Abstract class = blueprint​
​Subclasses = provide actual implementation​
​Achieves runtime polymorphism​

​ lgorithm​
A
​Step-by-step:​
​1. Start​
​2. Create an abstract class Shape​
​Declare abstract method numberOfSides()​
​3. Create class Trapezoid extending Shape​
​Define numberOfSides() → print "4 sides"​
​4. Create class Triangle extending Shape​
​Define numberOfSides() → print "3 sides"​
​5. Create class Hexagon extending Shape​
​Define numberOfSides() → print "6 sides"​
​6. In main() method:​
​Create objects of all three classes​
​Call numberOfSides() using each object​
​7. End​

​ ode:​
C
​abstract class Shape {​
​// Abstract method​
​abstract void numberOfSides();​
​}​
​// Trapezoid Class​
​class Trapezoid extends Shape {​
​void numberOfSides() {​
​[Link]("Trapezoid has 4 sides");​
​}​
​}​
​// Triangle Class​
​class Triangle extends Shape {​
​void numberOfSides() {​
​[Link]("Triangle has 3 sides");​
​}​
​}​
​// Hexagon Class​
​class Hexagon extends Shape {​
​void numberOfSides() {​
​[Link]("Hexagon has 6 sides");​
​}​
​}​
​// Main Class​
​public class AbstractDemo {​
​public static void main(String[] args) {​
​Shape s1 = new Trapezoid();​
​Shape s2 = new Triangle();​
​Shape s3 = new Hexagon();​
​[Link]();​
​[Link]();​
​[Link]();​
​}​
​}​
​Experiment 7​

​ rite a GUI program using Swing and event handlers in Java where:​
W
​• The user enters a temperature in Celsius or Fahrenheit.​
​• The user can click a button to convert it to the other scale.​
​• The result is displayed in the GUI.​
​• Includes input validation (non-numeric input handled with exception).​

​ his program creates a GUI (Graphical User Interface) using Java Swing to convert​
T
​temperature between Celsius and Fahrenheit.​
​Components Used​
​JFrame → Main window​
​JLabel → Text labels​
​JTextField → User input​
​JButton → Trigger conversion​
​JComboBox → Select conversion type​
​JLabel (result) → Display output​
​Event Handling​
​Uses ActionListener​
​When button is clicked:​
​1. Read input​
​2. Convert temperature​
​3. Display result​
​Exception Handling​
​If user enters invalid input (like text),​
​NumberFormatException is handled and error message is shown.​

​ lgorithm​
A
​1. Start​
​2. Create a JFrame window​
​3. Add components:​
​Label → "Enter Temperature"​
​TextField → input​
​ComboBox → select conversion type:​
​Celsius → Fahrenheit​
​Fahrenheit → Celsius​
​Button → "Convert"​
​Label → result display​
​4. Add ActionListener to button:​
​Read input from text field​
​ onvert string → double​
C
​If invalid → catch NumberFormatException​
​Check selected option:​
​If Celsius → Fahrenheit​
​→ F = (C × 9/5) + 32​
​If Fahrenheit → Celsius​
​→ C = (F − 32) × 5/9​
​Display result​
​5. Show window​
​6. End​

​Code​

i​mport [Link].*;​
​import [Link].*;​
​import [Link].*;​
​public class TemperatureConverter extends JFrame implements ActionListener {​
​JTextField inputField;​
​JComboBox<String> options;​
​JLabel resultLabel;​
​JButton convertButton;​
​public TemperatureConverter() {​
​setTitle("Temperature Converter");​
​setSize(400, 200);​
​setLayout(new FlowLayout());​
​setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);​
​// Components​
​add(new JLabel("Enter Temperature:"));​
​inputField = new JTextField(10);​
​add(inputField);​
​String[] choices = {​
​"Celsius to Fahrenheit",​
​"Fahrenheit to Celsius"​
​};​
​options = new JComboBox<>(choices);​
​add(options);​
​convertButton = new JButton("Convert");​
​add(convertButton);​
​resultLabel = new JLabel("Result: ");​
​add(resultLabel);​
/​/ Event Handling​
​[Link](this);​
​setVisible(true);​
​}​
​@Override​
​public void actionPerformed(ActionEvent e) {​
​try {​
​double input = [Link]([Link]());​
​double result;​
​if ([Link]() == 0) {​
​// Celsius to Fahrenheit​
​result = (input * 9 / 5) + 32;​
​[Link]("Result: " + result + " °F");​
​} else {​
​// Fahrenheit to Celsius​

r​ esult = (input - 32) * 5 / 9;​


​[Link]("Result: " + result + " °C");​
​}​
​} catch (NumberFormatException ex) {​
​[Link]("Invalid input! Enter a number.");​
​}​
​}​
​public static void main(String[] args) {​
​new TemperatureConverter();​
​}​
​}​
​Experiment 8​

I​ magine​ ​a​ ​digital​ ​library​ ​management​ ​system​ ​where​ ​a​ ​librarian​ ​interacts​ ​with​ ​a​ ​central​ ​record​ ​book.​ ​In​ ​this​
​scenario,​ ​a​ ​Java​ ​program​ ​acts​ ​as​ ​the​ ​librarian,​ ​using​ ​JDBC​ ​as​ ​the​ ​communication​ ​channel​ ​to​ ​connect​ ​to​ ​the​
​database,​ ​which​ ​represents​ ​the​ ​record​ ​book.​ ​Through​ ​this​ ​connection,​ ​the​ ​program​ ​can​ ​perform​ ​essential​
​operations​​such​​as​​adding​​new​​records,​​removing​​outdated​​entries,​​updating​​existing​​information,​​and​​retrieving​
​stored​ ​data​ ​whenever​ ​required.​ ​This​ ​analogy​ ​highlights​ ​how​ ​JDBC​ ​enables​ ​smooth​​and​​organized​​interaction​
​between a Java application and a database for complete data management.​

I​ n this system:​
​Java Program (Librarian) → Handles user requests​
​JDBC API (Communication Channel) → Connects Java to database​
​Database (Record Book) → Stores library data​
​What JDBC Does​
​JDBC allows a Java program to:​
​Connect to a database​
​Insert records (Add books)​
​Update records (Modify book details)​
​Delete records (Remove books)​
​Retrieve records (View books)​
​Key JDBC Components​
​Connection → Establish connection​
​Statement / PreparedStatement → Execute SQL queries​
​ResultSet → Store retrieved data​

​ lgorithm - Step-by-step:​
A
​1. Start​
​2. Load JDBC driver​
​3. Establish connection to database:​
​URL, username, password​
​4. Create SQL operations:​
​INSERT (Add record)​
​UPDATE (Modify record)​
​DELETE (Remove record)​
​SELECT (Retrieve record)​
​5. Execute queries using PreparedStatement​
​6. If SELECT:​
​Store results in ResultSet​
​Display data​
7​ . Handle exceptions (SQLException)​
​8. Close connection​
​9. End​

​Code​

i​mport [Link].*;​
​public class LibraryJDBC {​
​public static void main(String[] args) {​
​String url = "jdbc:mysql://localhost:3306/library";​
​String user = "root";​
​String password = "root";​
​try {​
​// 1. Establish Connection​
​Connection con = [Link](url, user, password);​
​[Link]("Connected to Database!");​
​// 2. INSERT (Add Book)​
​String insertQuery = "INSERT INTO books (id, title) VALUES (?, ?)";​
​PreparedStatement psInsert = [Link](insertQuery);​
​[Link](1, 101);​
​[Link](2, "Java Programming");​
​[Link]();​
​// 3. UPDATE (Modify Book)​
​String updateQuery = "UPDATE books SET title=? WHERE id=?";​
​PreparedStatement psUpdate = [Link](updateQuery);​
​[Link](1, "Advanced Java");​
​[Link](2, 101);​
​[Link]();​
​// 4. SELECT (Retrieve Books)​
​String selectQuery = "SELECT * FROM books";​
​Statement stmt = [Link]();​
​ResultSet rs = [Link](selectQuery);​
​[Link]("Library Records:");​
​while ([Link]()) {​
​[Link]([Link]("id") + " - " + [Link]("title"));​
​}​
​// 5. DELETE (Remove Book)​
​String deleteQuery = "DELETE FROM books WHERE id=?";​
​ reparedStatement psDelete = [Link](deleteQuery);​
P
​[Link](1, 101);​
​[Link]();​
​// 6. Close Connection​
​[Link]();​
​} catch (SQLException e) {​
​[Link]("Database Error: " + [Link]());​
​}​
​}​
​}​

You might also like