1.
Develop a java application with an employee class with
members for generate pay Slip using inheritance.
AIM:
To develop a Java application with an Employee class and its subclasses to generate a Pay
Slip using the concept of Inheritance.
ALGORITHM:
1. Start the program.
2. Create a base class Employee with data members:
o empId, empName, basicPay
o and a method to get employee details.
3. Create a subclass PaySlip that inherits Employee.
4. Add methods to calculate:
o DA = 0.8 × Basic Pay
o HRA = 0.15 × Basic Pay
o PF = 0.12 × Basic Pay
o Gross Salary = Basic + DA + HRA
o Net Salary = Gross Salary – PF
5. In main(), create an object of PaySlip.
6. Read employee details and generate a formatted pay slip.
7. Display all computed salary details.
8. Stop.
PROGRAM (Java):
import [Link];
// Base Class
class Employee {
int empId;
String empName;
double basicPay;
void getEmployeeDetails() {
Scanner sc = new Scanner([Link]);
[Link]("Enter Employee ID: ");
empId = [Link]();
[Link](); // consume newline
[Link]("Enter Employee Name: ");
empName = [Link]();
[Link]("Enter Basic Pay: ");
basicPay = [Link]();
}
}
// Derived Class
class PaySlip extends Employee {
double da, hra, pf, gross, net;
void calculatePay() {
da = 0.8 * basicPay;
hra = 0.15 * basicPay;
pf = 0.12 * basicPay;
gross = basicPay + da + hra;
net = gross - pf;
}
void generatePaySlip() {
[Link]("\n-----------------------------");
[Link](" PAY SLIP");
[Link]("-----------------------------");
[Link]("Employee ID : " + empId);
[Link]("Employee Name : " + empName);
[Link]("Basic Pay : " + basicPay);
[Link]("DA (80%) : " + da);
[Link]("HRA (15%) : " + hra);
[Link]("PF (12%) : " + pf);
[Link]("-----------------------------");
[Link]("Gross Salary : " + gross);
[Link]("Net Salary : " + net);
[Link]("-----------------------------");
}
}
// Main Class
public class Main {
public static void main(String[] args) {
PaySlip emp = new PaySlip();
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
Enter Employee ID: 101
Enter Employee Name: Meena
Enter Basic Pay: 30000
-----------------------------
PAY SLIP
-----------------------------
Employee ID : 101
Employee Name : Meena
Basic Pay : 30000.0
DA (80%) : 24000.0
HRA (15%) : 4500.0
PF (12%) : 3600.0
-----------------------------
Gross Salary : 58500.0
Net Salary : 54900.0
-----------------------------
RESULT:
The Java program successfully demonstrates Inheritance by creating an Employee class
and a subclass PaySlip to calculate and generate the employee’s salary slip.
2. Write a java program to create abstract class for calculating area of
different shape.
AIM:
To write a Java program that uses an abstract class to calculate the area of different shapes
such as Circle, Rectangle, and Triangle.
ALGORITHM:
1. Start the program.
2. Define an abstract class Shape that contains:
o A method calculateArea() (abstract).
3. Create subclasses:
o Circle
o Rectangle
o Triangle
Each subclass implements calculateArea() according to its shape formula:
o Circle → π × r²
o Rectangle → length × breadth
o Triangle → ½ × base × height
4. In the main() method, use a menu-driven program to select a shape.
5. Create the corresponding shape object and display its area.
6. Stop.
PROGRAM (Java):
import [Link];
// Abstract class
abstract class Shape {
abstract void calculateArea();
}
// Circle subclass
class Circle extends Shape {
double radius;
Circle(double r) {
radius = r;
}
void calculateArea() {
double area = [Link] * radius * radius;
[Link]("Area of Circle = " + area);
}
}
// Rectangle subclass
class Rectangle extends Shape {
double length, breadth;
Rectangle(double l, double b) {
length = l;
breadth = b;
}
void calculateArea() {
double area = length * breadth;
[Link]("Area of Rectangle = " + area);
}
}
// Triangle subclass
class Triangle extends Shape {
double base, height;
Triangle(double b, double h) {
base = b;
height = h;
}
void calculateArea() {
double area = 0.5 * base * height;
[Link]("Area of Triangle = " + area);
}
}
// Main class
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int choice;
[Link]("Choose Shape:");
[Link]("1. Circle");
[Link]("2. Rectangle");
[Link]("3. Triangle");
[Link]("Enter your choice: ");
choice = [Link]();
Shape shape = null;
switch (choice) {
case 1:
[Link]("Enter radius: ");
double r = [Link]();
shape = new Circle(r);
break;
case 2:
[Link]("Enter length and breadth: ");
double l = [Link]();
double b = [Link]();
shape = new Rectangle(l, b);
break;
case 3:
[Link]("Enter base and height: ");
double base = [Link]();
double h = [Link]();
shape = new Triangle(base, h);
break;
default:
[Link]("Invalid choice!");
[Link](0);
}
[Link]();
}
}
OUTPUT:
Choose Shape:
1. Circle
2. Rectangle
3. Triangle
Enter your choice: 1
Enter radius: 5
Area of Circle = 78.53981633974483
Choose Shape:
1. Circle
2. Rectangle
3. Triangle
Enter your choice: 2
Enter length and breadth: 10 5
Area of Rectangle = 50.0
Choose Shape:
1. Circle
2. Rectangle
3. Triangle
Enter your choice: 3
Enter base and height: 8 6
Area of Triangle = 24.0
RESULT:
The Java program successfully demonstrates the use of abstract classes and method overriding
to calculate the area of different shapes — Circle, Rectangle, and Triangle.
3. Write a java program to create interface for calculating area of
different shape.
AIM:
To write a Java program that uses an interface to calculate the area of different shapes such
as Circle, Rectangle, and Triangle.
ALGORITHM:
1. Start the program.
2. Create an interface Shape with a method calculateArea().
3. Create three classes — Circle, Rectangle, and Triangle — that implement the Shape
interface.
4. Each class should have data members for its dimensions (like radius, length, breadth, etc.).
5. Implement calculateArea() in each class using the correct formula:
o Circle → π × r²
o Rectangle → l × b
o Triangle → ½ × base × height
6. In main(), take user input, create the appropriate shape object, and display its area.
7. Stop.
PROGRAM (Java):
import [Link];
// Interface declaration
interface Shape {
void calculateArea();
}
// Circle class implementing Shape
class Circle implements Shape {
double radius;
Circle(double r) {
radius = r;
}
public void calculateArea() {
double area = [Link] * radius * radius;
[Link]("Area of Circle = " + area);
}
}
// Rectangle class implementing Shape
class Rectangle implements Shape {
double length, breadth;
Rectangle(double l, double b) {
length = l;
breadth = b;
}
public void calculateArea() {
double area = length * breadth;
[Link]("Area of Rectangle = " + area);
}
}
// Triangle class implementing Shape
class Triangle implements Shape {
double base, height;
Triangle(double b, double h) {
base = b;
height = h;
}
public void calculateArea() {
double area = 0.5 * base * height;
[Link]("Area of Triangle = " + area);
}
}
// Main class
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Choose Shape:");
[Link]("1. Circle");
[Link]("2. Rectangle");
[Link]("3. Triangle");
[Link]("Enter your choice: ");
int choice = [Link]();
Shape shape = null;
switch (choice) {
case 1:
[Link]("Enter radius: ");
double r = [Link]();
shape = new Circle(r);
break;
case 2:
[Link]("Enter length and breadth: ");
double l = [Link]();
double b = [Link]();
shape = new Rectangle(l, b);
break;
case 3:
[Link]("Enter base and height: ");
double base = [Link]();
double h = [Link]();
shape = new Triangle(base, h);
break;
default:
[Link]("Invalid choice!");
[Link](0);
}
[Link]();
}
}
OUTPUT:
Case 1: Circle
Choose Shape:
1. Circle
2. Rectangle
3. Triangle
Enter your choice: 1
Enter radius: 5
Area of Circle = 78.53981633974483
Case 2: Rectangle
Choose Shape:
1. Circle
2. Rectangle
3. Triangle
Enter your choice: 2
Enter length and breadth: 8 4
Area of Rectangle = 32.0
Case 3: Triangle
Choose Shape:
1. Circle
2. Rectangle
3. Triangle
Enter your choice: 3
Enter base and height: 10 6
Area of Triangle = 30.0
RESULT:
The Java program successfully demonstrates the use of an interface to calculate the area of
different shapes — Circle, Rectangle, and Triangle — showing abstraction and runtime
polymorphism.
4. write a java program for implementing user defined exceptions
handling.
AIM:
To write a Java program that demonstrates user-defined exceptions for handling specific
error conditions.
ALGORITHM:
1. Start the program.
2. Define a user-defined exception class (e.g., InvalidAgeException) extending Exception.
3. In the main class, read user input (e.g., age).
4. If the entered age is less than 18, throw the user-defined exception.
5. Catch the exception and display the custom error message.
6. If no exception occurs, print a success message.
7. Stop the program.
PROGRAM (Java):
import [Link];
// User-defined exception class
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
// Main class
public class Main {
// Method to check voting eligibility
static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is below 18. Not eligible to vote!");
} else {
[Link]("You are eligible to vote.");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link]();
try {
checkAge(age);
} catch (InvalidAgeException e) {
[Link]("Exception Caught: " + [Link]());
}
[Link]("Program continues normally...");
}
}
OUTPUTS:
Case 1: Valid Age
Enter your age: 22
You are eligible to vote.
Program continues normally...
Case 2: Invalid Age
Enter your age: 15
Exception Caught: Age is below 18. Not eligible to vote!
Program continues normally...
RESULT:
The Java program successfully demonstrates user-defined exception handling by creating
and throwing a custom exception (InvalidAgeException) and handling it using try-catch.
5. write a java program for implementing multi-threaded application.
AIM:
To write a Java program that demonstrates the concept of multithreading by creating and
running multiple threads concurrently.
ALGORITHM:
1. Start the program.
2. Create two classes that extend the Thread class or implement Runnable.
3. Override the run() method in each class to define its specific task.
4. In the main() method, create objects of each thread class.
5. Call the start() method to execute the threads concurrently.
6. Observe the interleaved execution of threads.
7. Stop the program.
PROGRAM (Java):
// Example of Multi-threaded Application
// Thread 1 – prints numbers
class NumberThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Number Thread: " + i);
try {
[Link](500); // pause for 0.5 sec
} catch (InterruptedException e) {
[Link](e);
}
}
}
}
// Thread 2 – prints alphabets
class AlphabetThread extends Thread {
public void run() {
for (char ch = 'A'; ch <= 'E'; ch++) {
[Link]("Alphabet Thread: " + ch);
try {
[Link](700); // pause for 0.7 sec
} catch (InterruptedException e) {
[Link](e);
}
}
}
}
// Main class
public class Main {
public static void main(String[] args) {
NumberThread t1 = new NumberThread();
AlphabetThread t2 = new AlphabetThread();
[Link]("Starting Threads...");
[Link]();
[Link]();
// Wait for both threads to finish
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Main Thread Finished Execution.");
}
}
SAMPLE OUTPUT:
Starting Threads...
Number Thread: 1
Alphabet Thread: A
Number Thread: 2
Alphabet Thread: B
Number Thread: 3
Alphabet Thread: C
Number Thread: 4
Alphabet Thread: D
Number Thread: 5
Alphabet Thread: E
Main Thread Finished Execution.
(Note: The output order may vary slightly depending on thread scheduling.)
RESULT:
The Java program successfully demonstrates multithreading, where multiple threads
(NumberThread and AlphabetThread) execute concurrently, showing parallelism in execution.
6. write a java program that reads a file name from the user, displays
information about whether the file exists, whether the file is
readable, or writable, the type of file and the length of the file in
bytes.
AIM:
To write a Java program that reads a file name from the user and displays:
• Whether the file exists
• Whether the file is readable
• Whether the file is writable
• The type of the file (directory or regular file)
• The length of the file in bytes
ALGORITHM:
1. Start the program.
2. Import the [Link].* package.
3. Read a file name from the user using Scanner.
4. Create a File object for the given file name.
5. Check if the file exists using exists().
6. If it exists, display the following:
o File name
o Readable or not (canRead())
o Writable or not (canWrite())
o Type of file (isFile() / isDirectory())
o File size in bytes (length())
7. If the file doesn’t exist, display an appropriate message.
8. Stop the program.
PROGRAM (Java):
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the file name (with path if needed): ");
String fileName = [Link]();
File file = new File(fileName);
if ([Link]()) {
[Link]("\nFile Information:");
[Link]("-------------------------");
[Link]("File Name : " + [Link]());
[Link]("Absolute Path : " + [Link]());
[Link]("Readable : " + [Link]());
[Link]("Writable : " + [Link]());
[Link]("Is Directory : " + [Link]());
[Link]("Is File : " + [Link]());
[Link]("File Size : " + [Link]() + " bytes");
} else {
[Link]("File does not exist!");
}
[Link]();
}
}
OUTPUT 1:
(For an existing text file)
Enter the file name (with path if needed): [Link]
File Information:
-------------------------
File Name : [Link]
Absolute Path : C:\Users\Meena\[Link]
Readable : true
Writable : true
Is Directory : false
Is File : true
File Size : 124 bytes
OUTPUT 2:
(For a non-existing file)
Enter the file name (with path if needed): [Link]
File does not exist!
RESULT:
The Java program successfully reads a file name from the user and displays detailed
information about the file — including whether it exists, its permissions, type, and size in bytes.
7. Write a Java Program to create an abstract class named sum of
Two and sum of Three. Perform addition of two numbers and
addition of three numbers
AIM:
To write a Java program that creates an abstract class named Sum with abstract methods to
perform the addition of two and three numbers using inheritance.
ALGORITHM:
1. Start the program.
2. Define an abstract class Sum containing two abstract methods:
o sum(int a, int b)
o sum(int a, int b, int c)
3. Create a subclass Addition that extends Sum.
4. Implement both abstract methods in the subclass.
5. In the main() method:
o Create an object of the subclass.
o Call both methods to perform addition of two and three numbers.
6. Display the results.
7. Stop the program.
PROGRAM (Java):
import [Link];
// Abstract class
abstract class Sum {
abstract void sum(int a, int b);
abstract void sum(int a, int b, int c);
}
// Subclass implementing abstract methods
class Addition extends Sum {
void sum(int a, int b) {
int result = a + b;
[Link]("Sum of two numbers: " + result);
}
void sum(int a, int b, int c) {
int result = a + b + c;
[Link]("Sum of three numbers: " + result);
}
}
// Main class
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Addition add = new Addition();
[Link]("Enter two numbers: ");
int x = [Link]();
int y = [Link]();
[Link](x, y);
[Link]("\nEnter three numbers: ");
int p = [Link]();
int q = [Link]();
int r = [Link]();
[Link](p, q, r);
[Link]();
}
}
OUTPUT:
Enter two numbers: 10 20
Sum of two numbers: 30
Enter three numbers: 5 15 25
Sum of three numbers: 45
RESULT:
The Java program successfully demonstrates the concept of abstract classes by performing:
• Addition of two numbers, and
• Addition of three numbers
using method overriding in a subclass.
8. Write a program to Check Prime Number using Interface.
AIM:
To write a Java program that uses an interface to check whether a given number is prime or not.
ALGORITHM:
1. Start the program.
2. Create an interface named PrimeCheck with an abstract method isPrime(int n).
3. Create a class Prime that implements the interface.
4. Define the logic inside isPrime():
o A number is prime if it is greater than 1 and divisible only by 1 and itself.
5. In the main() method:
o Read a number from the user.
o Call the isPrime() method and display whether it is prime or not.
6. Stop the program.
PROGRAM (Java):
import [Link];
// Interface declaration
interface PrimeCheck {
boolean isPrime(int n);
}
// Class implementing the interface
class Prime implements PrimeCheck {
public boolean isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0)
return false;
}
return true;
}
}
// Main class
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Prime p = new Prime();
[Link]("Enter a number: ");
int num = [Link]();
if ([Link](num))
[Link](num + " is a Prime Number.");
else
[Link](num + " is Not a Prime Number.");
[Link]();
}
}
OUTPUT:
Case 1:
Enter a number: 13
13 is a Prime Number.
Case 2:
Enter a number: 20
20 is Not a Prime Number.
RESULT:
The Java program successfully demonstrates the use of an interface to implement a method
for checking whether a given number is prime or not.
9. Write Java programs to implementing Arithmetic exception and
implementing Array Index Out Of Bound exception.
AIM:
To write two Java programs demonstrating:
1. Handling of ArithmeticException (example: division by zero).
2. Handling of ArrayIndexOutOfBoundsException (accessing invalid array index).
ALGORITHM (Common Steps):
1. Start the program.
2. Use a try block to perform operations that might cause exceptions.
3. Use a catch block to handle specific exceptions (like ArithmeticException or
ArrayIndexOutOfBoundsException).
4. Display appropriate error messages.
5. Continue program execution normally after handling the exception.
6. Stop the program.
PROGRAM 1: Handling Arithmetic Exception
import [Link];
public class ArithmeticExceptionExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();
int result = a / b;
[Link]("Result = " + result);
}
catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed!");
}
[Link]("Program continues after handling ArithmeticException.");
[Link]();
}
}
Output 1:
Enter first number: 10
Enter second number: 0
Error: Division by zero is not allowed!
Program continues after handling ArithmeticException.
PROGRAM 2: Handling Array Index Out of Bound Exception
import [Link];
public class ArrayIndexOutOfBoundExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] arr = {10, 20, 30, 40, 50};
try {
[Link]("Enter array index to access (0–4): ");
int index = [Link]();
[Link]("Element at index " + index + " = " + arr[index]);
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Invalid array index accessed!");
}
[Link]("Program continues after handling ArrayIndexOutOfBoundsException.");
[Link]();
}
}
Output 2:
Enter array index to access (0–4): 7
Error: Invalid array index accessed!
Program continues after handling ArrayIndexOutOfBoundsException.
RESULT:
Both programs successfully demonstrate the use of exception handling in Java:
• ArithmeticException for handling division by zero.
• ArrayIndexOutOfBoundsException for handling invalid array index access.
This ensures the program continues execution even after runtime errors occur.
10. Write a Java program that keeps a number from the user and
generates an integer between 1 and 12 and displays the name of the
month.
AIM:
To write a Java program that takes a number from the user and generates a random integer
between 1 and 12, then displays the name of the corresponding month.
ALGORITHM:
1. Start the program.
2. Import [Link] and [Link].
3. Prompt the user to enter any number (to initiate the process).
4. Use the Random class to generate a random number between 1 and 12.
5. Use a switch statement to map the number to its corresponding month name.
6. Display the generated month name.
7. Stop the program.
PROGRAM (Java):
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Random rand = new Random();
[Link]("Enter any number to generate a random month: ");
int userInput = [Link]();
int monthNumber = [Link](12) + 1; // Generates 1 to 12
[Link]("\nGenerated Number: " + monthNumber);
String monthName = "";
switch (monthNumber) {
case 1: monthName = "January"; break;
case 2: monthName = "February"; break;
case 3: monthName = "March"; break;
case 4: monthName = "April"; break;
case 5: monthName = "May"; break;
case 6: monthName = "June"; break;
case 7: monthName = "July"; break;
case 8: monthName = "August"; break;
case 9: monthName = "September"; break;
case 10: monthName = "October"; break;
case 11: monthName = "November"; break;
case 12: monthName = "December"; break;
default: monthName = "Invalid"; break;
}
[Link]("Month Name: " + monthName);
[Link]();
}
}
OUTPUT:
Case 1:
Enter any number to generate a random month: 5
Generated Number: 8
Month Name: August
Case 2:
Enter any number to generate a random month: 22
Generated Number: 12
Month Name: December
RESULT:
The Java program successfully generates a random number between 1 and 12 and displays the
corresponding month name, demonstrating the use of random number generation and switch-
case in Java.