Oops Using Java
Oops Using Java
(Autonomous)
RAMAPURAM, CHENNAI-89
LAB MANUAL
REGULATIONS R23
LABORATORY
ACADEMIC YEAR:2024-2025
Prepared By Approved By
HOD/IT
LT PRC 0 0 4 02
COURSE OBJECTIVES
1. To build software development skills using java programming for real-world applications.
2. To apply the concepts of classes, packages, interfaces, array list, exception handling and file
processing.
3. To develop applications using event handling.
4. To apply the concept of multithreading.
LIST OF EXPERIMENTS
1. Develop a Java application to generate Electricity bill. Create a class with the following
members:
Consumer no., consumer name, previous month reading, current month reading, type of
EB connection (i.e. domestic or commercial). Compute the bill amount using the following
tariff.
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
First100units - Rs. 1 per unit
101-200units - Rs. 2.50 per unit
201 -500 units - Rs. 4 per unit
501units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as
follows:
First 100 units - Rs. 2 per unit
101-200 units - Rs. 4.50 per unit
201 -500 units - Rs. 6 per unit
501 units - Rs. 7 per unit
4. Write a Java Program to create an abstract class named Shape that contains two integers and
an empty method named printArea(). Provide three classes named Rectangle, Triangle and
Circle such that each one of the classes extends the class Shape. Each one of the classes
contains only the method printArea( ) that prints the area of the given shape.
7. Write a java program that implements a multi-threaded application that has three threads. First
thread generates a random integer every 1 second and if the value is even, the second thread
computes the square of the number and prints. If the value is odd, the third thread will print the
value of the cube of the number.
8. Write a Java program to perform write and read operations in file handling.
10. Develop a Mini Project for any application using Java Concepts
TOTAL:60 PERIODS
2 Packages
4 Abstract Class
5 Interface
6 Exception handling
7 Multi-threaded application
8 File handling
10 Mini Project
11 Generic Function
16 Generics classes
JAVA PROGRAMMING
Java is a widely-used, high-level programming language known for its versatility, portability, and
performance. Developed by Sun Microsystems in the mid-1990s and now maintained by Oracle
Corporation, Java has become one of the most popular programming languages in the world. Its design
is driven by the philosophy of "write once, run anywhere," meaning that Java applications can run on
any device equipped with a Java Virtual Machine (JVM), regardless of the underlying hardware and
operating system.
Java Development Kit (JDK): Download and install the latest version of the JDK from Oracle’s
official website. The JDK includes the necessary tools to compile and run Java programs.
Integrated Development Environment (IDE): Use an IDE such as IntelliJ IDEA, Eclipse, or NetBeans
to write, compile, and debug your Java code. These tools provide features like syntax highlighting, code
completion, and integrated debugging to enhance your productivity.
Text Editor: While an IDE is recommended, you can also use a simple text editor like Notepad++ or
Sublime Text to write Java code and compile it using the command line.
Ex NO: 1 ELECTRICITY BILL CALCULATION
DATE :
Aim
To develop a Java application to generate an electricity bill for consumers based on their type of
EB connection.
Algorithm
Step 1: Start
Step 4: Implement main() Method, Call calculateBill() method to compute and display the bill details.
Step 5: Stop
Program
import java.util.Scanner;
class ElectricityBill {
int consumerNo;
String consumerName;
int previousMonthReading;
int currentMonthReading;
String ebConnectionType;
void calculateBill() {
int unitsConsumed = currentMonthReading - previousMonthReading;
double billAmount = 0;
if (ebConnectionType.equalsIgnoreCase("domestic")) {
if (unitsConsumed <= 100) {
billAmount = unitsConsumed * 1;
} else if (unitsConsumed <= 200) {
billAmount = 100 * 1 + (unitsConsumed - 100) * 2.50;
} else if (unitsConsumed <= 500) {
billAmount = 100 * 1 + 100 * 2.50 + (unitsConsumed - 200) * 4;
} else {
billAmount = 100 * 1 + 100 * 2.50 + 300 * 4 + (unitsConsumed - 500) * 6;
}
} else if (ebConnectionType.equalsIgnoreCase("commercial")) {
if (unitsConsumed <= 100) {
billAmount = unitsConsumed * 2;
} else if (unitsConsumed <= 200) {
billAmount = 100 * 2 + (unitsConsumed - 100) * 4.50;
} else if (unitsConsumed <= 500) {
billAmount = 100 * 2 + 100 * 4.50 + (unitsConsumed - 200) * 6;
} else {
billAmount = 100 * 2 + 100 * 4.50 + 300 * 6 + (unitsConsumed - 500) * 7;
}
}
bill.calculateBill();
}
}
Output
Result
Thus the Java application to calculate and display the electricity bill for a consumer based on the type of
EB connection and the number of units consumed was executed and verified.
Ex NO: 2
PACKAGES
DATE :
Aim
To develop a Java application that demonstrates the use of packages for organizing classes and
interfaces.
Algorithm
Step 1: Start
Step 2: Create a package named bank:
Inside the package, create a class named BankAccount with methods for deposit, withdrawal,
and balance inquiry.
Step 3: Create a main class outside the package:
Import the bank.BankAccount class.
Instantiate BankAccount and perform various operations (deposit, withdrawal, and balance
inquiry).
Step 4: Compile the package and the main class:
Use the javac command to compile the Java files.
Step 5: Run the main class:
Use the java command to execute the main class.
Step 6: Stop
Program
File: bank/BankAccount.java
package bank;
File: BankApplication.java
import bank.BankAccount;
account1.displayBalance();
account1.deposit(1500.0);
account1.displayBalance();
account1.withdraw(2000.0);
account1.displayBalance();
account1.withdraw(5000.0);
account1.displayBalance();
}
}
Output
Result
Thus the ‘Java’ program to implement packages is executed and the output is verified successfully.
Ex NO: 3
EMPLOYEE PAYSLIP
DATE :
Aim
Algorithm
Step 1: Start
Step 2: Define Employee Class:
Declare Emp_name, Emp_id, Address, Mail_id, Mobile_no as member variables.
Implement a constructor to initialize these variables.
Implement displayDetails() method to print employee details.
Step 3: Define Subclasses (Programmer, AssistantProfessor, AssociateProfessor, Professor):
Inherit from Employee.
Add BP (Basic Pay) as a private member variable.
Implement constructor to initialize inherited members and BP.
Implement grossSalary() method:
Calculate DA (Dearness Allowance) as 97% of BP.
Calculate HRA (House Rent Allowance) as 10% of BP.
Calculate PF (Provident Fund) as 12% of BP.
Calculate staff club fund as 0.1% of BP.
Compute gross salary as BP + DA + HRA - PF - staffClubFund.
Step 4: Implement displayPaySlip() method to:
Call displayDetails() from superclass.
Print BP, gross salary calculated from grossSalary() method.
Step 5: Create Main Class (EmployeePaySlip):
Instantiate objects of each subclass (Programmer, AssistantProfessor, AssociateProfessor,
Professor).
Call displayPaySlip() for each object to print pay slip details.
Step 6: Stop
Program
import java.util.Scanner;
// Employee class
class Employee {
// Member variables
protected String Emp_name;
protected int Emp_id;
protected String Address;
protected String Mail_id;
protected String Mobile_no;
// Constructor
public Employee(String emp_name, int emp_id, String address, String mail_id, String mobile_no) {
this.Emp_name = emp_name;
this.Emp_id = emp_id;
this.Address = address;
this.Mail_id = mail_id;
this.Mobile_no = mobile_no;
}
// Constructor
public Programmer(String emp_name, int emp_id, String address, String mail_id, String mobile_no,
double bp) {
super(emp_name, emp_id, address, mail_id, mobile_no);
this.BP = bp;
}
// Constructor
public AssistantProfessor(String emp_name, int emp_id, String address, String mail_id, String
mobile_no, double bp) {
super(emp_name, emp_id, address, mail_id, mobile_no);
this.BP = bp;
}
// Constructor
public AssociateProfessor(String emp_name, int emp_id, String address, String mail_id, String
mobile_no, double bp) {
super(emp_name, emp_id, address, mail_id, mobile_no);
this.BP = bp;
}
// Constructor
public Professor(String emp_name, int emp_id, String address, String mail_id, String mobile_no,
double bp) {
super(emp_name, emp_id, address, mail_id, mobile_no);
this.BP = bp;
}
// Create a Professor
Professor professor = new Professor("Emily Brown", 4001, "101 Pine St", "emily@example.com",
"9998887777", 80000.0);
System.out.println("\nProfessor Pay Slip:");
professor.displayPaySlip();
Output
Result
Thus, the ‘Java‘ program to generate the pay slip has been executed and the output is verified
successfully.
Ex NO: 4
ABSTRACT CLASS
DATE :
Aim
To write a program to implement the abstract class in java.
Algorithm
Step 1: Start
Step 2: Define Abstract Class Shape
Declare two integers dim1 and dim2.
Declare abstract method printArea().
Step 3: Define Subclass Rectangle extending Shape
Override printArea():
Calculate area using length (stored in dim1) and breadth (stored in dim2).
Print the area of the rectangle.
Step 4: Define Subclass Triangle extending Shape:
Override printArea():
Calculate area using base (stored in dim1) and height (stored in dim2).
Print the area of the triangle.
Step 5: Define Subclass Circle extending Shape:
Override printArea():
Calculate area using radius (stored in dim1).
Print the area of the circle.
Step 6: Main Class (ShapeMain):
Instantiate objects of Rectangle, Triangle, and Circle.
Call printArea() for each object to display its area.
Step 7: Stop
Program
// Abstract method
public abstract void printArea();
}
// Print areas
rectangle.printArea();
triangle.printArea();
circle.printArea();
}
}
Output
Result
Thus, the ‘Java’ program to implement abstract class has been executed and the output is verified
successfully.
Ex NO: 5
DATE : INTERFACE
Aim:
To write a ‘Java’ program to implement interface.
Algorithm
Step 1: Start
Step 2: Define Interface Shape
Declare two integers dim1 and dim2.
Declare abstract method printArea().
Step 3: Implement Class Rectangle implementing Shape
Declare two private integers dim1 and dim2.
Implement a constructor to initialize dim1 (length) and dim2 (breadth).
Override printArea() method to calculate area (dim1 * dim2) and print it.
Step 4: Implement Class Triangle implementing Shape
Declare two private integers dim1 (base) and dim2 (height).
Implement a constructor to initialize dim1 and dim2.
Override printArea() method to calculate area (0.5 * dim1 * dim2) and print it.
Step 5: Implement Class Circle implementing Shape
Declare one private integer dim1 (radius).
Implement a constructor to initialize dim1.
Override printArea() method to calculate area (Math.PI * dim1 * dim1) and print it.
Step 6: Main Class ShapeMain to test the implementation
Instantiate objects of Rectangle, Triangle, and Circle.
Call printArea() method for each object to display its area.
Step 7: Stop
Program
interface Shape {
void printArea();
}
@Override
public void printArea() {
int area = dim1 * dim2;
System.out.println("Area of Rectangle: " + area);
}
}
@Override
public void printArea() {
double area = 0.5 * dim1 * dim2;
System.out.println("Area of Triangle: " + area);
}
}
@Override
public void printArea() {
double area = Math.PI * dim1 * dim1;
System.out.println("Area of Circle: " + area);
}
}
rectangle.printArea();
triangle.printArea();
circle.printArea();
}
}
Output
Result
Thus, the Java program to implement the interface has been executed and the output is verified
successfully.
Ex NO: 6
EXCEPTION HANDLING
DATE :
Aim
To write a ‘Java ‘program to implement exception handling and to create user-defined interface.
Algorithm
Step 1: Start
Step 2: Define Interface Shape
Declare method printArea() without specifying exceptions.
Step 3: Implement Class Rectangle implementing Shape
Implement a constructor that throws a user-defined InvalidDimensionException if non-positive
dimensions are provided.
Override printArea() to handle exceptions and calculate/print the area of the rectangle.
Step 4: Implement Class Triangle implementing Shape
Implement a constructor that throws InvalidDimensionException.
Override printArea() to handle exceptions and calculate/print the area of the triangle.
Step 5: Implement Class Circle implementing Shape
Implement a constructor that throws InvalidDimensionException.
Override printArea() to handle exceptions and calculate/print the area of the circle.
Step 6: Define InvalidDimensionException (User-Defined Exception)
Extend Exception class.
Provide constructors to initialize exception messages.
Step 7: Main Class ShapeMain to test the implementation
Instantiate objects of Rectangle, Triangle, and Circle.
Handle exceptions and display appropriate messages for invalid dimensions.
Step 8: Stop
Program
interface Shape {
void printArea();
}
@Override
public void printArea() {
try {
int area = dim1 * dim2;
System.out.println("Area of Rectangle: " + area);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
@Override
public void printArea() {
try {
double area = 0.5 * dim1 * dim2;
System.out.println("Area of Triangle: " + area);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
@Override
public void printArea() {
try {
double area = Math.PI * dim1 * dim1;
System.out.println("Area of Circle: " + area);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
rectangle.printArea();
triangle.printArea();
circle.printArea();
Output
Result
Thus the ‘Java’ program to implement the exception handling and it has been executed and the output is
verified successfully.
Ex NO: 7
DATE : MULTITHREADING
Aim
To write a Java program for multithreading.
Algorithm
Step 1: Start
Step 2: Define a class RandomNumberGenerator implementing Runnable
Generate random integers every second.
Use Thread.sleep(1000) for the delay.
If the number is even, call computeSquare() method of SquareThread.
If the number is odd, call computeCube() method of CubeThread.
Step 3: Define SquareThread class extending Thread
Implement computeSquare() method to compute square of a number and print.
Step 4: Define CubeThread class extending Thread
Implement computeCube() method to compute cube of a number and print.
Step 5: Main class MultiThreadedApp to create and start threads
Instantiate RandomNumberGenerator, SquareThread, and CubeThread.
Start threads to execute their respective tasks.
Step 6: Stop
Program
import java.util.Random;
class RandomNumberGenerator implements Runnable {
private final Random random = new Random();
@Override
public void run() {
try {
while (true) {
int number = random.nextInt(100); // Generate random integer between 0 and 99
System.out.println("Generated number: " + number);
if (number % 2 == 0) {
SquareThread squareThread = new SquareThread(number);
squareThread.start();
} else {
CubeThread cubeThread = new CubeThread(number);
cubeThread.start();
}
Thread.sleep(1000); // Delay for 1 second
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
class SquareThread extends Thread {
private int number;
Result
Thus the ‘Java’ program for multi-threading has been executed and the output is verified successfully.
Ex NO: 8
FILE HANDLING
DATE :
Aim
Algorithm
Step 1: Start
Step 2: Import necessary Java I/O classes (File, FileWriter, BufferedWriter, FileReader,
BufferedReader, IOException).
Step 3: Define a class FileHandler to handle file operations.
Create a method writeToFile(String fileName, String content) to write content to a file.
Create a method readFromFile(String fileName) to read content from a file.
Step 4: Main class FileHandlingDemo to demonstrate file handling operations.
Instantiate FileHandler.
Call writeToFile() and readFromFile() methods to perform write and read operations.
Step 5: Stop
Program
import java.io.*;
class FileHandler {
// Method to write content to a file
public void writeToFile(String fileName, String content) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(content);
System.out.println("Content successfully written to " + fileName);
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
fileHandler.writeToFile(fileName, content);
fileHandler.readFromFile(fileName);
}
}
// Step 5: Stop
Output
Result
Thus the ‘Java’ program to implement file handling has been executed and the output is verified
successfully.
Ex NO: 9
Aim
Algorithm
Program
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.stage.Window;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Registration Form JavaFX Application");
primaryStage.show();
}
// Position the pane at the center of the screen, both vertically and horizontally
gridPane.setAlignment(Pos.CENTER);
gridPane.getColumnConstraints().addAll(columnOneConstraints, columnTwoConstrains);
return gridPane;
}
submitButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if(nameField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Form Error!",
"Please enter your name");
return;
}
if(emailField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Form Error!",
"Please enter your email id");
return;
}
if(passwordField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Form Error!",
"Please enter a password");
return;
}
showAlert(Alert.AlertType.CONFIRMATION, gridPane.getScene().getWindow(),
"Registration Successful!", "Welcome " + nameField.getText());
}
});
}
private void showAlert(Alert.AlertType alertType, Window owner, String title, String message) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.initOwner(owner);
alert.show();
}
Output
Result
Thus, the ‘Java’ program to implement JavaFX has been executed and the output is verified
successfully.
Ex NO: 10
Aim
Algorithm
Step 1: Start
Define TextField for entering the first number (num1Field) and prompt text.
Define TextField for entering the second number (num2Field) and prompt text.
Create a Label (resultLabel) to display the calculation result initialized with "Result: ".
Create an abstract class Operation with an abstract method operate(double num1, double num2).
Define concrete subclasses (Addition, Subtraction, Multiplication, Division) that extend
Operation and implement the operate method to perform specific arithmetic operations.
Step 5: Set up Buttons for Operations
Implement isValidNumber(String text) to verify if the input string matches the numeric format
using regular expressions.
Update resultLabel with the computed result or error message based on the operation performed.
Step 9: Stop
Program
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
abstract class Operation {
abstract double operate(double num1, double num2);
}
Output
Result
Aim
Algorithm
Step 1: Start
Step 9: Stop
Program
import java.util.Arrays;
// Output results
System.out.println("Maximum Integer: " + maxInt);
System.out.println("Maximum Double: " + maxDouble);
System.out.println("Maximum String: " + maxString);
}
}
Output
Result
Thus, the ‘Java ’program to implement generic function has been executed and the output is verified
successfully.
Ex NO: 12
CONTENT BEYOND SYLLABUS
DATE :
GENERICS CLASSES
Aim
Algorithm
Step 1: Start
Step 6: Stop
Program
// Step 1: Start
Output:
Result
Thus the ‘Java’ program to implement the generic classes has been executed and the output is verified
successfully.