KEMBAR78
Oops Using Java | PDF | Java (Programming Language) | Java (Software Platform)
0% found this document useful (0 votes)
29 views49 pages

Oops Using Java

The document is a lab manual for the Object Oriented Programming using Java course at Easwari Engineering College for the academic year 2024-2025. It outlines course objectives, a list of experiments, and expected student outcomes, as well as detailed instructions for various programming tasks including electricity bill calculation, package implementation, employee pay slip generation, and multi-threaded applications. Additionally, it provides information on Java programming, the Java Development Kit, and Integrated Development Environments.

Uploaded by

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

Oops Using Java

The document is a lab manual for the Object Oriented Programming using Java course at Easwari Engineering College for the academic year 2024-2025. It outlines course objectives, a list of experiments, and expected student outcomes, as well as detailed instructions for various programming tasks including electricity bill calculation, package implementation, employee pay slip generation, and multi-threaded applications. Additionally, it provides information on Java programming, the Java Development Kit, and Integrated Development Environments.

Uploaded by

jayapriya060226
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 49

EASWARI ENGINEERING COLLEGE

(Autonomous)

RAMAPURAM, CHENNAI-89

DEPARTMENT OF INFORMATION AND TECHNOLOGY

LAB MANUAL

REGULATIONS R23

231ITC312L - OBJECT ORIENTED PROGRAMMING USING JAVA

LABORATORY

ACADEMIC YEAR:2024-2025

II YEAR IT/ III SEMESTER

Prepared By Approved By
HOD/IT

231ITC312L - OBJECT ORIENTED PROGRAMMING USING JAVA

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

2. Write a java program to implement the concept of packages.


3. Develop a java application with an Employee class with Emp_name, Emp_id, Address, Mail_id,
Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate Professor
and Professor from employee class. Add Basic Pay (BP) as the member of all the inherited classes
with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club funds.
Generate pay slips for the employees with their gross and net salary.

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.

5. Solve the above problem using an interface.

6. Implement exception handling and creation of user-defined exceptions

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.

9. Develop applications using JavaFX controls, layouts and menus

10. Develop a Mini Project for any application using Java Concepts

TOTAL:60 PERIODS

Course Name: 231ITC312L - OBJECT ORIENTED PROGRAMMING USING JAVA


Year / Sem: 2024-2025/ III
Students will be able to :
CO1 Design and develop java programs using object oriented programming
concepts
CO.2 Develop simple applications using object oriented concepts such as package,
exceptions
CO3 Develop applications using event handling.
CO4 Create GUIs and event driven programming applications for real world
problems
CO5 Implement and deploy web applications using Java
TABLE OF CONTENTS

Ex.No. Date Title of the Experiment Page No. Signature

1 Electricity bill Calculation

2 Packages

3 Employee Pay Slips

4 Abstract Class

5 Interface

6 Exception handling

7 Multi-threaded application

8 File handling

9 JavaFX controls, menus and layouts

10 Mini Project

CONTENT BEYOND SYLLABUS

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 2: Define the ElectricityBill Class

Step 3: Define calculateBill() Method

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;
}
}

System.out.println("Consumer No: " + consumerNo);


System.out.println("Consumer Name: " + consumerName);
System.out.println("EB Connection Type: " + ebConnectionType);
System.out.println("Units Consumed: " + unitsConsumed);
System.out.println("Bill Amount: Rs. " + billAmount);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

ElectricityBill bill = new ElectricityBill();

System.out.print("Enter Consumer No: ");


bill.consumerNo = sc.nextInt();

System.out.print("Enter Consumer Name: ");


bill.consumerName = sc.next();

System.out.print("Enter Previous Month Reading: ");


bill.previousMonthReading = sc.nextInt();

System.out.print("Enter Current Month Reading: ");


bill.currentMonthReading = sc.nextInt();

System.out.print("Enter EB Connection Type (domestic/commercial): ");


bill.ebConnectionType = sc.next();

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;

public class BankAccount {


private String accountNumber;
private String accountHolderName;
private double balance;

public BankAccount(String accountNumber, String accountHolderName, double initialBalance) {


this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = initialBalance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposited: Rs. " + amount);
} else {
System.out.println("Invalid deposit amount");
}
}

public void withdraw(double amount) {


if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: Rs. " + amount);
} else {
System.out.println("Invalid or insufficient funds for withdrawal");
}
}

public void displayBalance() {


System.out.println("Account Holder: " + accountHolderName);
System.out.println("Account Number: " + accountNumber);
System.out.println("Current Balance: Rs. " + balance);
}
}

File: BankApplication.java
import bank.BankAccount;

public class BankApplication {


public static void main(String[] args) {
BankAccount account1 = new BankAccount("1234567890", "John Doe", 5000.0);

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

To Develop a java application to generate pay slips for the employees.

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;
}

// Display employee details


public void displayDetails() {
System.out.println("Employee Name: " + Emp_name);
System.out.println("Employee ID: " + Emp_id);
System.out.println("Address: " + Address);
System.out.println("Mail ID: " + Mail_id);
System.out.println("Mobile No.: " + Mobile_no);
}
}

// Programmer class inherits from Employee


class Programmer extends Employee {
// Member variables
private double BP; // Basic Pay

// 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;
}

// Calculate gross salary


public double grossSalary() {
double DA = 0.97 * BP;
double HRA = 0.1 * BP;
double PF = 0.12 * BP;
double staffClubFund = 0.001 * BP;
return BP + DA + HRA - PF - staffClubFund;
}

// Display pay slip


public void displayPaySlip() {
displayDetails();
System.out.println("Basic Pay: " + BP);
System.out.println("Gross Salary: " + grossSalary());
}
}

// AssistantProfessor class inherits from Employee


class AssistantProfessor extends Employee {
// Member variables
private double BP; // Basic Pay

// 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;
}

// Calculate gross salary


public double grossSalary() {
double DA = 0.97 * BP;
double HRA = 0.1 * BP;
double PF = 0.12 * BP;
double staffClubFund = 0.001 * BP;
return BP + DA + HRA - PF - staffClubFund;
}

// Display pay slip


public void displayPaySlip() {
displayDetails();
System.out.println("Basic Pay: " + BP);
System.out.println("Gross Salary: " + grossSalary());
}
}

// AssociateProfessor class inherits from Employee


class AssociateProfessor extends Employee {
// Member variables
private double BP; // Basic Pay

// 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;
}

// Calculate gross salary


public double grossSalary() {
double DA = 0.97 * BP;
double HRA = 0.1 * BP;
double PF = 0.12 * BP;
double staffClubFund = 0.001 * BP;
return BP + DA + HRA - PF - staffClubFund;
}
// Display pay slip
public void displayPaySlip() {
displayDetails();
System.out.println("Basic Pay: " + BP);
System.out.println("Gross Salary: " + grossSalary());
}
}

// Professor class inherits from Employee


class Professor extends Employee {
// Member variables
private double BP; // Basic Pay

// 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;
}

// Calculate gross salary


public double grossSalary() {
double DA = 0.97 * BP;
double HRA = 0.1 * BP;
double PF = 0.12 * BP;
double staffClubFund = 0.001 * BP;
return BP + DA + HRA - PF - staffClubFund;
}

// Display pay slip


public void displayPaySlip() {
displayDetails();
System.out.println("Basic Pay: " + BP);
System.out.println("Gross Salary: " + grossSalary());
}
}

// Main class to test the implementation


public class EmployeePaySlip {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Create a Programmer
Programmer programmer = new Programmer("John Doe", 1001, "123 Main St",
"john@example.com", "1234567890", 50000.0);
System.out.println("\nProgrammer Pay Slip:");
programmer.displayPaySlip();

// Create an Assistant Professor


AssistantProfessor assistantProfessor = new AssistantProfessor("Jane Smith", 2001, "456 Elm St",
"jane@example.com", "9876543210", 60000.0);
System.out.println("\nAssistant Professor Pay Slip:");
assistantProfessor.displayPaySlip();

// Create an Associate Professor


AssociateProfessor associateProfessor = new AssociateProfessor("David Johnson", 3001, "789 Oak
St", "david@example.com", "5551234567", 70000.0);
System.out.println("\nAssociate Professor Pay Slip:");
associateProfessor.displayPaySlip();

// 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();

// Close the scanner


sc.close();
}
}

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 class Shape

abstract class Shape {


// Two integers
protected int dim1;
protected int dim2;

// Abstract method
public abstract void printArea();
}

// Rectangle class extending Shape


class Rectangle extends Shape {
// Constructor
public Rectangle(int length, int breadth) {
this.dim1 = length;
this.dim2 = breadth;
}
// Implementing abstract method
@Override
public void printArea() {
int area = dim1 * dim2;
System.out.println("Area of Rectangle: " + area);
}
}
// Triangle class extending Shape
class Triangle extends Shape {
// Constructor
public Triangle(int base, int height) {
this.dim1 = base;
this.dim2 = height;
}

// Implementing abstract method


@Override
public void printArea() {
double area = 0.5 * dim1 * dim2;
System.out.println("Area of Triangle: " + area);
}
}

// Circle class extending Shape


class Circle extends Shape {
// Constructor
public Circle(int radius) {
this.dim1 = radius;
}

// Implementing abstract method


@Override
public void printArea() {
double area = Math.PI * dim1 * dim1;
System.out.println("Area of Circle: " + area);
}
}

// Main class to test the implementation


public class ShapeMain {
public static void main(String[] args) {
// Create objects of Rectangle, Triangle and Circle
Rectangle rectangle = new Rectangle(5, 10);
Triangle triangle = new Triangle(4, 8);
Circle circle = new Circle(6);

// 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();
}

class Rectangle implements Shape {


private int dim1;
private int dim2;

public Rectangle(int length, int breadth) {


this.dim1 = length;
this.dim2 = breadth;
}

@Override
public void printArea() {
int area = dim1 * dim2;
System.out.println("Area of Rectangle: " + area);
}
}

class Triangle implements Shape {


private int dim1;
private int dim2;

public Triangle(int base, int height) {


this.dim1 = base;
this.dim2 = height;
}

@Override
public void printArea() {
double area = 0.5 * dim1 * dim2;
System.out.println("Area of Triangle: " + area);
}
}

class Circle implements Shape {


private int dim1;

public Circle(int radius) {


this.dim1 = radius;
}

@Override
public void printArea() {
double area = Math.PI * dim1 * dim1;
System.out.println("Area of Circle: " + area);
}
}

// Step 3: Main class ShapeMain to test the implementation


public class ShapeMain {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 10);
Triangle triangle = new Triangle(4, 8);
Circle circle = new Circle(6);

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();
}

class InvalidDimensionException extends Exception {


public InvalidDimensionException(String message) {
super(message);
}
}

class Rectangle implements Shape {


private int dim1;
private int dim2;

public Rectangle(int length, int breadth) throws InvalidDimensionException {


if (length <= 0 || breadth <= 0) {
throw new InvalidDimensionException("Dimensions must be positive for Rectangle.");
}
this.dim1 = length;
this.dim2 = breadth;
}

@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());
}
}
}

class Triangle implements Shape {


private int dim1;
private int dim2;

public Triangle(int base, int height) throws InvalidDimensionException {


if (base <= 0 || height <= 0) {
throw new InvalidDimensionException("Dimensions must be positive for Triangle.");
}
this.dim1 = base;
this.dim2 = height;
}

@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());
}
}
}

class Circle implements Shape {


private int dim1;
public Circle(int radius) throws InvalidDimensionException {
if (radius <= 0) {
throw new InvalidDimensionException("Radius must be positive for Circle.");
}
this.dim1 = radius;
}

@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());
}
}
}

public class ShapeMain {


public static void main(String[] args) {
try {
Rectangle rectangle = new Rectangle(5, 10);
Triangle triangle = new Triangle(4, 8);
Circle circle = new Circle(6);

rectangle.printArea();
triangle.printArea();
circle.printArea();

Rectangle invalidRectangle = new Rectangle(-1, 5);


} catch (InvalidDimensionException e) {
System.out.println("Invalid Dimension Exception: " + e.getMessage());
}
}
}

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;

public SquareThread(int number) {


this.number = number;
}
public void computeSquare() {
int square = number * number;
System.out.println("Square of " + number + " is: " + square);
}
@Override
public void run() {
computeSquare();
}
}
class CubeThread extends Thread {
private int number;

public CubeThread(int number) {


this.number = number;
}
public void computeCube() {
int cube = number * number * number;
System.out.println("Cube of " + number + " is: " + cube);
}
@Override
public void run() {
computeCube();
}
}
public class MultiThreadedApp {
public static void main(String[] args) {
RandomNumberGenerator randomNumberGenerator = new RandomNumberGenerator();
Thread generatorThread = new Thread(randomNumberGenerator);
generatorThread.start(); // Start the random number generator thread
}
}
Output

Result

Thus the ‘Java’ program for multi-threading has been executed and the output is verified successfully.
Ex NO: 8

FILE HANDLING
DATE :

Aim

To write a Java program to file handling

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());
}
}

// Method to read content from a file


public void readFromFile(String fileName) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
System.out.println("Reading from file " + fileName + ":");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading from file: " + e.getMessage());
}
}
}

public class FileHandlingDemo {


public static void main(String[] args) {
FileHandler fileHandler = new FileHandler();
String fileName = "testfile.txt";
String content = "Hello, this is a test file content.";

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

DATE : JAVAFX CONTROLS, LAYOUTS, MENUS

Aim

To write a ‘Java’ program to implement JavaFx controls, layouts and menus.

Algorithm

Step 1: Setup and Imports the needed packages


Import necessary JavaFX packages.
Extend Application class for JavaFX application.
Step 2: Define Application Class:
Override start() method to initialize the primary stage (main window).
Step 3: Create UI Components:
Use JavaFX controls (Button, Label, TextField, TextArea, etc.) for user interaction.
Define layouts (VBox, HBox, GridPane, etc.) to organize and position controls.
Step 4: Add Event Handling:
Implement event handlers (ActionEvent, MouseEvent, etc.) for interactive components (e.g.,
buttons).
Step 5: Include Menus:
Implement menus (MenuBar, Menu, MenuItem) for additional functionality and navigation.

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;

public class RegistrationFormApplication extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Registration Form JavaFX Application");

// Create the registration form grid pane


GridPane gridPane = createRegistrationFormPane();
// Add UI controls to the registration form grid pane
addUIControls(gridPane);
// Create a scene with registration form grid pane as the root node
Scene scene = new Scene(gridPane, 800, 500);
// Set the scene in primary stage
primaryStage.setScene(scene);

primaryStage.show();
}

private GridPane createRegistrationFormPane() {


// Instantiate a new Grid Pane
GridPane gridPane = new GridPane();

// Position the pane at the center of the screen, both vertically and horizontally
gridPane.setAlignment(Pos.CENTER);

// Set a padding of 20px on each side


gridPane.setPadding(new Insets(40, 40, 40, 40));

// Set the horizontal gap between columns


gridPane.setHgap(10);

// Set the vertical gap between rows


gridPane.setVgap(10);

// Add Column Constraints

// columnOneConstraints will be applied to all the nodes placed in column one.


ColumnConstraints columnOneConstraints = new ColumnConstraints(100, 100,
Double.MAX_VALUE);
columnOneConstraints.setHalignment(HPos.RIGHT);

// columnTwoConstraints will be applied to all the nodes placed in column two.


ColumnConstraints columnTwoConstrains = new ColumnConstraints(200,200,
Double.MAX_VALUE);
columnTwoConstrains.setHgrow(Priority.ALWAYS);

gridPane.getColumnConstraints().addAll(columnOneConstraints, columnTwoConstrains);

return gridPane;
}

private void addUIControls(GridPane gridPane) {


// Add Header
Label headerLabel = new Label("Registration Form");
headerLabel.setFont(Font.font("Arial", FontWeight.BOLD, 24));
gridPane.add(headerLabel, 0,0,2,1);
GridPane.setHalignment(headerLabel, HPos.CENTER);
GridPane.setMargin(headerLabel, new Insets(20, 0,20,0));

// Add Name Label


Label nameLabel = new Label("Full Name : ");
gridPane.add(nameLabel, 0,1);

// Add Name Text Field


TextField nameField = new TextField();
nameField.setPrefHeight(40);
gridPane.add(nameField, 1,1);

// Add Email Label


Label emailLabel = new Label("Email ID : ");
gridPane.add(emailLabel, 0, 2);

// Add Email Text Field


TextField emailField = new TextField();
emailField.setPrefHeight(40);
gridPane.add(emailField, 1, 2);

// Add Password Label


Label passwordLabel = new Label("Password : ");
gridPane.add(passwordLabel, 0, 3);

// Add Password Field


PasswordField passwordField = new PasswordField();
passwordField.setPrefHeight(40);
gridPane.add(passwordField, 1, 3);

// Add Submit Button


Button submitButton = new Button("Submit");
submitButton.setPrefHeight(40);
submitButton.setDefaultButton(true);
submitButton.setPrefWidth(100);
gridPane.add(submitButton, 0, 4, 2, 1);
GridPane.setHalignment(submitButton, HPos.CENTER);
GridPane.setMargin(submitButton, new Insets(20, 0,20,0));

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();
}

public static void main(String[] args) {


launch(args);
}
}

Output

Result

Thus, the ‘Java’ program to implement JavaFX has been executed and the output is verified
successfully.
Ex NO: 10

DATE : MINI PROJECT

Aim

To develop a ‘Java’ mini project

Algorithm

Step 1: Start

Step 2: Initialize GUI

Set up the JavaFX application window (Stage) titled "Enhanced Calculator".


Create a GridPane layout with horizontal and vertical gaps, and padding for the content.

Step 3: Create Text Fields and Labels

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: ".

Step 4: Define Operation Classes

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

Create buttons (addButton, subtractButton, multiplyButton, divideButton) for each operation


(Add, Subtract, Multiply, Divide).
Assign event handlers to each button to perform the respective operation using lambda
expressions (e -> performOperation(new OperationSubclass())).

Step 6: Perform Operation

Implement the performOperation(Operation operation) method:


Retrieve input values (num1Text, num2Text) from num1Field and num2Field.
Validate input using isValidNumber() method to ensure numeric format.
Convert input strings to double values (num1, num2).
Invoke the operate() method of the selected Operation subclass (Addition, Subtraction, etc.).
Handle exceptions (NumberFormatException for invalid input format,
IllegalArgumentException for division by zero) with appropriate error messages displayed in
resultLabel.

Step 7: Validate Number Input

Implement isValidNumber(String text) to verify if the input string matches the numeric format
using regular expressions.

Step 8: Display Result

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);
}

class Addition extends Operation {


@Override
double operate(double num1, double num2) {
return num1 + num2;
}
}
class Subtraction extends Operation {
@Override
double operate(double num1, double num2) {
return num1 - num2;
}
}
class Multiplication extends Operation {
@Override
double operate(double num1, double num2) {
return num1 * num2;
}
}

class Division extends Operation {


@Override
double operate(double num1, double num2) {
if (num2 != 0) {
return num1 / num2;
} else {
throw new IllegalArgumentException("Division by zero");
}
}
}

public class Main extends Application {

private TextField num1Field;


private TextField num2Field;
private Label resultLabel;

public static void main(String[] args) {


launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Enhanced Calculator");

GridPane grid = new GridPane();


grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(10, 10, 10, 10));

num1Field = new TextField();


num1Field.setPromptText("Enter first number");
GridPane.setConstraints(num1Field, 0, 0);
num2Field = new TextField();
num2Field.setPromptText("Enter second number");
GridPane.setConstraints(num2Field, 0, 1);
resultLabel = new Label("Result: ");
GridPane.setConstraints(resultLabel, 0, 2);
Button addButton = new Button("Add");
addButton.setOnAction(e -> performOperation(new Addition()));
GridPane.setConstraints(addButton, 1, 0);
Button subtractButton = new Button("Subtract");
subtractButton.setOnAction(e -> performOperation(new Subtraction()));
GridPane.setConstraints(subtractButton, 2, 0);
Button multiplyButton = new Button("Multiply");
multiplyButton.setOnAction(e -> performOperation(new Multiplication()));
GridPane.setConstraints(multiplyButton, 1, 1);
Button divideButton = new Button("Divide");
divideButton.setOnAction(e -> performOperation(new Division()));
GridPane.setConstraints(divideButton, 2, 1);
grid.getChildren().addAll(num1Field, num2Field, resultLabel, addButton, subtractButton,
multiplyButton, divideButton);
Scene scene = new Scene(grid, 300, 200);
primaryStage.setScene(scene);
primaryStage.show();
}

private void performOperation(Operation operation) {


String num1Text = num1Field.getText();
String num2Text = num2Field.getText();

if (isValidNumber(num1Text) && isValidNumber(num2Text)) {


try {
double num1 = Double.parseDouble(num1Text);
double num2 = Double.parseDouble(num2Text);

double result = operation.operate(num1, num2);


resultLabel.setText("Result: " + result);
} catch (NumberFormatException e) {
resultLabel.setText("Result: Invalid Input");
} catch (IllegalArgumentException e) {
resultLabel.setText("Result: Error (" + e.getMessage() + ")");
}
} else {
resultLabel.setText("Result: Invalid Input");
}
}

private boolean isValidNumber(String text) {


return text.matches("-?\\d*\\.?\\d+");
}
}

Output
Result

Thus, the ‘Java’ calculator mini project is verified successfully.


Ex NO: 11 CONTENT BEYOND SYLLABUS
DATE : GENERIC FUNCTION

Aim

To write a ‘Java’ program to implement generic function.

Algorithm

Step 1: Start

Step 2: Define a Generic Method

Step 3: Validate the input

Step 4: Initialize Maximum Value

Step 5: Iterate through Array elements

Step 6: Return Maximum Value

Step 7: Implement the Main Method

Step 8: Create sample arrays

Step 9: Stop

Program

import java.util.Arrays;

public class MaxValueFinder {

// Generic method to find maximum value in an array of Comparable elements


public static <T extends Comparable<T>> T findMax(T[] array) {
if (array == null || array.length == 0) {
throw new IllegalArgumentException("Array must not be empty or null");
}
T max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i].compareTo(max) > 0) {
max = array[i];
}
}
return max;
}

public static void main(String[] args) {


// Example usage with different types
Integer[] intArray = {10, 3, 7, 15, 2};
Double[] doubleArray = {3.5, 1.2, 8.9, 4.7};
String[] stringArray = {"apple", "orange", "banana", "pear"};

// Find maximum values


Integer maxInt = findMax(intArray);
Double maxDouble = findMax(doubleArray);
String maxString = findMax(stringArray);

// 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

To write a ‘Java’ program to generic classses.

Algorithm

Step 1: Start

Step 2: Define a Generic Class Box<T>

Step 3: Define Class Members

Step 4: Create a Main Class GenericBoxDemo

Step 5: Instantiate and Use Box Objects

Step 6: Stop

Program

// Step 1: Start

// Step 2: Define a generic class Box<T>


class Box<T> {
private T item;

// Constructor to initialize the box with an item


public Box(T item) {
this.item = item;
}

// Method to get the item from the box


public T getItem() {
return item;
}

// Method to set the item in the box


public void setItem(T item) {
this.item = item;
}

// Method to display information about the item in the box


public void displayBoxContents() {
System.out.println("Box contains: " + item.toString());
}
}

// Step 3: Main class to demonstrate generic class usage


public class GenericBoxDemo {
public static void main(String[] args) {
// Step 4: Create instances of Box with different types
// Create a Box for Integer
Box<Integer> integerBox = new Box<>(10);
integerBox.displayBoxContents();

// Create a Box for String


Box<String> stringBox = new Box<>("Hello, Generics!");
stringBox.displayBoxContents();

// Create a Box for Double


Box<Double> doubleBox = new Box<>(3.14);
doubleBox.displayBoxContents();

// Step 5: Modify and display box contents


// Modify integerBox contents
integerBox.setItem(20);
integerBox.displayBoxContents();

// Modify stringBox contents


stringBox.setItem("Updated content!");
stringBox.displayBoxContents();

// Modify doubleBox contents


doubleBox.setItem(2.718);
doubleBox.displayBoxContents();
// Step 6: Stop
}
}

Output:

Result

Thus the ‘Java’ program to implement the generic classes has been executed and the output is verified
successfully.

You might also like