Oop Final
Oop Final
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
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:
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;
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.*;
{
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:
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;
// 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;
}
scanner.close();
}
}
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;
scanner.close();
}
Output:
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;
int vowelCount = 0;
int consonantCount = 0;
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
vowelCount++;
} else if (letter >= 'a' && letter <= 'z')
consonantCount++;
}
}
scanner.close();
}
}
Output:
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;
int prefixLength = 0;
while (prefixLength < str1.length() && prefixLength < str2.length() &&
str1.charAt(prefixLength) == str2.charAt(prefixLength)) {
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:
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;
int flag = 0;
while (flag != 2) {
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;
}
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;
// Eliminate duplicates
int[] result = eliminateDuplicates(numbers);
return result;
}
}
Output:
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;
// Iterate through the array to find the smallest element and its index
return smallestIndex;
}
}
Output:
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:
// 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);
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:
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;
private int id = 0;
private double balance = 0.0;
private double annualInterestRate = 0.0;
private Date dateCreated;
// Accessor methods
public int getId() {
return id;
}
// Mutator methods
public void setId(int id) {
this.id = id;
}
// Test program
public static void main(String[] args) {
Account account = new Account(1122, 20000.0);
account.setAnnualInterestRate(4.5);
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());
Output:
}
return (currentPrice - previousClosingPrice) / previousClosingPrice * 100;
}
// Test program
public static void main(String[] args) {
Stock stock = new Stock("ORCL", "Oracle Corporation");
stock.setPreviousClosingPrice(34.5);
stock.setCurrentPrice(34.35);
Output:
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;
@Override
public String toString() {
return "Person: " + name;
}
}
public Student(String name, String address, String phoneNumber, String emailAddress, String
classStatus) {
super(name, address, phoneNumber, emailAddress);
this.classStatus = classStatus;
}
@Override
public String toString() {
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();
}
}
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();
}
}
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();
}
}
System.out.println(person);
System.out.println(student);
System.out.println(employee);
System.out.println(faculty);
System.out.println(staff);
}
}
Output:
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();
}
@Override
public String toString() {
return "Account[id=" + id + ", balance=" + balance + ", dateCreated=" + dateCreated +
"]";
}
}
@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();
}
}
public CheckingAccount() {
super();
overdraftLimit = 0;
}
@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();
}
}
System.out.println(account);
System.out.println(savingsAccount);
System.out.println(checkingAccount);
}
}
Output:
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.
Write a program to implement all these classes and test program to test all the methods.
Program:
import java.util.Arrays;
class Person {
private String name;
private String address;
@Override
public String toString() {
return "Person [name=" + name + ", address=" + address + "]";
}
}
@Override
public String toString() {
return "Student " + super.toString();
}
}
@Override
public String toString() {
return "Teacher " + super.toString();
}
}
Output:
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.
Write two subclasses of Shape called Circle and Rectangle, as shown in the class
diagram.
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:
• 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.
Program:
public Shape() {
this.color = "green";
this.filled = true;
}
@Override
public String toString() {
String filledStatus = filled ? "filled" : "Not filled";
return "A Shape with color of " + color + " and " + filledStatus;
}
}
public Circle() {
super();
this.radius = 1.0;
}
@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 Rectangle() {
super();
this.width = 1.0;
this.length = 1.0;
}
@Override
public double getArea() {
return width * length;
}
@Override
public double getPerimeter() {
return 2 * (width + length);
}
@Override
public String toString() {
return "A Rectangle with width=" + width + " and length=" + length + ", which is a subclass of
" + super.toString();
}
}
@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();
}
}
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:
@Override
public String toString() {
return "A Shape";
}
}
@Override
public double getArea() {
return width * length;
}
@Override
public String toString() {
return "A Rectangle with width=" + width + " and length=" + length;
}
}
@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) {
Output:
Program:
interface Shape {
double getArea();
}
@Override
public double getArea() {
return width * length;
}
@Override
public String toString() {
return "A Rectangle with width=" + width + " and length=" + length;
}
}
@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);
Output:
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;
@Override
public String toString() {
return "My circle, radius is " + radius;
}
}
Output:
import java.util.Random;
Output:
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;
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();
Output:
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:
// Getters and Setters for side1, side2, and side3 (implement these)
1 (Extend Thread) Write a program to create a thread extending Thread class and demonstrate the use
of slip() method.
Program:
try {
// Main thread sleeps for 2 seconds
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
@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:
2 (Implement Runnable) Write a program to create a thread implementing Runnable interface and
demonstrate the use of join() method.
Program:
@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:
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:
Output:
Final sum: 10
Final sum: 6
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;
try {
// Create a Scanner to read from the input file
Scanner scanner = new Scanner(new File(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;
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;
writeRandomNumbers(fileName, numIntegers);
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)
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:
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;
}
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;
Output:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
if (index != -1) {
System.out.println("Element \"" + key + "\" found at index: " + index);
} else {
System.out.println("Element \"" + key + "\" not found in the list.");
}
}
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)
}
}
Output:
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 LinkedListNumbersGUI() {
super("Linked List Numbers");
numbers = new LinkedList<>();
addButton.addActionListener(this);
sortButton.addActionListener(this);
shuffleButton.addActionListener(this);
reverseButton.addActionListener(this);
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.");
}
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),
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)
));
// 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);
}
}
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);
}
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;
if (state.equalsIgnoreCase("quit")) {
break;
}
scanner.close();
}
}
Output:
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.*;
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);
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.
Program:
import java.awt.*;
g.setColor(quizzesColor);
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
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.
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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();
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 DynamicFontLabel() {
super();
setLayout(new FlowLayout());
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(textLabel);
add(fontNameComboBox);
add(fontSizeComboBox);
add(boldCheckBox);
add(italicCheckBox);
}
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.
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
isMoving = false;
@Override
public void mouseReleased(MouseEvent e) {
isMoving = true;
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
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.
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.*;
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());
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());
if (audioClip != null) {
audioClip.stop(); // Stop audio playback (optional)
}
}