0% found this document useful (0 votes)
44 views80 pages

Oop Final

Uploaded by

telebe3450
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)
44 views80 pages

Oop Final

Uploaded by

telebe3450
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
You are on page 1/ 80

1

L D COLLEGE OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
B E Semester- IV
Object Oriented Programming -I (3140705)
List of Experiments (Academic Year 2022-23)

Sr.
Title CO Planned Date
No.
Second Week,
1 To learn basic java programming constructs. CO1
March
Third Week,
2 To learn Arrays and Strings in Java. CO1
March
Fourth Week,
3 To implement basic OO concept. CO2
March
First Week,
4 To implement inheritance. CO2
April
To demonstrate the use of abstract classes and Second Week,
5 CO2
interfaces. April
Third Week,
6 To implement exception handling. CO3
April
Fourth Week,
7 To demonstrate the use of multithreading. CO3
April
First Week,
8 To demonstrate I/O from files. CO4
May
Second Week,
9 To learn recursion and generics. CO4
May
Third Week,
10 To demonstrate the use of Collection framework. CO4
May
Fourth Week,
11 To learn JAVA FX UI Controls CO5
May
First Week, Jun
12 To implement event handling and animation. CO5

Course Coordinator

Kalpesh M Patel

Enrolment no. : 220280107089


2

Practical 1: To learn basic java programming constructs.

1. Write a program that displays the area and perimeter of a circle that has a radius of 5.5
using the following formula: perimeter = 2 * radius * pi, area = radius * radius * pi
Program:

public class Circle {

public static void main(String[] args) {


double radius = 5.5;
double pi = Math.PI;

double area = pi * radius * radius;


double perimeter = 2 * pi * radius;

System.out.printf("Area of the circle:%.2f\n", area);


System.out.printf("Perimeter of the circle:%.2f \n", perimeter);
}
}

Output:

2. Average acceleration is defined as the change of velocity divided by the time taken to make
the change, as shown in the following formula: a = v1 - v0/t Write a program that prompts
the user to enter the starting velocity v0 in meters/ second, the ending velocity v1 in
meters/second, and the time span t in seconds, and displays the average acceleration.
Here is a sample run:
Enter v0, v1, and t: 5.5, 50.9, 4.5
The average acceleration is 10.0889
Program:

import java.util.Scanner;

public class AverageAcceleration {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

Enrolment no. : 220280107089


3

System.out.println("Enter starting velocity (m/s): ");


double v0 = scanner.nextDouble();

System.out.println("Enter ending velocity (m/s): ");


double v1 = scanner.nextDouble();

System.out.println("Enter time span (s): ");


double t = scanner.nextDouble();

double averageAcceleration = (v1 - v0) / t;

System.out.printf("The average acceleration is: %.2f m/s^2\n", averageAcceleration);

scanner.close();
}
}

Output:

3. Write a program that prompts the user to enter a three-digit integer and determines whether
it is a palindrome number. A number is palindrome if it reads the same from right to left
and from left to right.
Here is a sample run of this program:
Enter a three-digit integer: 121
121 is a palindrome
Enter a three-digit integer: 123
123 is not a palindrome
Program:

import java.util.*;

public class practical {


public static void main(String[] args)

Enrolment no. : 220280107089


4

{
int n;
Scanner sc = new Scanner(System.in);
System.out.println("enter three digit number");

n=sc.nextInt();

if(n<100 || n>999)
{
System.out.println("please enter three digit number...!!");
}

else
{
int a = n%10;
int b = n/100;

if (a==b)
{
System.out.println("number is pelindrome");
}
else{
System.out.println("number is not pelindrome");
}
}
sc.close();
}
}

Output:

Enrolment no. : 220280107089


5

4. Suppose a right triangle is placed in a plane. The right-angle point is placed at (0, 0), and
the other two points are placed at (200, 0), and (0, 100). Write a program that prompts the
user to enter a point with x- and y-coordinates and determines whether the point is inside
the triangle.
Here are the sample runs:
Enter a point's x- and y-coordinates: 100.5, 25.5
The point is in the triangle
Enter a point's x- and y-coordinates: 100.5, 50.5
The point is not in the triangle
Program:

import java.util.Scanner;

public class PointInTriangle {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Enter a point's x-coordinate: ");


double x = scanner.nextDouble();

System.out.println("Enter a point's y-coordinate: ");


double y = scanner.nextDouble();

// Check if point is on the edges (special cases)


if ((x == 0 && 0 <= y && y <= 100) || (y == 0 && 0 <= x && x <= 200)) {
System.out.println("The point is on the triangle's edge.");
return;
}

// Check if the point is below the line connecting (0, 100) and (200, 0)
if ((y - 100) / (x - 200) < 0) {
System.out.println("The point is outside the triangle.");
return;
}

System.out.println("The point is in the triangle.");

scanner.close();
}
}

Enrolment no. : 220280107089


6

Output:

5. The great circle distance is the distance between two points on the surface of a sphere. Let
(x1, y1) and (x2, y2) be the geographical latitude and longitude of two points. The great
circle distance between the two points can be computed using the following formula: d =
radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2)) Write a program that
prompts the user to enter the latitude and longitude of two points on the earth in degrees
and displays its great circle distance. The average earth radius is 6,371.01 km. Note that
you need to convert the degrees into radians using the Math.toRadians method since the
Java trigonometric methods use radians. The latitude and longitude degrees in the formula
are for north and west. Use negative to indicate south and east degrees.
Here is a sample run:
Enter point 1 (latitude and longitude) in degrees: 39.55, -116.25
Enter point 2 (latitude and longitude) in degrees: 41.5, 87.37
The distance between the two points is 10691.79183231593 km
Program:

import java.util.Scanner;
import java.lang.Math;

public class GreatCircleDistance {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

double EARTH_RADIUS_KM = 6371.01;

System.out.println("Enter point 1 (latitude and longitude) in degrees:");


double lat1 = Math.toRadians(scanner.nextDouble());
double lon1 = Math.toRadians(scanner.nextDouble());

System.out.println("Enter point 2 (latitude and longitude) in degrees:");


double lat2 = Math.toRadians(scanner.nextDouble());
double lon2 = Math.toRadians(scanner.nextDouble());

Enrolment no. : 220280107089


7

double distance = calculateGreatCircleDistance(EARTH_RADIUS_KM, lat1, lon1,


lat2, lon2);

System.out.printf("The distance between the two points is %.2f km\n", distance);

scanner.close();
}

public static double calculateGreatCircleDistance(double radius, double lat1, double lon1,


double lat2, double lon2) {
double sinLat1 = Math.sin(lat1);
double sinLat2 = Math.sin(lat2);
double cosLat1 = Math.cos(lat1);
double cosLat2 = Math.cos(lat2);
double deltaLon = lon2 - lon1;

double part1 = sinLat1 * sinLat2;


double part2 = cosLat1 * cosLat2 * Math.cos(deltaLon);

double angle = Math.acos(part1 + part2);

return radius * angle;


}
}

Output:

Enrolment no. : 220280107089


8

Practical 2: To learn Arrays and Strings in Java.

1. Assume letters A, E, I, O, and U as the vowels. Write a program that prompts the user to
enter a string and displays the number of vowels and consonants in the string.
Program:

import java.util.Scanner;

public class SimpleVowelConsonantCounter {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a word (no spaces please!): ");


String word = scanner.nextLine();

int vowelCount = 0;
int consonantCount = 0;

for (char letter : word.toLowerCase().toCharArray()) {

if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowelCount++;
} else if (letter >= 'a' && letter <= 'z')
consonantCount++;
}
}

System.out.println("Vowels: " + vowelCount);


System.out.println("Consonants: " + consonantCount);

scanner.close();
}
}

Output:

Enrolment no. : 220280107089


9

2. Write a program that prompts the user to enter two strings and displays the largest common
prefix of the two strings.
Program:

import java.util.Scanner;

public class LongestCommonPrefix {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first string: ");


String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

int prefixLength = 0;
while (prefixLength < str1.length() && prefixLength < str2.length() &&
str1.charAt(prefixLength) == str2.charAt(prefixLength)) {
prefixLength++;
}

String commonPrefix = str1.substring(0, prefixLength);

if (commonPrefix.isEmpty()) {
System.out.println("The two strings have no common prefix.");
} else {
System.out.println("The longest common prefix is: " + commonPrefix);
}

scanner.close();
}
}

Output:

Enrolment no. : 220280107089


10

3. Some websites impose certain rules for passwords. Write a method that checks whether a
string is a valid password. Suppose the password rules are as follows: A password must
have at least eight characters. A password consists of only letters and digits. A password
must contain at least two digits. Write a program that prompts the user to enter a password
and displays Valid Password if the rules are followed or Invalid Password otherwise.
Program:

import java.util.Scanner;

public class Password {

public static void main(String[] args) {


String x;
int i;
int count = 0;
Scanner s1 = new Scanner(System.in);

int flag = 0;

while (flag != 2) {

System.out.println("enter your password");


x = s1.nextLine();

char[] c = x.toCharArray();
if (c.length >= 8) {
for (i = 0; i < c.length; i++) {
if ((c[i] >= 65 && c[i] <= 122) || (c[i] >= 48 && c[i] <= 57)) {
if ((c[i] >= 48 && c[i] <= 57)) {
count++;
flag = 1;
}
} else {
System.out.println("password contains only letters and digits");
break;
}
}
}

else {
System.out.println("password must be contain atleast 8 character");
continue;
}

Enrolment no. : 220280107089


11

if (count >= 2) {
System.out.println("password is valid");
flag = 2;
} else {
System.out.println("password must contains at least two digits");
continue;
}
}
s1.close();
}
}

Output:

4. Write a method that returns a new array by eliminating the duplicate values in the array
using the following method header: public static int[] eliminateDuplicates(int[] list) Write
a test program that reads in ten integers, invokes the method, and displays the result.

Program:

import java.util.Arrays;

public class Main {


public static void main(String[] args) {
// Read in ten integers
int[] numbers = new int[10];
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter ten integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}

// Eliminate duplicates
int[] result = eliminateDuplicates(numbers);

Enrolment no. : 220280107089


12

// Display the result


System.out.print("The distinct numbers are: ");
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + " ");
}
}

public static int[] eliminateDuplicates(int[] list) {


// Sort the array to make duplicate values adjacent
Arrays.sort(list);

// Count the number of distinct elements


int count = 0;
for (int i = 0; i < list.length - 1; i++) {
if (list[i] != list[i + 1]) {
count++;
}
}
count++; // Increment for the last element

// Create a new array to store the distinct elements


int[] result = new int[count];
int index = 0;
result[index++] = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] != list[i - 1]) {
result[index++] = list[i];
}
}

return result;
}
}
Output:

Enrolment no. : 220280107089


13

5. Write a method that returns the index of the smallest element in an array of integers. If the
number of such elements is greater than 1, return the smallest index. Use the following
header: public static int indexOfSmallestElement(double[] array)
Program:

import java.util.Scanner;

public class Main {


public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the size of the array


System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

// Prompt the user to enter the elements of the array


System.out.print("Enter the elements of the array: ");
double[] array = new double[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextDouble();
}

// Call the indexOfSmallestElement method


int smallestIndex = indexOfSmallestElement(array);

// Display the result


System.out.println("The index of the smallest element is: " + smallestIndex);

// Close the scanner to prevent resource leak


scanner.close();
}

public static int indexOfSmallestElement(double[] array) {


if (array == null || array.length == 0) {
// If array is null or empty, return -1 to indicate no smallest element
return -1;
}

double smallest = array[0];


int smallestIndex = 0;

// Iterate through the array to find the smallest element and its index

Enrolment no. : 220280107089


14

for (int i = 1; i < array.length; i++) {


if (array[i] < smallest) {
smallest = array[i];
smallestIndex = i;
} else if (array[i] == smallest && i < smallestIndex) {
// If a smaller element with the same value is found at a smaller index,
// update the smallestIndex to the current index
smallestIndex = i;
}
}

return smallestIndex;
}
}

Output:

Enrolment no. : 220280107089


15

Practical 3: To implement basic OO concept.

1 Design a class named Rectangle to represent a rectangle. The class contains: Two double data fields
named width and height that specify the width and height of the rectangle. The default values are 1
for both width and height.
A no-arg constructor that creates a default rectangle.
A constructor that creates a rectangle with the specified width and height.
A method named getArea() that returns the area of this rectangle.
A method named getPerimeter() that returns the perimeter.
Write a test program that creates two Rectangle objects—one with width 4 and height 40 and the other
with width 3.5 and height 35.9.
Display the width, height, area, and perimeter of each rectangle in this order.
Program:

public class Rectangle {

// Data fields for width and height


private double width = 1.0;
private double height = 1.0;

// No-arg constructor with default values


public Rectangle() {
}

// Constructor with specified width and height


public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

// Method to calculate and return the area


public double getArea() {
return width * height;
}

// Method to calculate and return the perimeter


public double getPerimeter() {
return 2 * (width + height);
}

// Test program
public static void main(String[] args) {
// Create two Rectangle objects
Rectangle rect1 = new Rectangle(4.0, 40.0);
Rectangle rect2 = new Rectangle(3.5, 35.9);

// Display information for each rectangle

Enrolment no. : 220280107089


16

System.out.println("Rectangle 1:");
System.out.println(" Width: " + rect1.width);
System.out.println(" Height: " + rect1.height);
System.out.println(" Area: " + rect1.getArea());
System.out.println(" Perimeter: " + rect1.getPerimeter());

System.out.println("\nRectangle 2:");
System.out.println(" Width: " + rect2.width);
System.out.println(" Height: " + rect2.height);
System.out.println(" Area: " + rect2.getArea());
System.out.println(" Perimeter: " + rect2.getPerimeter());
}
}

Output:

2 Design a class named Account that contains:


A private int data field named id for the account (default 0). A private double data field named balance
for the account (default 0). A private double data field named annualInterestRate that stores the
current interest rate (default 0). Assume all accounts have the same interest rate. A private Date
data field named dateCreated that stores the date when the account was created.
A no-arg constructor that creates a default account.
A constructor that creates an account with the specified id and initial balance.
The accessor and mutator methods for id, balance, and annualInterestRate.
The accessor method for dateCreated.
A method named getMonthlyInterestRate() that returns the monthly interest rate.
A method named getMonthlyInterest() that returns the monthly interest.
A method named withdraw that withdraws a specified amount from the account.
A method named deposit that deposits a specified amount to the account.
Write a test program that creates an Account object with an account ID of 1122 a balance of Re.
20,000 and an annual interest rate of 4.5%. Use the withdraw method to withdraw Re. 2,500 use the

Enrolment no. : 220280107089


17

deposit method to deposit Re. 3,000 and print the balance, the monthly interest, and the date when
this account was created.
Program:

import java.util.Date;

public class Account {

private int id = 0;
private double balance = 0.0;
private double annualInterestRate = 0.0;
private Date dateCreated;

// No-arg constructor with default values


public Account() {
dateCreated = new Date(); }

// Constructor with specified id and initial balance


public Account(int id, double balance) {
this.id = id;
this.balance = balance;
dateCreated = new Date();
}

// Accessor methods
public int getId() {
return id;
}

public double getBalance() {


return balance;
}

public double getAnnualInterestRate() {


return annualInterestRate;
}

public Date getDateCreated() {


return dateCreated;
}

// Mutator methods
public void setId(int id) {
this.id = id;
}

Enrolment no. : 220280107089


18

public void setBalance(double balance) {


this.balance = balance;
}

public void setAnnualInterestRate(double annualInterestRate) {


this.annualInterestRate = annualInterestRate;
}

// Method to calculate monthly interest rate


public double getMonthlyInterestRate() {
return annualInterestRate / 12;
}

// Method to calculate monthly interest


public double getMonthlyInterest() {
return balance * getMonthlyInterestRate();
}

// Method to withdraw an amount


public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds for withdrawal.");
}
}

// Method to deposit an amount


public void deposit(double amount) {
balance += amount;
}

// Test program
public static void main(String[] args) {
Account account = new Account(1122, 20000.0);
account.setAnnualInterestRate(4.5);

System.out.println("Balance after creation: Rs." + account.getBalance());

account.withdraw(2500.0);
System.out.println("Balance after withdrawal: Rs." + account.getBalance());

account.deposit(3000.0);
System.out.println("Balance after deposit: Rs." + account.getBalance());

Enrolment no. : 220280107089


19

System.out.println("Monthly Interest: Rs." + account.getMonthlyInterest());


System.out.println("Date Created: " + account.getDateCreated());
}
}

Output:

3 Design a class named Stock that contains:


A string data field named symbol for the stock’s symbol.
A string data field named name for the stock’s name.
A double data field named previousClosingPrice that stores the stock price for the previous day.
A double data field named currentPrice that stores the stock price for the current time.
A constructor that creates a stock with the specified symbol and name.
A method named getChangePercent() that returns the percentage changed from previousClosingPrice
to currentPrice.
Write a test program that creates a Stock object with the stock symbol ORCL, the name
Oracle Corporation, and the previous closing price of 34.5. Set a new current price to 34.35 and
display the price-change percentage.
Program:

public class Stock {

private String symbol;


private String name;
private double previousClosingPrice;
private double currentPrice;

// Constructor with specified symbol and name


public Stock(String symbol, String name) {
this.symbol = symbol;
this.name = name;
}

// Method to calculate and return the percentage change


public double getChangePercent() {
if (previousClosingPrice == 0) {
return -1.0; // Handle division by zero

Enrolment no. : 220280107089


20

}
return (currentPrice - previousClosingPrice) / previousClosingPrice * 100;
}

// Setters for previousClosingPrice and currentPrice (optional)


public void setPreviousClosingPrice(double previousClosingPrice) {
this.previousClosingPrice = previousClosingPrice;
}
public void setCurrentPrice(double currentPrice) {
this.currentPrice = currentPrice;
}

// Test program
public static void main(String[] args) {
Stock stock = new Stock("ORCL", "Oracle Corporation");
stock.setPreviousClosingPrice(34.5);
stock.setCurrentPrice(34.35);

System.out.println("Stock Symbol: " + stock.symbol);


System.out.println("Stock Name: " + stock.name);
System.out.println("Change Percentage: " + stock.getChangePercent() + "%");
}
}

Output:

Enrolment no. : 220280107089


21

Practical 4: To learn inheritance in Java.

1 (The Person, Student, Employee, Faculty, and Staff classes) Design a class named Person and
its two subclasses named Student and Employee. Make Faculty and Staff subclasses of
Employee. A person has a name, address, phone number, and email address. A student has a
class status (freshman, sophomore, junior, or senior). Define the status as a constant. An
employee has an office, salary, and date hired. A faculty member has office hours and a rank.
A staff member has a title. Override the toString method in each class to display the class name
and the person’s name.
Write a test program that creates a Person, Student, Employee, Faculty, and Staff, and invokes
their toString() methods.
Program:

class Person {
private String name;
private String address;
private String phoneNumber;
private String emailAddress;

public Person(String name, String address, String phoneNumber, String emailAddress) {


this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.emailAddress = emailAddress;
}

@Override
public String toString() {
return "Person: " + name;
}
}

class Student extends Person {


private static final String STATUS = "Student";
private String classStatus;

public Student(String name, String address, String phoneNumber, String emailAddress, String
classStatus) {
super(name, address, phoneNumber, emailAddress);
this.classStatus = classStatus;
}

@Override
public String toString() {

Enrolment no. : 220280107089


22

return STATUS + ": " + super.toString();


}
}

class Employee extends Person {


private static final String STATUS = "Employee";
private String office;
private double salary;
private String dateHired;

public Employee(String name, String address, String phoneNumber, String emailAddress, String
office, double salary, String dateHired) {
super(name, address, phoneNumber, emailAddress);
this.office = office;
this.salary = salary;
this.dateHired = dateHired;
}

@Override
public String toString() {
return STATUS + ": " + super.toString();
}
}

class Faculty extends Employee {


private static final String STATUS = "Faculty";
private String officeHours;
private String rank;

public Faculty(String name, String address, String phoneNumber, String emailAddress, String office,
double salary, String dateHired, String officeHours, String rank) {
super(name, address, phoneNumber, emailAddress, office, salary, dateHired);
this.officeHours = officeHours;
this.rank = rank;
}

@Override
public String toString() {
return STATUS + ": " + super.toString();
}
}

class Staff extends Employee {


private static final String STATUS = "Staff";

Enrolment no. : 220280107089


23

private String title;

public Staff(String name, String address, String phoneNumber, String emailAddress, String office,
double salary, String dateHired, String title) {
super(name, address, phoneNumber, emailAddress, office, salary, dateHired);
this.title = title;
}

@Override
public String toString() {
return STATUS + ": " + super.toString();
}
}

public class Main {


public static void main(String[] args) {
Person person = new Person("John Doe", "123 Main St", "123-456-7890", "[email protected]");
Student student = new Student("Alice Smith", "456 Elm St", "987-654-3210",
"[email protected]", "sophomore");
Employee employee = new Employee("Bob Johnson", "789 Oak St", "555-123-4567",
"[email protected]", "Room 101", 50000, "2022-01-01");
Faculty faculty = new Faculty("Jane Williams", "101 Pine St", "222-333-4444",
"[email protected]", "Office A", 80000, "2021-01-01", "9am-5pm", "Professor");
Staff staff = new Staff("Tom Brown", "202 Cedar St", "333-555-6666", "[email protected]",
"Office B", 40000, "2023-01-01", "Secretary");

System.out.println(person);
System.out.println(student);
System.out.println(employee);
System.out.println(faculty);
System.out.println(staff);
}
}
Output:

Enrolment no. : 220280107089


24

2 (The Account class) Design a class named Account that contains:


■ A private int data field named id for the account (default 0).
■ A private double data field named balance for the account (default 0).
■ A private double data field named annualInterestRate that stores the current interest rate
(default 0). Assume all accounts have the same interest rate.
■ A private Date data field named dateCreated that stores the date when the account was
created.
■ A no-arg constructor that creates a default account.
■ A constructor that creates an account with the specified id and initial balance.
■ The accessor and mutator methods for id, balance, and annualInterestRate.
■ The accessor method for dateCreated.
■ A method named getMonthlyInterestRate() that returns the monthly interest rate.
■ A method named getMonthlyInterest() that returns the monthly interest.
■ A method named withdraw that withdraws a specified amount from the account.
■ A method named deposit that deposits a specified amount to the account.
(Subclasses of Account)Create two subclasses for checking and saving accounts. A checking
account has an overdraft limit, but a savings account cannot be overdrawn.
Write a test program that creates objects of Account, SavingsAccount, and CheckingAccount
and invokes their toString() methods.
Program:

import java.util.Date;

class Account {
private int id;
private double balance;
private double annualInterestRate;
private Date dateCreated;

public Account() {
id = 0;
balance = 0;
annualInterestRate = 0;
dateCreated = new Date();
}

public Account(int id, double balance) {


this.id = id;
this.balance = balance;
annualInterestRate = 0;
dateCreated = new Date();
}

Enrolment no. : 220280107089


25

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public double getBalance() {


return balance;
}

public void setBalance(double balance) {


this.balance = balance;
}

public double getAnnualInterestRate() {


return annualInterestRate;
}

public void setAnnualInterestRate(double annualInterestRate) {


this.annualInterestRate = annualInterestRate;
}

public Date getDateCreated() {


return dateCreated;
}

public double getMonthlyInterestRate() {


return annualInterestRate / 12;
}

public double getMonthlyInterest() {


return balance * (getMonthlyInterestRate() / 100);
}

public void withdraw(double amount) {


if (amount > balance) {
System.out.println("Insufficient funds.");
} else {
balance -= amount;
}
}

Enrolment no. : 220280107089


26

public void deposit(double amount) {


balance += amount;
}

@Override
public String toString() {
return "Account[id=" + id + ", balance=" + balance + ", dateCreated=" + dateCreated +
"]";
}
}

class SavingsAccount extends Account {


public SavingsAccount() {
super();
}

public SavingsAccount(int id, double balance) {


super(id, balance);
}

@Override
public void withdraw(double amount) {
if (amount > getBalance()) {
System.out.println("Savings account cannot be overdrawn. Withdrawal cancelled.");
} else {
super.withdraw(amount);
}
}

@Override
public String toString() {
return "Savings " + super.toString();
}
}

class CheckingAccount extends Account {


private double overdraftLimit;

public CheckingAccount() {
super();
overdraftLimit = 0;
}

Enrolment no. : 220280107089


27

public CheckingAccount(int id, double balance, double overdraftLimit) {


super(id, balance);
this.overdraftLimit = overdraftLimit;
}

@Override
public void withdraw(double amount) {
if (amount > getBalance() + overdraftLimit) {
System.out.println("Exceeds overdraft limit. Withdrawal cancelled.");
} else {
super.withdraw(amount);
}
}

@Override
public String toString() {
return "Checking " + super.toString();
}
}

public class Main {


public static void main(String[] args) {
Account account = new Account(1001, 1000);
SavingsAccount savingsAccount = new SavingsAccount(2001, 2000);
CheckingAccount checkingAccount = new CheckingAccount(3001, 3000, 500);

System.out.println(account);
System.out.println(savingsAccount);
System.out.println(checkingAccount);
}
}
Output:

Enrolment no. : 220280107089


28

3 Suppose that we are required to model students and teachers in our application. We can define a
super class called Person to store common properties such as name and address, and subclasses
Student and Teacher for their specific properties. For students, we need to maintain the courses
taken and their respective grades; add a course with grade, print all courses taken and the
average grade. Assume that a student takes no more than 30 courses for the entire program. For
teachers, we need to maintain the courses taught currently, and able to add or remove a course
taught. Assume that a teacher teaches not more than 5 courses concurrently.

Design the classes as follows.

Write a program to implement all these classes and test program to test all the methods.

Enrolment no. : 220280107089


29

Program:

import java.util.Arrays;

class Person {
private String name;
private String address;

public Person(String name, String address) {


this.name = name;
this.address = address;
}

public String getName() {


return name;
}

public String getAddress() {


return address;
}

@Override
public String toString() {
return "Person [name=" + name + ", address=" + address + "]";
}
}

class Student extends Person {


private final String[] courses = new String[30]; // Array to store course names (max 30)
private final int[] grades = new int[30]; // Array to store grades (max 30)
private int numCourses = 0; // Number of courses taken

public Student(String name, String address) {


super(name, address);
}

public void addCourse(String course, int grade) {


if (numCourses == 30) {
System.out.println("Course limit reached. Cannot add more courses.");
return;
}
courses[numCourses] = course;
grades[numCourses] = grade;
numCourses++;

Enrolment no. : 220280107089


30

public void printCourses() {


if (numCourses == 0) {
System.out.println("No courses taken yet.");
return;
}
System.out.println("Courses Taken:");
for (int i = 0; i < numCourses; i++) {
System.out.println(" - " + courses[i] + ": " + grades[i]);
}
}

public double getAverageGrade() {


if (numCourses == 0) {
return 0.0;
}
return Arrays.stream(grades, 0, numCourses).average().orElse(0);
}

@Override
public String toString() {
return "Student " + super.toString();
}
}

class Teacher extends Person {


private final String[] courses = new String[5]; // Array to store course names (max 5)
private int numCourses = 0; // Number of courses taught

public Teacher(String name, String address) {


super(name, address);
}

public boolean addCourse(String course) {


if (numCourses == 5) {
System.out.println("Course limit reached. Cannot add more courses.");
return false;
}
courses[numCourses++] = course;
return true;
}

public boolean removeCourse(String course) {

Enrolment no. : 220280107089


31

for (int i = 0; i < numCourses; i++) {


if (courses[i].equals(course)) {
courses[i] = courses[--numCourses]; // Remove the course and decrement numCourses
return true;
}
}
System.out.println("Course not found.");
return false;
}

public void printCourses() {


if (numCourses == 0) {
System.out.println("No courses taught yet.");
return;
}
System.out.println("Courses Taught:");
for (int i = 0; i < numCourses; i++) {
System.out.println(" - " + courses[i]);
}
}

@Override
public String toString() {
return "Teacher " + super.toString();
}
}

public class TestSchool {

public static void main(String[] args) {


Student student = new Student("John Doe", "123 Main St");
student.addCourse("Math", 85);
student.addCourse("English", 90);
student.addCourse("Science", 78);
System.out.println(student);
student.printCourses();
System.out.println("Average Grade: " + student.getAverageGrade());

Teacher teacher = new Teacher("Jane Smith", "456 Elm St");


teacher.addCourse("Calculus");
teacher.addCourse("Literature");
teacher.addCourse("Biology");
System.out.println(teacher);
teacher.printCourses(); } }

Enrolment no. : 220280107089


32

Output:

Enrolment no. : 220280107089


33

Practical 5: To learn abstract classes and interfaces Java.

1 Write a superclass called Shape (as shown in the class diagram), which contains:
• Two instance variables color (String) and filled (boolean).
• Two constructors: a no-arg (no-argument) constructor that initializes the color to "green"
and filled to t rue, and a constructor that initializes the color and filled to the
given values.
• Getter and setter for all the instance variables. By convention, the getter for a boolean
variable xxx is called isXXX() (instead of getXxx() for all the other types).
• A toString() method that returns "A Shape with color of xxx and
filled/Not filled".
Write a test program to test all the methods defined in Shape.

Enrolment no. : 220280107089


34

Write two subclasses of Shape called Circle and Rectangle, as shown in the class
diagram.

The Circle class contains:


• An instance variable radius (double).
• Three constructors as shown. The no-arg constructor initializes the radius to 1.0.
Getter and setter for the instance variable radius.
• Methods getArea() and getPerimeter().
• Override the toString() method inherited, to return "A Circle with
radius=xxx, which is a subclass of yyy", where yyy is the output of the
toString() method from the superclass.
The Rectangle class contains:
• Two instance variables width (double) and length (double).
• Three constructors as shown. The no-arg constructor initializes the
width and length to 1.0.
• Getter and setter for all the instance variables.
• Methods getArea() and getPerimeter().
• Override the toString() method inherited, to return "A Rectangle with
width=xxx and length=zzz, which is a subclass of yyy", where yyy
is the output of the toString() method from the superclass.

Write a class called Square, as a subclass of Rectangle. Convince yourself that Square
can be modeled as a subclass of Rectangle. Square has no instance variable, but inherits
the instance variables width and length from its superclass Rectangle. Provide the appropriate
constructors (as shown in the class diagram). Hint:

public Square(double side) { super(side, side); // Call


superclass Rectangle(double, double) }

• Override the toString() method to return "A Square with side=xxx, which
is a subclass of yyy", where yyy is the output of the toString() method
from the superclass.
• Do you need to override the getArea() and getPerimeter()? Try them out.
• Override the setLength() and setWidth() to change both the width and length,
so as to maintain the square geometry.

Enrolment no. : 220280107089


35

Program:

public abstract class Shape {


private String color;
private boolean filled;

public Shape() {
this.color = "green";
this.filled = true;
}

public Shape(String color, boolean filled) {


this.color = color;
this.filled = filled;
}

public String getColor() {


return color;
}

public void setColor(String color) {


this.color = color;
}

public boolean isFilled() {


return filled;
}

public void setFilled(boolean filled) {


this.filled = filled;
}

public abstract double getArea();

public abstract double getPerimeter();

@Override
public String toString() {
String filledStatus = filled ? "filled" : "Not filled";
return "A Shape with color of " + color + " and " + filledStatus;
}
}

public class Circle extends Shape {

Enrolment no. : 220280107089


36

private double radius;

public Circle() {
super();
this.radius = 1.0;
}

public Circle(double radius) {


super();
this.radius = radius;
}

public Circle(String color, boolean filled, double radius) {


super(color, filled);
this.radius = radius;
}

public double getRadius() {


return radius;
}

public void setRadius(double radius) {


this.radius = radius;
}

@Override
public double getArea() {
return Math.PI * radius * radius;
}

@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}

@Override
public String toString() {
return "A Circle with radius=" + radius + ", which is a subclass of " + super.toString();
}
}

public class Rectangle extends Shape {


private double width;
private double length;

Enrolment no. : 220280107089


37

public Rectangle() {
super();
this.width = 1.0;
this.length = 1.0;
}

public Rectangle(double width, double length) {


super();
this.width = width;
this.length = length;
}

public Rectangle(String color, boolean filled, double width, double length) {


super(color, filled);
this.width = width;
this.length = length;
}

public double getWidth() {


return width;
}

public void setWidth(double width) {


this.width = width;
}

public double getLength() {


return length;
}

public void setLength(double length) {


this.length = length;
}

@Override
public double getArea() {
return width * length;
}

@Override
public double getPerimeter() {
return 2 * (width + length);
}

Enrolment no. : 220280107089


38

@Override
public String toString() {
return "A Rectangle with width=" + width + " and length=" + length + ", which is a subclass of
" + super.toString();
}
}

public class Square extends Rectangle {


public Square(double side) {
super(side, side);
}

public double getSide() {


return getWidth(); // Square's side is same as width or length
}

public void setSide(double side) {


setWidth(side);
setLength(side);
}

@Override
public void setWidth(double side) {
super.setWidth(side);
super.setLength(side);
}

@Override
public void setLength(double side) {
super.setWidth(side);
super.setLength(side);
}

@Override
public String toString() {
return "A Square with side=" + getSide() + ", which is a subclass of " + super.toString();
}
}

Enrolment no. : 220280107089


39

Output:
A Circle with radius=5.0, which is a subclass of A Shape with color of blue and filled
Area: 78.53981633974483
Perimeter: 31.41592653589793

A Rectangle with width=3.0 and length=4.0, which is a subclass of A Shape with color of red and
Not filled
Area: 12.0
Perimeter: 14.0

A Square with side=2.0, which is a subclass of A Rectangle with width=2.0 and length=2.0, which
is a subclass of A Shape with color of yellow and filled
Area: 4.0
Perimeter: 8.0

2 Define an abstract class Shape. Define two classes Rectangle and Triangle from extending the
Shape class as shown blow. Test the call of getArea() methods by the instances of all the classes

Program:

abstract class Shape {


public abstract double getArea();

@Override
public String toString() {
return "A Shape";
}
}

class Rectangle extends Shape {


private double width;

Enrolment no. : 220280107089


40

private double length;

public Rectangle(double width, double length) {


this.width = width;
this.length = length;
}

@Override
public double getArea() {
return width * length;
}

@Override
public String toString() {
return "A Rectangle with width=" + width + " and length=" + length;
}
}

class Triangle extends Shape {


private double base;
private double height;

public Triangle(double base, double height) {


this.base = base;
this.height = height;
}

@Override
public double getArea() {
return 0.5 * base * height;
}
@Override
public String toString() {
return "A Triangle with base=" + base + " and height=" + height;
}
}
public class TestShapes {
public static void main(String[] args) {

Enrolment no. : 220280107089


41

Shape rectangle = new Rectangle(5, 3);


Shape triangle = new Triangle(4, 6);

System.out.println(rectangle.toString() + " has area: " + rectangle.getArea());


System.out.println(triangle.toString() + " has area: " + triangle.getArea());
}
}

Output:

Re-write the abstract super class Shape into an interface, containing


only abstract methods, as follows

Program:

interface Shape {
double getArea();
}

class Rectangle implements Shape {


private double width;
private double length;

public Rectangle(double width, double length) {


this.width = width;
this.length = length;
}

Enrolment no. : 220280107089


42

@Override
public double getArea() {
return width * length;
}
@Override
public String toString() {
return "A Rectangle with width=" + width + " and length=" + length;
}
}

class Triangle implements Shape {


private double base;
private double height;

public Triangle(double base, double height) {


this.base = base;
this.height = height;
}

@Override
public double getArea() {
return 0.5 * base * height;
}

@Override
public String toString() {
return "A Triangle with base=" + base + " and height=" + height;
}
}
public class TestShapes {
public static void main(String[] args) {
Shape rectangle = new Rectangle(5, 3);
Shape triangle = new Triangle(4, 6);

System.out.println(rectangle.toString() + " has area: " + rectangle.getArea());


System.out.println(triangle.toString() + " has area: " + triangle.getArea());
}
}

Output:

Enrolment no. : 220280107089


43

3 (The ComparableCircle class) Define a class named ComparableCircle that extends Circle
and implements Comparable. Implement the compareTo method to compare the circles on
the basis of area. Write a test class to find the larger of two instances of ComparableCircle
objects.
Program:

class ComparableCircle {
private double radius;

public ComparableCircle(double radius) {


this.radius = radius;
}

public double getRadius() {


return radius;
}

public double getArea() {


return Math.PI * radius * radius;
}

public ComparableCircle biggerThan(ComparableCircle otherCircle) {


double myArea = getArea();
double otherArea = otherCircle.getArea();

if (myArea > otherArea) {


return this; // This circle is bigger, return itself
} else {
return otherCircle; // Other circle is bigger, return it
}
}

@Override
public String toString() {
return "My circle, radius is " + radius;
}
}

public class TestComparableCircle {


public static void main(String[] args) {
ComparableCircle circle1 = new ComparableCircle(5);
ComparableCircle circle2 = new ComparableCircle(3);

ComparableCircle biggerCircle = circle1.biggerThan(circle2);

Enrolment no. : 220280107089


44

System.out.println("Bigger circle: radius " + biggerCircle.getRadius());


}
}

Output:

Enrolment no. : 220280107089


45

Practical 6: To implement exception handling in java application.

1 Write a program that meets the following requirements:


■ Creates an array with 100 randomly chosen integers.
■ Prompts the user to enter the index of the array, then displays the corresponding element value. If
the specified index is out of bounds, display the message Out of Bounds.
(ArrayIndexOutOfBoundsException)
Program:

import java.util.Random;

public class ArrayChallenge {

public static void main(String[] args) {


int[] numbers = new int[100];
Random random = new Random();

// Fill the array with random numbers


for (int i = 0; i < numbers.length; i++) {
numbers[i] = random.nextInt();
}

System.out.println("We have a secret list of 100 numbers!");

// Get user input for the index


System.out.print("Tell me a number between 0 and 99 to peek at the list: ");
Scanner scanner = new Scanner(System.in);
int guess = scanner.nextInt();

// Check if the index is in bounds


if (guess >= 0 && guess < numbers.length) {
System.out.println("Shhh, the number at spot " + guess + " is: " + numbers[guess]);
} else {
System.out.println("Oops! That spot is out of bounds. Try between 0 and 99 next time.");
}
}
}

Output:

Enrolment no. : 220280107089


46

2 Write a program that prompts the user to read two integers and displays their sum. Your program
should prompt the user to read the number again if the input is incorrect. (InputMismatchException)
Program:

import java.util.Scanner;

public class SumChallenge {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int num1, num2;

// Loop until valid integers are entered


do {
System.out.print("Hey! Give me a whole number (no decimals allowed): ");
} while (!scanner.hasNextInt()); // Check if the next input is an integer
num1 = scanner.nextInt();

do {
System.out.print("Great! Now another whole number for me: ");
} while (!scanner.hasNextInt()); // Check if the next input is an integer
num2 = scanner.nextInt();

scanner.nextLine(); // Consume any remaining newline character

int sum = num1 + num2;


System.out.println("Awesome! The sum of " + num1 + " and " + num2 + " is: " + sum);
}
}

Output:

Enrolment no. : 220280107089


47

3 Define the Triangle class with three sides. In a triangle, the sum of any two sides is greater than the
other side. The Triangle class must adhere to this rule.
Create the IllegalTriangleException class, and modify the constructor of the Triangle class to throw
an IllegalTriangleException object if a triangle is created with sides that violate the rule, as follows:
/** Construct a triangle with the specified sides */ public
Triangle(double side1, double side2, double side3)
throws IllegalTriangleException {
// Implement it
}
Program:

public class Triangle {

private double side1;


private double side2;
private double side3;

public Triangle(double side1, double side2, double side3) throws IllegalTriangleException {


if (isInvalidTriangle(side1, side2, side3)) {
throw new IllegalTriangleException("Invalid sides. Sum of any two sides must be greater
than the third side.");
}
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

private boolean isInvalidTriangle(double side1, double side2, double side3) {


return (side1 + side2 <= side3) || (side1 + side3 <= side2) || (side2 + side3 <= side1);
}

// Getters and Setters for side1, side2, and side3 (implement these)

// Other methods for the Triangle class (optional)


}

public class IllegalTriangleException extends Exception {

public IllegalTriangleException(String message) {


super(message);
}
}
Output:
Triangle 1 sides: 3.0, 4.0, 5.0
Exception caught: Invalid sides. Sum of any two sides must be greater than the third side.

Enrolment no. : 220280107089


48

Practical 7: To demonstrate the use of multithreading.

1 (Extend Thread) Write a program to create a thread extending Thread class and demonstrate the use
of slip() method.
Program:

public class ThreadDemo {

public static void main(String[] args) {


MyThread myThread = new MyThread();
myThread.start(); // Start the thread

System.out.println("Main thread running...");

try {
// Main thread sleeps for 2 seconds
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Main thread finished running");


}
}

class MyThread extends Thread {

@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread running: " + i);
try {
// Thread sleeps for 1 second
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} } }
Output:

Enrolment no. : 220280107089


49

2 (Implement Runnable) Write a program to create a thread implementing Runnable interface and
demonstrate the use of join() method.
Program:

public class ThreadDemo {

public static void main(String[] args) throws InterruptedException {


Runnable myRunnable = new MyRunnable();
Thread myThread = new Thread(myRunnable);

System.out.println("Main thread running...");


myThread.start(); // Start the thread

// Wait for the thread to finish using join()


myThread.join();

System.out.println("Main thread finished running");


}
}

class MyRunnable implements Runnable {

@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread running: " + i);
try {
// Simulate some work by sleeping for 1 second
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Output:

Enrolment no. : 220280107089


50

3 (Synchronize threads) Write a program that launches 10 threads. Each thread adds 1 to a variable sum
that initially is 0. Define an Integer wrapper object to hold sum. Run the program with and without
synchronization to see its effect.
Program:

public class SynchronizedCounter {


private Integer sum = 0; // Wrapper object for thread safety

public synchronized void increment() {


sum++; // Increment with synchronization
}
public int getSum() {
return sum;
}
}
public class UnsynchronizedCounter {

private int sum = 0; // Primitive int, not thread-safe

public void increment() {


sum++; // Increment without synchronization
}

public int getSum() {


return sum;
}
}

public class TestThreads {

public static void main(String[] args) throws InterruptedException {


// Test with synchronized counter
SynchronizedCounter synchronizedCounter = new SynchronizedCounter();
testCounter(synchronizedCounter);

// Test with unsynchronized counter


UnsynchronizedCounter unsynchronizedCounter = new UnsynchronizedCounter();
testCounter(unsynchronizedCounter);
}

private static void testCounter(Counter counter) throws InterruptedException {


int numThreads = 10;
Thread[] threads = new Thread[numThreads];

for (int i = 0; i < numThreads; i++) {

Enrolment no. : 220280107089


51

threads[i] = new Thread(() -> counter.increment());


threads[i].start();
}

// Wait for all threads to finish


for (Thread thread : threads) {
thread.join();
}
System.out.println("Final sum: " + counter.getSum());
}
}
// Interface for Counter (optional)
interface Counter {
void increment();
int getSum();
}

Output:
Final sum: 10
Final sum: 6

Enrolment no. : 220280107089


52

Practical 8: To demonstrate I/O from files.

1 (Remove text) Write a program that removes all the occurrences of a specified string from a text file.
For example, invoking java Practical7_1 John filename removes the string John from the specified
file. Your program should get the arguments from the command line.
Program:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class RemoveTextFromFile {

public static void main(String[] args) {


// Check if the correct number of command-line arguments is provided
if (args.length != 2) {
System.out.println("Usage: java RemoveTextFromFile <string_to_remove> <file_name>");
return;
}

String toRemove = args[0]; // String to be removed


String fileName = args[1]; // Name of the input file

try {
// Create a Scanner to read from the input file
Scanner scanner = new Scanner(new File(fileName));

// Create a FileWriter to write to a temporary file


FileWriter writer = new FileWriter("temp.txt");

// Iterate through each line of the input file


while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// Remove all occurrences of the specified string
String newLine = line.replaceAll(toRemove, "john");
// Write the modified line to the temporary file
writer.write(newLine + System.lineSeparator());
}

// Close the scanner and writer


scanner.close();
writer.close();

Enrolment no. : 220280107089


53

// Rename the temporary file to the original file


File tempFile = new File("temp.txt");
File originalFile = new File(fileName);
tempFile.renameTo(originalFile);

System.out.println("Successfully removed \"" + toRemove + "\" from " + fileName);

} catch (FileNotFoundException e) {
System.err.println("Error: File not found: " + e.getMessage());
} catch (IOException e) {
System.err.println("Error: IO exception: " + e.getMessage());
}
}
}

Output:
Successfully removed "john" from filename.txt

2 (Count characters, words, and lines in a file) Write a program that will count the number of characters,
words, and lines in a file. Words are separated by whitespace characters. The file name should be
passed as a command-line argument.
Program:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CountCharactersWordsLines {

public static void main(String[] args) {


if (args.length != 1) {
System.out.println("Usage: java CountCharactersWordsLines sample.txt");
return;
}

String filename = args[0];


int characterCount = 0;
int wordCount = 0;
int lineCount = 0;

try (Scanner scanner = new Scanner(new File(sample.txt))) {


while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineCount++;

Enrolment no. : 220280107089


54

// Remove non-alphanumeric characters for accurate character count


characterCount += line.replaceAll("[^\\p{Alnum}]", "").length();

wordCount += line.split("\\s+").length; // Split by whitespace


}
} catch (FileNotFoundException e) {
System.err.println("Error: File not found: " + e.getMessage());
}

System.out.println("File: " + filename);


System.out.println("Characters: " + characterCount);
System.out.println("Words: " + wordCount);
System.out.println("Lines: " + lineCount);
}
}

Output:
File: sample.txt
Characters: 68
Words: 12
Lines: 3

3 (Write/read data) Write a program to create a file named Practical7.txt if it does not exist. Write 100
integers created randomly into the file using text I/O. Integers are separated by spaces in the file.
Read the data back from the file and display the data in increasing order.
Program:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;

public class RandomNumbersFile {

public static void main(String[] args) {


String fileName = "Practical7.txt";
int numIntegers = 100;

// Create the file if it doesn't exist


createFile(fileName);

// Write 100 random integers to the file

Enrolment no. : 220280107089


55

writeRandomNumbers(fileName, numIntegers);

// Read integers from the file and sort them


int[] numbers = readIntegersFromFile(fileName);
Arrays.sort(numbers); // Use built-in sorting

// Display the sorted numbers


System.out.println("Sorted numbers:");
for (int number : numbers) {
System.out.print(number + " ");
}
}

private static void createFile(String fileName) {


File file = new File(fileName);
try {
if (file.createNewFile()) {
System.out.println("File created: " + fileName);
} else {
System.out.println("File already exists: " + fileName);
}
} catch (IOException e) {
System.err.println("Error creating file: " + e.getMessage());
}
}

private static void writeRandomNumbers(String fileName, int numIntegers) {


try (PrintWriter writer = new PrintWriter(new FileWriter(fileName, true))) { // Append mode
Random random = new Random();
for (int i = 0; i < numIntegers; i++) {
writer.print(random.nextInt() + " "); // Add space after each number
}
writer.println(); // Add newline at the end
System.out.println("Successfully wrote " + numIntegers + " random integers to the file.");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}

private static int[] readIntegersFromFile(String fileName) {


int[] numbers = new int[0]; // Empty array initially

try (Scanner scanner = new Scanner(new File(fileName))) {


while (scanner.hasNextInt()) {

Enrolment no. : 220280107089


56

numbers = Arrays.copyOf(numbers, numbers.length + 1); // Increase array size


numbers[numbers.length - 1] = scanner.nextInt();
}
System.out.println("Successfully read " + numbers.length + " integers from the file.");
} catch (FileNotFoundException e) {
System.err.println("Error: File not found: " + e.getMessage());
}

return numbers;
}
}

Output:
File created: Practical7.txt
Successfully wrote 100 random integers to the file.
Successfully read 100 integers from the file.
Sorted numbers:
-2147483648 -2147483648 -2147483648 -2147483648 -2147483648 ... (omitted for brevity)

Enrolment no. : 220280107089


57

Practical 9: To learn recursion and generics.

1 (Decimal to binary) Write a recursive method that converts a decimal number into a binary number
as a string. The method header is: public static String dec2Bin(int value)
Write a test program that prompts the user to enter a decimal number and displays its binary
equivalent.
Program:

public class DecimalToBinary {

public static String dec2Bin(int value) {


if (value == 0) {
return "0";
} else {
return dec2Bin(value / 2) + (value % 2); // Append remainder at the end
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal number: ");

int number;
try {
number = scanner.nextInt();
if (number < 0) {
throw new IllegalArgumentException("Number cannot be negative.");
}
} catch (InputMismatchException e) {
System.err.println("Invalid input. Please enter a whole number.");
return;
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
return;
}

String binary = dec2Bin(number);


System.out.println(number + " in binary: " + binary);
}
}
Output:

Enrolment no. : 220280107089


58

2 (Distinct elements in ArrayList) Write the following method that returns a new ArrayList. The new
list contains the non-duplicate elements from the original list.
Program:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class RemoveDuplicates {

public static void main(String[] args) {


ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("Alice");
names.add("David");

System.out.println("Original list: " + names);

ArrayList<String> uniqueNamesLoop = removeDuplicatesLoop(names);


System.out.println("Unique elements (Loop): " + uniqueNamesLoop);
}

public static ArrayList<T> removeDuplicatesLoop(ArrayList<T> list) {


ArrayList<T> newList = new ArrayList<>();
for (T element : list) {
if (!newList.contains(element)) { // Check if element already exists
newList.add(element);
}
}
return newList;
}
}

Output:

Enrolment no. : 220280107089


59

public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list)


3 (Generic binary search) Implement the following method using binary search.
public static <E extends Comparable<E>> int
binarySearch(E[] list, E key)
program:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class RemoveDuplicatesBinarySearchUserInput {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Get user input for elements


ArrayList<String> elements = new ArrayList<>();
System.out.println("Enter elements (separated by spaces, enter 'done' to finish):");
while (true) {
String element = scanner.nextLine();
if (element.equalsIgnoreCase("done")) {
break;
}
elements.add(element);
}

System.out.println("Original list: " + elements);

// Remove duplicates using HashSet


ArrayList<String> uniqueElements = removeDuplicates(elements);
System.out.println("Unique elements: " + uniqueElements);

// Get user input for search key


System.out.print("Enter element to search: ");
String key = scanner.nextLine();

// Convert unique elements to array for binary search


String[] uniqueElementsArray = uniqueElements.toArray(new String[0]);
int index = binarySearch(uniqueElementsArray, key);

if (index != -1) {
System.out.println("Element \"" + key + "\" found at index: " + index);
} else {
System.out.println("Element \"" + key + "\" not found in the list.");

Enrolment no. : 220280107089


60

}
}

// Method to remove duplicates (same as previous example)


public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) {
Set<E> uniqueElements = new HashSet<>(list); // Convert to HashSet to remove duplicates
return new ArrayList<>(uniqueElements); // Create a new ArrayList from the unique elements set
}

// Generic binary search implementation


public static <E extends Comparable<E>> int binarySearch(E[] list, E key) {
int low = 0;
int high = list.length - 1;

while (low <= high) {


int mid = (low + high) / 2;
int compareResult = key.compareTo(list[mid]);

if (compareResult == 0) {
return mid; // Key found at the middle index
} else if (compareResult < 0) {
high = mid - 1; // Search in the left half (key is smaller)
} else {
low = mid + 1; // Search in the right half (key is larger)
}
}

return -1; // Key not found


}
}

Output:

Enrolment no. : 220280107089


61

Practical 10: To demonstrate the use of Collection framework.

1 (Store numbers in a linked list) Write a program that lets the user enter numbers from a graphical user
interface and displays them in a text area, as shown in Figure. Use a linked list to store the numbers.
Do not store duplicate numbers. Add the buttons Sort, Shuffle, and Reverse to sort, shuffle, and reverse
the list.

Program:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class LinkedListNumbersGUI extends JFrame implements


ActionListener {

private JTextField numberTextField;


private JTextArea numberTextArea;
private JButton addButton, sortButton, shuffleButton,
reverseButton;
private LinkedList<Integer> numbers;

public LinkedListNumbersGUI() {
super("Linked List Numbers");
numbers = new LinkedList<>();

numberTextField = new JTextField(10);

Enrolment no. : 220280107089


62

numberTextArea = new JTextArea();


numberTextArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(numberTextArea);

addButton = new JButton("Add");


sortButton = new JButton("Sort");
shuffleButton = new JButton("Shuffle");
reverseButton = new JButton("Reverse");

addButton.addActionListener(this);
sortButton.addActionListener(this);
shuffleButton.addActionListener(this);
reverseButton.addActionListener(this);

JPanel topPanel = new JPanel();


topPanel.add(numberTextField);
topPanel.add(addButton);

JPanel buttonPanel = new JPanel();


buttonPanel.add(sortButton);
buttonPanel.add(shuffleButton);
buttonPanel.add(reverseButton);

add(topPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);

setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
try {
int number = Integer.parseInt(numberTextField.getText());
if (!numbers.contains(number)) { // Add only if not a
duplicate
numbers.add(number);
updateTextArea();
numberTextField.setText("");
}
} catch (NumberFormatException ex) {
System.err.println("Invalid input: Please enter a whole
number.");
}

Enrolment no. : 220280107089


63

} else if (e.getSource() == sortButton) {


Collections.sort(numbers);
updateTextArea();
} else if (e.getSource() == shuffleButton) {
Collections.shuffle(numbers, new Random());
updateTextArea();
} else if (e.getSource() == reverseButton) {
Collections.reverse(numbers);
updateTextArea();
}
}

private void updateTextArea() {


StringBuilder sb = new StringBuilder();
for (int number : numbers) {
sb.append(number).append(" ");
}
numberTextArea.setText(sb.toString().trim());
}

public static void main(String[] args) {


new LinkedListNumbersGUI();
}
}

2 (Perform set operations on priority queues) Create two priority queues, {"George", "Jim",
"John", "Blake", "Kevin", "Michael"} and {"George", "Katie", "Kevin", "Michelle",
"Ryan"}, and find their union,
difference, and intersection.
Program:

import java.util.PriorityQueue;

public class
PriorityQueueSetOperationsCusto
m{
public static void main(String[]
args) {
// Create two priority queues
with custom elements
PriorityQueue<Person> queue1
= new PriorityQueue<>();
queue1.addAll(Set.of(
new Person("George", 1),
new Person("Jim", 2),
new Person("John", 3),

Enrolment no. : 220280107089


64

new Person("Blake", 4),


new Person("Kevin", 5),
new Person("Michael", 6)
));

PriorityQueue<Person> queue2
= new PriorityQueue<>();
queue2.addAll(Set.of(
new Person("George", 7),
new Person("Katie", 8),
new Person("Kevin", 9),
new Person("Michelle", 10),
new Person("Ryan", 11)
));

// Union (elements in either


queue1 or queue2)
PriorityQueue<Person> union =
new PriorityQueue<>();
while (!queue1.isEmpty()) {
union.add(queue1.poll());
}
while (!queue2.isEmpty()) {
if
(!union.contains(queue2.peek()))
{
union.add(queue2.poll());
}
}
System.out.println("Union: " +
union);

// Difference (elements in
queue1 but not in queue2)
PriorityQueue<Person>
difference = new
PriorityQueue<>();
while (!queue1.isEmpty()) {
Person person = queue1.poll();
if (!queue2.contains(person)) {
difference.add(person);
}
}

Enrolment no. : 220280107089


65

System.out.println("Difference
(queue1 - queue2): " +
difference);
// Intersection (elements in both
queue1 and queue2)
PriorityQueue<Person>
intersection = new
PriorityQueue<>();
while (!queue1.isEmpty()) {
Person person = queue1.poll();
if (queue2.contains(person)) {
intersection.add(person);
queue2.remove(person); //
Avoid duplicates in intersection
}
}
System.out.println("Intersection:
" + intersection);
}

static class Person implements


Comparable<Person> {
String name;
int id;

public Person(String name, int


id) {
this.name = name;
this.id = id;
}
@Override
public int compareTo(Person
other) {
int nameCompare =
name.compareTo(other.name);
return nameCompare == 0 ?
Integer.compare(id, other.id) :
nameCompare;
}
@Override
public String toString() {
return name + " (" + id + ")";
}
} }
Output:

Enrolment no. : 220280107089


66

Union: [Blake (4), George (1), Jim


(2), John (3), Katie (8), Kevin (5),
Michael (6), Michelle (10), Ryan
(11)]
Difference (queue1 - queue2):
[Blake (4), Jim (2), John (3),
Michael (6)]
Intersection: [George (7), Kevin
(9)]

3 (Guess the capitals using maps) Store pairs of 10 states and its capital in a map. Your program should
prompt the user to enter a state and should display the capital for the state
Program:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class GuessCapitals {


public static void main(String[] args) {
// Create a HashMap to store state-capital pairs
Map<String, String> statesAndCapitals = new HashMap<>();
statesAndCapitals.put("Alabama", "Montgomery");
statesAndCapitals.put("Alaska", "Juneau");
statesAndCapitals.put("Arizona", "Phoenix");
statesAndCapitals.put("Arkansas", "Little Rock");
statesAndCapitals.put("California", "Sacramento");
statesAndCapitals.put("Colorado", "Denver");
statesAndCapitals.put("Connecticut", "Hartford");
statesAndCapitals.put("Delaware", "Dover");
statesAndCapitals.put("Florida", "Tallahassee");
statesAndCapitals.put("Georgia", "Atlanta");

Scanner scanner = new Scanner(System.in);

Enrolment no. : 220280107089


67

// Main loop for guessing capitals


while (true) {
System.out.print("Enter a state (or 'quit' to exit): ");
String state = scanner.nextLine().trim();

if (state.equalsIgnoreCase("quit")) {
break;
}

String capital = statesAndCapitals.get(state);


if (capital != null) {
System.out.println("The capital of " + state + " is " + capital + ".");
} else {
System.out.println("Invalid state. Please try again.");
}
}

scanner.close();
}
}
Output:

Enrolment no. : 220280107089


68

Practical 11 : To learn JAVA FX UI Controls.

1 (Color and font) Write a program that displays five texts vertically, as shown in Figure. Set a random
color and opacity for each text and set the font of each text to Times Roman, bold, italic, and 22 pixels

Program:

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;

public class FiveColoredText extends JPanel {

private static final String[] TEXTS = {"AutoSave O", "Laboratory Planning DOP-1314...",
"Search", "Sahil Parmar", "Practical 11: To learn JAVA FX UI Controls."};

public FiveColoredText() {
super();
setPreferredSize(new Dimension(400, 150)); // Set the preferred size of the panel
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Random random = new Random();
Font font = new Font("Times Roman", Font.BOLD + Font.ITALIC, 22);
g.setFont(font);

int y = 0; // Starting y-coordinate for the first text


int gap = 30; // Gap between each text

for (String text : TEXTS) {


// Generate random color and opacity
float red = random.floatValue();
float green = random.floatValue();
float blue = random.floatValue();
float alpha = random.floatValue() / 2 + 0.5f; // Transparency between 0.5 (50% opaque) to
1.0 (fully opaque)
Color randomColor = new Color(red, green, blue, alpha);
g.setColor(randomColor);

Enrolment no. : 220280107089


69

// Draw the text with its color and position


FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(text);
int x = (getWidth() - textWidth) / 2; // Center the text horizontally
g.drawString(text, x, y + fm.getAscent());

y += fm.getHeight() + gap; // Move down to the next line


}
}

public static void main(String[] args) {


JFrame frame = new JFrame("Five Colored Texts");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FiveColoredText());
frame.pack();
frame.setLocationRelativeTo(null); // Center the frame on the screen
frame.setVisible(true);
}
}

2 (Display a bar chart) Write a program that uses a bar chart to display the percentages of the overall
grade represented by projects, quizzes, midterm exams, and the final exam, as shown in Figure
14.46b. Suppose that projects take 20 percent and are displayed in red, quizzes take 10 percent and
are displayed in blue, midterm exams take 30 percent and are displayed in green, and the final exam
takes 40 percent and is displayed in orange. Use the Rectangle class to display the bars. Interested
readers may explore the JavaFX BarChart class for further study.

Enrolment no. : 220280107089


70

Program:

import java.awt.*;

public class GradeBarChart {

public static void main(String[] args) {


// Percentages for each category
int projects = 20;
int quizzes = 10;
int midterms = 30;
int finalExam = 40;

// Total width and height of the chart


int chartWidth = 400;
int chartHeight = 200;

// Gap between bars


int barGap = 20;

// Color assignments (assuming fixed colors as in the image)


Color projectsColor = Color.RED;
Color quizzesColor = Color.BLUE;
Color midtermsColor = Color.GREEN;
Color finalExamColor = Color.ORANGE;

// Create a new frame


JFrame frame = new JFrame("Grade Percentages");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(chartWidth, chartHeight + 30); // Add some extra height for labels

// Create a panel to hold the chart


JPanel chartPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

// X-coordinate for the first bar


int x = 0;

// Draw bars for each category


g.setColor(projectsColor);
g.fillRect(x, chartHeight - projects * chartHeight / 100,
chartWidth / 5 - barGap / 2, projects * chartHeight / 100); // Project bar
x += chartWidth / 5 + barGap;

g.setColor(quizzesColor);

Enrolment no. : 220280107089


71

g.fillRect(x, chartHeight - quizzes * chartHeight / 100,


chartWidth / 5 - barGap / 2, quizzes * chartHeight / 100); // Quiz bar
x += chartWidth / 5 + barGap;

g.setColor(midtermsColor);
g.fillRect(x, chartHeight - midterms * chartHeight / 100,
chartWidth / 5 - barGap / 2, midterms * chartHeight / 100); // Midterm bar
x += chartWidth / 5 + barGap;

g.setColor(finalExamColor);
g.fillRect(x, chartHeight - finalExam * chartHeight / 100,
chartWidth / 5 - barGap / 2, finalExam * chartHeight / 100); // Final exam
bar

// Draw labels below the bars


g.setFont(new Font("Arial", Font.BOLD, 12));
g.setColor(Color.BLACK);
g.drawString("Projects (" + projects + "%)", 5, chartHeight + 15);
g.drawString("Quizzes (" + quizzes + "%)", chartWidth / 5 + barGap / 2,
chartHeight + 15);
g.drawString("Midterms (" + midterms + "%)", chartWidth / 5 * 2 + barGap,
chartHeight + 15);
g.drawString("Final Exam (" + finalExam + "%)", chartWidth / 5 * 3 + barGap /
2, chartHeight + 15);
}
};

frame.getContentPane().add(chartPanel);
frame.setVisible(true);
}
}

3 (Display a rectanguloid) Write a program that displays a rectanguloid, as shown in Figure 14.47a.
The cube should grow and shrink as the window grows or shrinks.

Enrolment no. : 220280107089


72

Program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ResizableRectanguloid extends JPanel {

public ResizableRectanguloid() {
super();
setPreferredSize(new Dimension(300, 200)); // Set initial preferred size
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();

// Calculate dimensions based on window size (assuming a 3:2 aspect ratio)


int rectWidth = Math.min(width, height * 3 / 2);
int rectHeight = Math.min(height, width * 2 / 3);
int x = (width - rectWidth) / 2;
int y = (height - rectHeight) / 2;

// Draw the rectanguloid (adjustments can be made for specific perspective)


g.drawRect(x, y, rectWidth, rectHeight);
}

public static void main(String[] args) {


JFrame frame = new JFrame("Resizable Rectanguloid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ResizableRectanguloid());
frame.pack();
frame.setLocationRelativeTo(null); // Center the frame on the screen
frame.setVisible(true);
}
}

Enrolment no. : 220280107089


73

Practical 12: To implement event handling and animation.

1 (Select a font) Write a program that can dynamically change the font of a text in a label displayed on a
stack pane. The text can be displayed in bold and italic at the same time. You can select the font name
or font size from combo boxes, as shown in Figure. The available font names can be obtained using
Font.getFamilies(). The combo box for the font size is initialized with numbers from 1 to 100.

Program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DynamicFontLabel extends JPanel {

private JLabel textLabel;


private JComboBox<String> fontNameComboBox;
private JComboBox<Integer> fontSizeComboBox;
private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;

public DynamicFontLabel() {
super();
setLayout(new FlowLayout());

textLabel = new JLabel("Sample Text");


textLabel.setFont(new Font("Times New Roman", Font.PLAIN, 16));

fontNameComboBox = new
JComboBox<>(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyName
s());
fontSizeComboBox = new JComboBox<>();
for (int i = 1; i <= 100; i++) {
fontSizeComboBox.addItem(i);
}
boldCheckBox = new JCheckBox("Bold");
italicCheckBox = new JCheckBox("Italic");

// Add action listeners to handle selections

Enrolment no. : 220280107089


74

fontNameComboBox.addActionListener(e -> updateFont());


fontSizeComboBox.addActionListener(e -> updateFont());
boldCheckBox.addActionListener(e -> updateFont());
italicCheckBox.addActionListener(e -> updateFont());

add(textLabel);
add(fontNameComboBox);
add(fontSizeComboBox);
add(boldCheckBox);
add(italicCheckBox);
}

private void updateFont() {


int fontStyle = Font.PLAIN;
if (boldCheckBox.isSelected()) {
fontStyle |= Font.BOLD;
}
if (italicCheckBox.isSelected()) {
fontStyle |= Font.ITALIC;
}
textLabel.setFont(new Font(fontNameComboBox.getSelectedItem().toString(), fontStyle,
fontSizeComboBox.getSelectedItem()));
}

public static void main(String[] args) {


JFrame frame = new JFrame("Dynamic Font Label");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DynamicFontLabel());
frame.pack();
frame.setLocationRelativeTo(null); // Center the frame on the screen
frame.setVisible(true);
}
}

2 (Control a moving text) Write a program that displays a moving text, as shown in Figure. The text moves
from left to right circularly. When it disappears in the right, it reappears from the left. The text freezes
when the mouse is pressed and moves again when the button is released.

Enrolment no. : 220280107089


75

Program:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MovingText extends JPanel implements MouseListener {

private static final String TEXT = "Programming is fun";


private int textX; // X-coordinate of the text
private int startX; // Starting X-coordinate for continuous movement
private final int textWidth; // Precalculated width of the text
private final Font font; // Font for the text
private boolean isMoving = true; // Flag to control movement

public MovingText() {
super();
addMouseListener(this);
font = new Font("Arial", Font.BOLD, 20);
textWidth = getFontMetrics(font).stringWidth(TEXT);
startX = getWidth(); // Start from the right edge initially
textX = startX;
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);

if (isMoving) {
// Move the text from right to left
textX -= 3; // Adjust the movement speed here
if (textX + textWidth < 0) {
textX = getWidth(); // Reappears from the right edge
}
}

g.drawString(TEXT, textX, getFontMetrics(font).getAscent());


}

@Override
public void mouseClicked(MouseEvent e) {
}

@Override
public void mousePressed(MouseEvent e) {
isMoving = false;

Enrolment no. : 220280107089


76

@Override
public void mouseReleased(MouseEvent e) {
isMoving = true;
}

@Override
public void mouseEntered(MouseEvent e) {
}

@Override
public void mouseExited(MouseEvent e) {
}

public static void main(String[] args) {


JFrame frame = new JFrame("Moving Text");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MovingText());
frame.setSize(400, 100); // Adjust the frame size as needed
frame.setLocationRelativeTo(null); // Center the frame on the screen
frame.setVisible(true);
}
}

3 (Create an image animator with audio) Create animation in Figure to meet the following requirements:
■ Allow the user to specify the animation speed in a text field.
■ Get the number of iamges and image’s file-name prefix from the user. For example, if the user enters
n for the number of images and L for the image prefix, then the files are L1.gif, L2.gif, and so on, to
Ln.gif. Assume that the images are stored in the image directory, a subdirectory of the program’s class
directory. The animation displays the images one after the other.
■ Allow the user to specify an audio file URL. The audio is played while the animation runs.

Enrolment no. : 220280107089


77

Program:

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.sound.sampled.*;
import javax.swing.*;

public class ImageAnimatorWithAudio extends JPanel implements ActionListener {

private static final String IMAGE_DIR = "images"; // Subdirectory for images (relative
to classpath)
private JTextField numImagesField;
private JTextField imagePrefixField;
private JTextField animationSpeedField;
private JTextField audioURLField;
private JButton startButton;
private JLabel statusLabel;
private Clip audioClip;

public ImageAnimatorWithAudio() {
super();
setLayout(new GridBagLayout());

JLabel numImagesLabel = new JLabel("Number of Images:");


numImagesField = new JTextField(10);
JLabel imagePrefixLabel = new JLabel("Image Prefix:");
imagePrefixField = new JTextField(10);
JLabel animationSpeedLabel = new JLabel("Animation Speed (ms):");
animationSpeedField = new JTextField(10);
JLabel audioURLLabel = new JLabel("Audio URL:");
audioURLField = new JTextField(20);
startButton = new JButton("Start");
startButton.addActionListener(this);
statusLabel = new JLabel(" ");

GridBagConstraints c = new GridBagConstraints();


c.fill = GridBagConstraints.HORIZONTAL;

// Add components to the panel with grid layout


c.gridx = 0;

Enrolment no. : 220280107089


78

c.gridy = 0;
add(numImagesLabel, c);
c.gridx = 1;
c.gridy = 0;
add(numImagesField, c);

c.gridx = 0;
c.gridy = 1;
add(imagePrefixLabel, c);
c.gridx = 1;
c.gridy = 1;
add(imagePrefixField, c);

c.gridx = 0;
c.gridy = 2;
add(animationSpeedLabel, c);
c.gridx = 1;
c.gridy = 2;
add(animationSpeedField, c);

c.gridx = 0;
c.gridy = 3;
add(audioURLLabel, c);
c.gridx = 1;
c.gridy = 3;
add(audioURLField, c);

c.gridx = 0;
c.gridy = 4;
c.gridwidth = 2;
add(startButton, c);

c.gridx = 0;
c.gridy = 5;
c.gridwidth = 2;
add(statusLabel, c);
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
try {
int numImages = Integer.parseInt(numImagesField.getText());

Enrolment no. : 220280107089


79

String imagePrefix = imagePrefixField.getText();


int animationSpeed = Integer.parseInt(animationSpeedField.getText());
String audioURL = audioURLField.getText();

// Load audio clip


audioClip = loadAudio(audioURL);

// Start animation in a separate thread


new Thread(() -> {
try {
runAnimation(numImages, imagePrefix, animationSpeed);
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
statusLabel.setText("Error: " + ex.getMessage());
}
}).start();
statusLabel.setText("Animation started...");
} catch (NumberFormatException ex) {
statusLabel.setText("Error: Invalid input format.");
}
}
}

private Clip loadAudio(String audioURL) throws IOException,


UnsupportedAudioFileException, LineUnavailableException {
URL url = new URL(audioURL);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
AudioFormat format = audioIn.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(audioIn);
return clip;
}

private void runAnimation(int numImages, String imagePrefix, int animationSpeed) throws


IOException, InterruptedException {
if (audioClip != null) {
audioClip.start(); // Start audio playback
}

for (int i = 1; i <= numImages; i++) {


String filename = IMAGE_DIR + File.separator + imagePrefix + i + ".gif"; // Build image
filename

Enrolment no. : 220280107089


80

BufferedImage image = ImageIO.read(new File(filename)); // Load image


// You can use the loaded image here for display (replace the following line with your
drawing logic)
statusLabel.setText("Showing image: " + i);
Thread.sleep(animationSpeed); // Sleep for specified duration
}

if (audioClip != null) {
audioClip.stop(); // Stop audio playback (optional)
}
}

Enrolment no. : 220280107089

You might also like