0% found this document useful (0 votes)
15 views71 pages

Java Programming Lab Exercises 2024

This document outlines the Java Programming Lab assignments for Amity University Madhya Pradesh for the session 2024-25. It includes a series of programming tasks aimed at teaching various Java concepts such as data types, control structures, object-oriented programming, exception handling, and GUI development. Each task is accompanied by example code and expected outputs to guide students in their learning process.

Uploaded by

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

Java Programming Lab Exercises 2024

This document outlines the Java Programming Lab assignments for Amity University Madhya Pradesh for the session 2024-25. It includes a series of programming tasks aimed at teaching various Java concepts such as data types, control structures, object-oriented programming, exception handling, and GUI development. Each task is accompanied by example code and expected outputs to guide students in their learning process.

Uploaded by

meghnasinha457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

AMITY UNIVERSITY MADHYA PRADESH

Session: 2024-25

JAVA PROGRAMMING LAB

(CSE-423)

SUBMITTED TO- SUBMITTED BY -

Dr. Rajeev Goyal Abhay Singh Chauhan

A60205223185

[Link]. CSE

(2023-27 Batch)

Section ‘D’

1
INDEX
S No. List of Program Page Date Signature
No.
Write a Java program to print "My First Java
1 Program!" to the console and demonstrate the
use of different data types and arithmetic
operators.
Implement a program to check if a given
2 number is even or odd using an if-else
statement.
Write a Java program to calculate the factorial
3 of a number entered by the user using a for
loop.
4 Create a program to find the largest element in
a one-dimensional integer array.
5 Implement a Java program to add two matrices
(2D arrays) and display the result.
Design a Book class with attributes like title,
6 author, and price. Include a method to
displayBookDetails(). Create two Book objects
and call their methods.
Write a program to demonstrate method
7 overloading by creating methods to calculate
the sum of two integers, three integers, and two
doubles.
Create a Student class with multiple
8 constructors (default and parameterized) and
demonstrate constructor overloading.
Implement a Counter class where a static
9 variable keeps track of the number of objects
created from that class. Display the count using
a static method.
Write a program to illustrate single inheritance
10 by creating a Vehicle class and a Car class that
extends Vehicle.
Demonstrate method overriding by creating a
11 Shape class with a draw() method and a Circle
class that extends Shape and overrides the
draw() method.
Implement a program to show the usage of the
12 super keyword to call a parent class constructor
and method.
Design an abstract class Animal with an
13 abstract method makeSound(). Create concrete
classes Dog and Cat that extend Animal and
implement makeSound().
Define an interface called Playable with a
14 method play(). Create classes MusicPlayer and
VideoPlayer that implement this interface.
2
Create a custom Java package named
15 [Link] and include a class with a
utility method (e.g., isEven()). Demonstrate its
usage in another program.
Write a program that uses classes from built-in
16 packages like [Link] and
[Link] to perform operations.
Implement a multithreaded program by
17 extending the Thread class, where two threads
print numbers from 1 to 5 with a small delay.
Rewrite the multithreaded program from Q17
18 by implementing the Runnable interface.
Demonstrate thread priorities by creating
19 multiple threads with different priorities and
observing their execution behavior.
Write a program to show thread
20 synchronization using a synchronized method
when multiple threads access a shared resource
(e.g., a bank account).
Implement thread synchronization using a
21 synchronized block to protect a critical section
in a shared resource scenario.
Create a Producer-Consumer problem
22 demonstration using wait(), notify(), and
notifyAll() for inter-thread communication.
Write a program that uses try-catch blocks to
23 handle an ArithmeticException (e.g., division
by zero).
Implement a program demonstrating multiple
catch blocks to handle different types of
24 exceptions (e.g.,
ArrayIndexOutOfBoundsException,
NumberFormatException).
Show the usage of the finally block to ensure a
25 piece of code (e.g., resource cleanup) executes
regardless of whether an exception occurs.
Create a custom exception class called
26 InvalidInputException and use the throw
keyword to throw it when invalid user input is
detected.
Write a method that declares it throws a
27 specific exception, and show how the calling
method handles or re-throws it.
Design a simple AWT Frame and draw a
28 rectangle and an oval using the Graphics object
in its paint() method.
29 Create an AWT application with a Label,
TextField, and Button using FlowLayout.
Implement an AWT application demonstrating
30 the BorderLayout by adding components to its
NORTH, SOUTH, EAST, WEST, and
3
CENTER regions.
31 Design an AWT application using GridLayout
to arrange components in a 3x3 grid.
Create your first Swing application with a
32 JFrame and add a JPanel to it. Place a JLabel
displaying "Welcome to Swing!" on the panel.
Develop a Swing application showcasing
33 various components: JButton, JTextField,
JTextArea, JCheckBox, JRadioButton, and
JComboBox.
Implement a Swing application with a
34 JMenuBar, a JMenu (e.g., "File"), and
JMenuItems (e.g., "Open", "Save", "Exit").
Write a Swing program where clicking a
35 JButton (using ActionListener) changes the text
of a JLabel.

4
Q [Link] a Java program to print "My First Java Program!" to the console and
demonstrate the use of different data types and arithmetic operators.
Code :
public class FirstJavaProgram {
public static void main(String[] args) {
// Printing a message to the console
[Link]("My First Java Program!");

// Demonstrating different data types


int a = 10; // Integer type
double b = 5.5; // Double type
char c = 'J'; // Character type
boolean d = true; // Boolean type
String e = "Java"; // String type

// Performing arithmetic operations


int sum = a + 5; // Addition
double product = b * 2; // Multiplication
int division = a / 2; // Division
int remainder = a % 3; // Modulus
int difference = a - 3; // Subtraction

// Displaying results
[Link]("Integer value: " + a);
[Link]("Double value: " + b);
[Link]("Character value: " + c);
[Link]("Boolean value: " + d);
[Link]("String value: " + e);

[Link]("Sum: " + sum);


[Link]("Product: " + product);
[Link]("Division result: " + division);
[Link]("Remainder: " + remainder);
[Link]("Difference: " + difference);
}
}

5
Output :

6
Q 2. Implement a program to check if a given number is even or odd using an if-else
statement.
Code :
import [Link];

public class EvenOddChecker {


public static void main(String[] args) {
// Creating a Scanner object for user input
Scanner scanner = new Scanner([Link]);

// Prompting the user to enter a number


[Link]("Enter a number: ");
int number = [Link](); // Reading user input

// Checking if the number is even or odd using if-else


if (number % 2 == 0) {
[Link](number + " is an even number.");
} else {
[Link](number + " is an odd number.");
}

// Closing the scanner to prevent resource leaks


[Link]();
}
}

Output :

7
Q 3. Write a Java program to calculate the factorial of a number entered by the user
using a for loop
Code :
import [Link];

public class FactorialCalculator {


public static void main(String[] args) {
// Creating a Scanner object for user input
Scanner scanner = new Scanner([Link]);

// Prompting the user to enter a number


[Link]("Enter a number to find its factorial: ");
int number = [Link](); // Reading user input

// Initializing the factorial result


long factorial = 1;

// Calculating factorial using a for loop


for (int i = 1; i <= number; i++) {
factorial *= i;
}

// Displaying the result


[Link]("Factorial of " + number + " is: " + factorial);

// Closing the scanner to prevent resource leaks


[Link]();
}
}

Output :

8
Q 4. Create a program to find the largest element in a one-dimensional integer array.
Code :
public class MaxInArrayExample {
public static void main(String[] args) {
// Example array
int[] array = {12, 45, 7, 89, 23, 56, 90, 34};

// Finding the maximum element


int max = array[0]; // Assume first element is the largest
for (int i = 1; i < [Link]; i++) {
if (array[i] > max) {
max = array[i]; // Update max if a larger element is found
}
}

// Displaying the largest element


[Link]("The maximum element in the array is: " + max);
}
}

Output :

9
Q [Link] a Java program to add two matrices (2D arrays) and display the result.
Code :
public class MatrixAddition {
public static void main(String[] args) {
// Define two 2D arrays (matrices)
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int[][] matrix2 = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};

// Get the number of rows and columns


int rows = [Link];
int cols = matrix1[0].length;

// Create a result matrix to store the sum


int[][] sum = new int[rows][cols];

// Perform addition
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Display the result


[Link]("Sum of the two matrices:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
[Link](sum[i][j] + " ");
}
[Link]();
}
}

Output :
10
Q 6. Design a Book class with attributes like title, author, and price. Include a method
11
to displayBookDetails(). Create two Book objects and call their methods.
Code :
public class Book {
private String title;
private String author;
private double price;

// Constructor
public Book(String title, String author, double price) {
[Link] = title;
[Link] = author;
[Link] = price;
}

// Method to display book details


public void displayBookDetails() {
[Link]("Title: " + title);
[Link]("Author: " + author);
[Link]("Price: $" + price);
[Link]();
}

// Main method to test the Book class


public static void main(String[] args) {
// Create two Book objects
Book book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald", 9.99);
Book book2 = new Book("1984", "George Orwell", 12.50);

// Call displayBookDetails method for both books


[Link]("Book 1 Details:");
[Link]();

[Link]("Book 2 Details:");
[Link]();
}
}

Output :
12
Q 7. Write a program to demonstrate method overloading by creating methods to
13
calculate the sum of two integers, three integers, and two doubles.
Code :
public class SumCalculator {
// Method to sum two integers
public int sum(int a, int b) {
return a + b;
}

// Method to sum three integers


public int sum(int a, int b, int c) {
return a + b + c;
}

// Method to sum two doubles


public double sum(double a, double b) {
return a + b;
}

// Main method to test method overloading


public static void main(String[] args) {
SumCalculator calculator = new SumCalculator();

// Testing sum of two integers


[Link]("Sum of two integers (5, 10): " + [Link](5, 10));

// Testing sum of three integers


[Link]("Sum of three integers (5, 10, 15): " + [Link](5, 10,
15));

// Testing sum of two doubles


[Link]("Sum of two doubles (5.5, 10.75): " + [Link](5.5,
10.75));
}
}

Output :
14
Q 8. Create a Student class with multiple constructors (default and parameterized)
and demonstrate constructor overloading.
15
Code :
public class Student {
private String name;
private int id;
private double gpa;

// Default constructor
public Student() {
[Link] = "Unknown";
[Link] = 0;
[Link] = 0.0;
}

// Parameterized constructor
public Student(String name, int id, double gpa) {
[Link] = name;
[Link] = id;
[Link] = gpa;
}

// Method to display student details


public void displayDetails() {
[Link]("Name: " + name);
[Link]("ID: " + id);
[Link]("GPA: " + gpa);
[Link]();
}

// Main method to test constructor overloading


public static void main(String[] args) {
// Using default constructor
Student student1 = new Student();
[Link]("Student 1 Details (Default Constructor):");
[Link]();

// Using parameterized constructor


Student student2 = new Student("Alice Smith", 1001, 3.85);
[Link]("Student 2 Details (Parameterized Constructor):");
[Link]();
}
}
16
Output :

Q 9. Implement a Counter class where a static variable keeps track of the number of
objects created from that class. Display the count using a static method.
17
Code :
public class Counter {
// Static variable to track number of objects created
private static int objectCount = 0;

// Instance variable
private int id;

// Constructor
public Counter() {
[Link] = ++objectCount; // Increment count and assign to id
}

// Static method to display the count


public static void displayCount() {
[Link]("Total objects created: " + objectCount);
}

// Instance method to display individual object details


public void displayDetails() {
[Link]("Object ID: " + id);
}

// Main method to test the Counter class


public static void main(String[] args) {
// Create multiple Counter objects
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

// Display details of each object


[Link]("After creating 3 objects:");
[Link]();
[Link]();
[Link]();

// Display total count using static method


[Link]();

// Create one more object


Counter c4 = new Counter();
[Link]("\nAfter creating one more object:");
[Link]();
18
// Display updated count
[Link]();
}
}

Output :

Q 10. Write a program to illustrate single inheritance by creating a Vehicle class and
a Car class that extends Vehicle.
Code :
// Base class
class Vehicle {
19
protected String brand;
protected int year;

// Constructor
public Vehicle(String brand, int year) {
[Link] = brand;
[Link] = year;
}

// Method to display vehicle details


public void displayDetails() {
[Link]("Brand: " + brand);
[Link]("Year: " + year);
}

// Method to start the vehicle


public void start() {
[Link]("Vehicle is starting...");
}
}

// Derived class
class Car extends Vehicle {
private int numDoors;

// Constructor
public Car(String brand, int year, int numDoors) {
super(brand, year); // Call the parent class constructor
[Link] = numDoors;
}

// Override displayDetails to include Car-specific details


@Override
public void displayDetails() {
[Link](); // Call parent class method
[Link]("Number of Doors: " + numDoors);
}

// Method specific to Car


public void honk() {
[Link]("Car is honking!");
20
}
}

// Main class to test single inheritance


public class VehicleInheritance {
public static void main(String[] args) {
// Create a Vehicle object
Vehicle vehicle = new Vehicle("Toyota", 2020);
[Link]("Vehicle Details:");
[Link]();
[Link]();
[Link]();

// Create a Car object


Car car = new Car("Honda", 2022, 4);
[Link]("Car Details:");
[Link]();
[Link](); // Inherited from Vehicle
[Link](); // Specific to Car
}
}
Output :

Q 11. Demonstrate method overriding by creating a Shape class with a draw()


method and a Circle class that extends Shape and overrides the draw() method.
Code :
// Base class
class Shape {
21
// Method to draw a generic shape
public void draw() {
[Link]("Drawing a generic shape");
}
}

// Derived class
class Circle extends Shape {
private double radius;

// Constructor
public Circle(double radius) {
[Link] = radius;
}

// Override draw method


@Override
public void draw() {
[Link]("Drawing a circle with radius: " + radius);
}
}

// Main class to test method overriding


public class ShapeDemo {
public static void main(String[] args) {
// Create a Shape object
Shape shape = new Shape();
[Link]("Calling draw on Shape object:");
[Link]();
[Link]();

// Create a Circle object


Circle circle = new Circle(5.0);
[Link]("Calling draw on Circle object:");
[Link]();

// Demonstrate polymorphism
[Link]("\nUsing Shape reference for Circle object:");
Shape shapeReference = new Circle(3.0);
[Link]();
}
}
22
Output :

Q 12. Implement a program to show the usage of the super keyword to call a parent
class constructor and method.
Code :
// Parent class
class Person {
protected String name;
23
protected int age;

// Constructor
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}

// Method to display info


public void displayInfo() {
[Link]("Person: " + name + ", Age: " + age);
}
}

// Derived class
class Employee extends Person {
private String jobTitle;
private double salary;

// Constructor using super to call parent constructor


public Employee(String name, int age, String jobTitle, double salary) {
super(name, age); // Call parent class constructor
[Link] = jobTitle;
[Link] = salary;
}

// Override method using super to call parent method


@Override
public void displayInfo() {
[Link](); // Call parent class method
[Link]("Job Title: " + jobTitle + ", Salary: $" + salary);
}
}

// Main class to test super keyword usage


public class SuperKeywordDemo2 {
public static void main(String[] args) {
// Create an Employee object
Employee employee = new Employee("Sarah Johnson", 30, "Software
Engineer", 75000.0);

24
// Call displayInfo to demonstrate super usage
[Link]("Employee Information:");
[Link]();
}
}

Output :

Q 13. Design an abstract class Animal with an abstract method makeSound(). Create
concrete classes Dog and Cat that extend Animal and implement makeSound().
Code :
abstract class Animal {
protected String name;

25
// Constructor
public Animal(String name) {
[Link] = name;
}

// Abstract method
abstract void makeSound();

// Concrete method
public void displayName() {
[Link]("Animal Name: " + name);
}
}

// Concrete class Dog


class Dog extends Animal {
public Dog(String name) {
super(name);
}

// Implement abstract method


@Override
void makeSound() {
[Link](name + " says: Woof!");
}
}

// Concrete class Cat


class Cat extends Animal {
public Cat(String name) {
super(name);
}

// Implement abstract method


@Override
void makeSound() {
[Link](name + " says: Meow!");
}
}

// Main class to test the implementation


26
public class AbstractClass {
public static void main(String[] args) {
// Create Dog and Cat objects
Animal dog = new Dog("Buddy");
Animal cat = new Cat("Whiskers");

// Test Dog
[Link]("Dog Details:");
[Link]();
[Link]();
[Link]();

// Test Cat
[Link]("Cat Details:");
[Link]();
[Link]();
}
}

Output :

Q 14. Define an interface called Playable with a method play(). Create classes
MusicPlayer and VideoPlayer that implement this interface.
Code :
// Interface definition
interface Playable {
void play();
27
}

// MusicPlayer class implementing Playable


class MusicPlayer implements Playable {
private String songTitle;

// Constructor
public MusicPlayer(String songTitle) {
[Link] = songTitle;
}

// Implement play method


@Override
public void play() {
[Link]("Playing music: " + songTitle);
}
}

// VideoPlayer class implementing Playable


class VideoPlayer implements Playable {
private String videoTitle;

// Constructor
public VideoPlayer(String videoTitle) {
[Link] = videoTitle;
}

// Implement play method


@Override
public void play() {
[Link]("Playing video: " + videoTitle);
}
}

// Main class to test the interface implementation


public class PlayableDemo {
public static void main(String[] args) {
// Create MusicPlayer and VideoPlayer objects
Playable musicPlayer = new MusicPlayer("Moonlight Sonata");
Playable videoPlayer = new VideoPlayer("Introduction to Java");

28
// Test play method for MusicPlayer
[Link]("Music Player:");
[Link]();
[Link]();

// Test play method for VideoPlayer


[Link]("Video Player:");
[Link]();
}
}

Output :

Q 15. Create a custom Java package named [Link] and include a class with a
utility method (e.g., isEven()). Demonstrate its usage in another program.
Code :

//[Link] packge class


package [Link];
29
public class MathUtils {
// Utility method to check if a number is even
public static boolean isEven(int number) {
return number % 2 == 0;
}
}

//From another class where we use MathUtils isEven Function


import [Link];

public class UtilityDemo {


public static void main(String[] args) {
// Test the isEven method with different numbers
int num1 = 4;
int num2 = 7;
int num3 = 0;

[Link](num1 + " is even: " + [Link](num1));


[Link](num2 + " is even: " + [Link](num2));
[Link](num3 + " is even: " + [Link](num3));
}
}

Output :

Q 16. Write a program that uses classes from built-in packages like
[Link] and [Link] to perform operations.
Code :
import [Link];

public class MathOperations {


30
public static void main(String[] args) {
// Create an ArrayList to store numbers
ArrayList<Double> numbers = new ArrayList<>();

// Add some numbers to the ArrayList


[Link](16.0);
[Link](25.0);
[Link](9.0);
[Link](4.0);

// Display the original numbers


[Link]("Original numbers: " + numbers);

// Calculate and display square roots using [Link]


[Link]("\nSquare roots:");
for (Double num : numbers) {
double sqrt = [Link](num);
[Link]("Square root of " + num + " = " + sqrt);
}

// Calculate and store squares using [Link]


ArrayList<Double> squares = new ArrayList<>();
for (Double num : numbers) {
double square = [Link](num, 2);
[Link](square);
}
[Link]("\nSquares: " + squares);

// Find and display the maximum number using [Link]


double max = [Link](0);
for (int i = 1; i < [Link](); i++) {
max = [Link](max, [Link](i));
}
[Link]("\nMaximum number: " + max);
}
}

Output :

31
Q 17. Implement a multithreaded program by extending the Thread class, where two
threads print numbers from 1 to 5 with a small delay.
Code :
class NumberPrinterThread extends Thread {
private String threadName;

32
// Constructor
public NumberPrinterThread(String threadName) {
[Link] = threadName;
}

// Run method to define thread behavior


@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](threadName + " prints: " + i);
try {
// Add a 500ms delay between prints
[Link](500);
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
}
}
}
}

public class NumberPrinterThreadDemo {


public static void main(String[] args) {
// Create two thread instances
NumberPrinterThread thread1 = new NumberPrinterThread("Thread-1");
NumberPrinterThread thread2 = new NumberPrinterThread("Thread-2");

// Start both threads


[Link]();
[Link]();

// Wait for both threads to finish


try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}

[Link]("Both threads have finished execution.");


}
}
33
Output :

Q 18. Rewrite the multithreaded program from Q17 by implementing the Runnable
interface.
Code :

class NumberPrinterRunnable implements Runnable {


private String threadName;
34
// Constructor
public NumberPrinterRunnable(String threadName) {
[Link] = threadName;
}

// Run method to define thread behavior


@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](threadName + " prints: " + i);
try {
// Add a 500ms delay between prints
[Link](500);
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
}
}
}
}

public class NumberPrinterRunnableDemo {


public static void main(String[] args) {
// Create two Runnable instances
NumberPrinterRunnable runnable1 = new NumberPrinterRunnable("Thread-
1");
NumberPrinterRunnable runnable2 = new NumberPrinterRunnable("Thread-
2");

// Create Thread objects with Runnable instances


Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);

// Start both threads


[Link]();
[Link]();
[Link]("Both threads have finished execution.");
}
}

Output :
35
Q 19. Demonstrate thread priorities by creating multiple threads with different
priorities and observing their execution behavior.
Code :
class PriorityThread extends Thread {
private String threadName;

// Constructor
36
public PriorityThread(String threadName) {
[Link] = threadName;
}

// Run method to define thread behavior


@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](threadName + " (Priority: " + getPriority() + ") prints: " + i) ;
}
}
}

public class ThreadPriorityDemo {


public static void main(String[] args) {
// Create three threads with different priorities
PriorityThread lowPriorityThread = new PriorityThread("LowPriorityThread");
PriorityThread normalPriorityThread = new
PriorityThread("NormalPriorityThread");
PriorityThread highPriorityThread = new PriorityThread("HighPriorityThread");

// Set thread priorities


[Link](Thread.MIN_PRIORITY); // Priority 1
[Link](Thread.NORM_PRIORITY); // Priority 5
[Link](Thread.MAX_PRIORITY); // Priority 10

// Start all threads


[Link]("Starting threads...");
[Link]();
[Link]();
[Link]();

// Wait for all threads to finish


try {
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}

37
[Link]("All threads have finished execution.");
}
}

Output :

Q 20. Write a program to show thread synchronization using a synchronized method


when multiple threads access a shared resource (e.g., a bank account).
Code :

class BankAccount {
private double balance;
private String accountNumber;
38
// Constructor
public BankAccount(String accountNumber, double initialBalance) {
[Link] = accountNumber;
[Link] = initialBalance;
}

// Synchronized method for withdrawal


public synchronized void withdraw(double amount, String threadName) {
[Link](threadName + " attempting to withdraw $" + amount);
if (balance >= amount) {
try {
// Simulate processing time
[Link](100);
} catch (InterruptedException e) {
[Link](threadName + " interrupted during withdrawal.");
}
balance -= amount;
[Link](threadName + " withdrew $" + amount + ". New balance:
$" + balance);
} else {
[Link](threadName + ": Insufficient funds for withdrawal of $" +
amount + ". Current balance: $" + balance);
}
}

// Synchronized method for deposit


public synchronized void deposit(double amount, String threadName) {
[Link](threadName + " attempting to deposit $" + amount);
balance += amount;
[Link](threadName + " deposited $" + amount + ". New balance: $"
+ balance);
}

// Get current balance


public double getBalance() {
return balance;
}
}

class TransactionThread extends Thread {


39
private BankAccount account;
private double amount;
private boolean isWithdrawal;

// Constructor
public TransactionThread(BankAccount account, String threadName, double
amount, boolean isWithdrawal) {
super(threadName);
[Link] = account;
[Link] = amount;
[Link] = isWithdrawal;
}

// Run method to perform transaction


@Override
public void run() {
if (isWithdrawal) {
[Link](amount, getName());
} else {
[Link](amount, getName());
}
}
}

public class BankAccountDemo {


public static void main(String[] args) {
// Create a shared bank account
BankAccount account = new BankAccount("12345", 1000.0);
[Link]("Initial balance: $" + [Link]());

// Create multiple threads for transactions


TransactionThread thread1 = new TransactionThread(account, "Thread-1",
500.0, true); // Withdraw $500
TransactionThread thread2 = new TransactionThread(account, "Thread-2",
300.0, true); // Withdraw $300
TransactionThread thread3 = new TransactionThread(account, "Thread-3",
400.0, false); // Deposit $400
TransactionThread thread4 = new TransactionThread(account, "Thread-4",
700.0, true); // Withdraw $700

// Start all threads


40
[Link]();
[Link]();
[Link]();
[Link]();

// Wait for all threads to finish


try {
[Link]();
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}

[Link]("Final balance: $" + [Link]());


}
}

Output :

Q 21. Implement thread synchronization using a synchronized block to protect a


critical section in a shared resource scenario.
Code :
// Shared Resource: Counter
class Counter {
private int count = 0;

41
// Method to increment the counter (critical section)
public void increment(String threadName) {
synchronized (this) {
[Link](threadName + " is incrementing the counter...");
int temp = count;
try {
[Link](100); // simulate delay
} catch (InterruptedException e) {
[Link]();
}
count = temp + 1;
[Link](threadName + " updated count to: " + count);
}
}

public int getCount() {


return count;
}
}

// Thread class
class CounterThread extends Thread {
private Counter counter;
private String threadName;

public CounterThread(Counter counter, String name) {


[Link] = counter;
[Link] = name;
}

public void run() {


[Link](threadName);
}
}

// Main class
public class SynchronizedCounterDemo {
public static void main(String[] args) {
Counter sharedCounter = new Counter();

// Create multiple threads that access the shared counter


42
Thread t1 = new CounterThread(sharedCounter, "Thread A");
Thread t2 = new CounterThread(sharedCounter, "Thread B");
Thread t3 = new CounterThread(sharedCounter, "Thread C");

[Link]();
[Link]();
[Link]();

// Wait for all threads to finish


try {
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]();
}

[Link]("\nFinal counter value: " + [Link]());


}
}
Output :

Q 22. Create a Producer-Consumer problem demonstration using wait(), notify(), and


notifyAll() for inter-thread communication
Code :
import [Link];
import [Link];

// Shared resource
43
class Buffer {
private final Queue<Integer> queue = new LinkedList<>();
private final int capacity = 5;

// Producer adds items


public void produce(int value) throws InterruptedException {
synchronized (this) {
while ([Link]() == capacity) {
[Link]("Buffer full. Producer is waiting...");
wait(); // wait for space
}

[Link](value);
[Link]("Producer produced: " + value);
notifyAll(); // notify consumer(s)
}
}

// Consumer removes items


public void consume() throws InterruptedException {
synchronized (this) {
while ([Link]()) {
[Link]("Buffer empty. Consumer is waiting...");
wait(); // wait for item
}

int val = [Link]();


[Link]("Consumer consumed: " + val);
notifyAll(); // notify producer(s)
}
}
}

// Producer Thread
class Producer extends Thread {
private final Buffer buffer;

Producer(Buffer buffer) {
[Link] = buffer;
}

44
public void run() {
int value = 1;
try {
while (true) {
[Link](value++);
[Link](500);
}
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}

// Consumer Thread
class Consumer extends Thread {
private final Buffer buffer;

Consumer(Buffer buffer) {
[Link] = buffer;
}

public void run() {


try {
while (true) {
[Link]();
[Link](800);
}
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}

// Main class
public class ProducerConsumerDemo {
public static void main(String[] args) {
Buffer sharedBuffer = new Buffer();

Producer producer = new Producer(sharedBuffer);


Consumer consumer = new Consumer(sharedBuffer);

45
[Link]();
[Link]();
}
}

Output :

Q 23. Write a program that uses try-catch blocks to handle an ArithmeticException


(e.g., division by zero).
Code :
import [Link];

public class DivisionExample {


public static void main(String[] args) {
46
Scanner scanner = new Scanner([Link]);

try {
// Input two numbers
[Link]("Enter numerator: ");
int numerator = [Link]();

[Link]("Enter denominator: ");


int denominator = [Link]();

// Attempt division
int result = numerator / denominator;

[Link]("Result: " + result);


} catch (ArithmeticException e) {
// Handle division by zero
[Link]("Error: Cannot divide by zero!");
} finally {
[Link]();
[Link]("Program ended.");
}
}
}

Output :

47
Q 24. Implement a program demonstrating multiple catch blocks to handle different
types of exceptions (e.g., ArrayIndexOutOfBoundsException,
48
NumberFormatException).
Code :
import [Link];

public class MultipleCatchExample {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int[] numbers = {10, 20, 30, 40, 50};

try {
// User input for index
[Link]("Enter an array index (0 to 4): ");
int index = [Link]([Link]());

// Access array at given index


[Link]("Value at index " + index + " is: " + numbers[index]);

} catch (NumberFormatException e) {
[Link]("Error: Invalid number format. Please enter a valid
integer.");

} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Index out of bounds. Please enter an index
between 0 and 4.");

} catch (Exception e) {
[Link]("An unexpected error occurred: " + [Link]());

} finally {
[Link]();
[Link]("Program execution completed.");
}
}
}

Output :
49
Q 25. Show the usage of the finally block to ensure a piece of code (e.g., resource
cleanup) executes regardless of whether an exception occurs.
50
Code :
class DatabaseConnection {
public void connect() {
[Link]("Database connected.");
}

public void query(String sql) throws Exception {


[Link]("Executing query: " + sql);
if ([Link]("BAD QUERY")) {
throw new Exception("Query error!");
}
[Link]("Query executed successfully.");
}

public void close() {


[Link]("Database connection closed.");
}
}

public class FinallyDemo {


public static void main(String[] args) {
DatabaseConnection db = new DatabaseConnection();

try {
[Link]();
[Link]("SELECT * FROM users");
// Uncomment the next line to simulate an error
// [Link]("BAD QUERY");
} catch (Exception e) {
[Link]("Exception caught: " + [Link]());
} finally {
// This block always executes, closing the connection
[Link]();
}
}
}

Output :

51
Q 26. Create a custom exception class called InvalidInputException and use the
52
throw keyword to throw it when invalid user input is detected.
Code :
import [Link];

public class CustomExceptionDemo {


// Custom exception extending Exception (checked exception)
public static class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}
}

// Method to check user input and throw InvalidInputException if invalid


public static void validateInput(int number) throws InvalidInputException {
if (number < 0 || number > 100) {
throw new InvalidInputException("Input must be between 0 and 100.");
}
[Link]("Valid input: " + number);
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

[Link]("Enter a number between 0 and 100: ");


int userInput = [Link]();

try {
validateInput(userInput);
} catch (InvalidInputException e) {
[Link]("Caught exception: " + [Link]());
}

[Link]();
}
}

Output :
53
Q 27. Write a method that declares it throws a specific exception, and show how the
calling method handles or re-throws it.
54
Code :
// Custom exception for demonstration
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

public class ExceptionHandlingDemo {

// Method that declares it throws CustomException


public static void riskyMethod(boolean trigger) throws CustomException {
if (trigger) {
throw new CustomException("Something went wrong in riskyMethod!");
} else {
[Link]("riskyMethod executed successfully.");
}
}

// Calling method that handles the exception


public static void handleException() {
try {
riskyMethod(true); // This will throw the exception
} catch (CustomException e) {
[Link]("Caught exception in handleException(): " +
[Link]());
}
}

// Calling method that re-throws the exception


public static void rethrowException() throws CustomException {
riskyMethod(true); // Doesn't catch here, just declares throws
}

public static void main(String[] args) {


// Handle the exception
handleException();

// Re-throw the exception and catch it here


try {
rethrowException();
55
} catch (CustomException e) {
[Link]("Caught exception in main(): " + [Link]());
}
}
}

Output :

Q 28. Design a simple AWT Frame and draw a rectangle and an oval using the
Graphics object in its paint() method.
56
Code :
import [Link];
import [Link];
import [Link];

public class ShapeDrawingFrame extends Frame {


public ShapeDrawingFrame() {
setSize(400, 300); // Set frame size
setTitle("AWT Shape Drawing");
setVisible(true); // Make frame visible
}
@Override
public void paint(Graphics g) {
// Set color and draw a rectangle
[Link]([Link]);
[Link](50, 50, 150, 100); // x, y, width, height

// Set color and draw an oval


[Link]([Link]);
[Link](220, 50, 150, 100); // x, y, width, height
}

public static void main(String[] args) {


new ShapeDrawingFrame();
}
}

Output :

Q 29. Create an AWT application with a Label, TextField, and Button using
FlowLayout.
57
Code :
import [Link].*;
import [Link].*;

public class SimpleAWTApp extends Frame {

public SimpleAWTApp() {
// Set the layout manager to FlowLayout
setLayout(new FlowLayout());

// Create components
Label label = new Label("Enter Name:");
TextField textField = new TextField(20); // 20 columns wide
Button button = new Button("Submit");

// Add components to the Frame


add(label);
add(textField);
add(button);

// Frame settings
setTitle("AWT FlowLayout Example");
setSize(300, 120);
setVisible(true);

// Add window closing functionality


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
}

public static void main(String[] args) {


new SimpleAWTApp();
}
}

Output :

58
Q 30. Implement an AWT application demonstrating the BorderLayout by adding
components to its NORTH, SOUTH, EAST, WEST, and CENTER regions.
59
Code :
import [Link].*;
import [Link].*;

public class BorderLayoutDemo extends Frame {

public BorderLayoutDemo() {
// Set BorderLayout for the Frame
setLayout(new BorderLayout());

// Create buttons for each region


Button northButton = new Button("North");
Button southButton = new Button("South");
Button eastButton = new Button("East");
Button westButton = new Button("West");
Button centerButton = new Button("Center");

// Add buttons to the frame with BorderLayout regions


add(northButton, [Link]);
add(southButton, [Link]);
add(eastButton, [Link]);
add(westButton, [Link]);
add(centerButton, [Link]);

// Frame settings
setTitle("BorderLayout Example");
setSize(400, 300);
setVisible(true);

// Window closing handler


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
}

public static void main(String[] args) {


new BorderLayoutDemo();
}
}
60
Output :

Q 31. Design an AWT application using GridLayout to arrange components in a 3x3


grid.
61
Code :
import [Link].*;
import [Link].*;

public class GridLayoutDemo extends Frame {

public GridLayoutDemo() {
// Set GridLayout with 3 rows and 3 columns
setLayout(new GridLayout(3, 3));

// Add 9 buttons labeled 1 to 9


for (int i = 1; i <= 9; i++) {
add(new Button("Button " + i));
}

// Frame settings
setTitle("GridLayout 3x3 Example");
setSize(300, 300);
setVisible(true);

// Window closing event handler


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
}

public static void main(String[] args) {


new GridLayoutDemo();
}
}

Output :

62
Q 32. Create your first Swing application with a JFrame and add a JPanel to it. Place
a JLabel displaying "Welcome to Swing!" on the panel.
63
Code :
import [Link].*;

public class FirstSwingApp {

public static void main(String[] args) {


// Create the JFrame (main window)
JFrame frame = new JFrame("My First Swing Application");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](400, 200);

// Create a JPanel
JPanel panel = new JPanel();

// Create a JLabel with the message


JLabel label = new JLabel("Welcome to Swing!");

// Add the label to the panel


[Link](label);

// Add the panel to the frame


[Link](panel);

// Make the frame visible


[Link](true);
}
}

Output :

Q 33. Develop a Swing application showcasing various components: JButton,


JTextField, JTextArea, JCheckBox, JRadioButton, and JComboBox.
64
Code :
import [Link].*;
import [Link].*;
import [Link].*;

public class SwingComponentDemo extends JFrame {

public SwingComponentDemo() {
setTitle("Swing Components Demo");
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// JTextField
JTextField textField = new JTextField(20);

// JTextArea
JTextArea textArea = new JTextArea(5, 20);
[Link](true);
[Link](true);
JScrollPane scrollPane = new JScrollPane(textArea);

// JCheckBox
JCheckBox checkBox = new JCheckBox("Subscribe to newsletter");

// JRadioButtons with ButtonGroup


JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
[Link](male);
[Link](female);

// JComboBox
String[] countries = { "USA", "India", "Germany", "Canada", "Australia" };
JComboBox<String> countryBox = new JComboBox<>(countries);

// JButton
JButton submitButton = new JButton("Submit");

// JLabel to show output


JLabel resultLabel = new JLabel("");
65
// ActionListener for the button
[Link](e -> {
String name = [Link]();
String comments = [Link]();
String country = (String) [Link]();
boolean subscribed = [Link]();
String gender = [Link]() ? "Male" : [Link]() ? "Female" :
"Unspecified";

[Link]("<html>Name: " + name + "<br>Gender: " + gender +


"<br>Country: " + country + "<br>Subscribed: " + subscribed +
"<br>Comments: " + comments + "</html>");
});

// Add components to frame


add(new JLabel("Name:"));
add(textField);
add(new JLabel("Comments:"));
add(scrollPane);
add(new JLabel("Gender:"));
add(male);
add(female);
add(new JLabel("Country:"));
add(countryBox);
add(checkBox);
add(submitButton);
add(resultLabel);
}

public static void main(String[] args) {


[Link](() -> {
new SwingComponentDemo().setVisible(true);
});
}
}

Output :

66
Q 34. Implement a Swing application with a JMenuBar, a JMenu (e.g., "File"), and
JMenuItems (e.g., "Open", "Save", "Exit").
67
Code :
import [Link].*;
import [Link].*;

public class MenuExample extends JFrame {

public MenuExample() {
// Set title and size
setTitle("Swing Menu Example");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);

// Create a menu bar


JMenuBar menuBar = new JMenuBar();

// Create the "File" menu


JMenu fileMenu = new JMenu("File");

// Create menu items


JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem exitItem = new JMenuItem("Exit");

// Add action listener for "Exit"


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link](0); // Exit the application
}
});

// Add menu items to the "File" menu


[Link](openItem);
[Link](saveItem);
[Link](); // Add a separator line
[Link](exitItem);

// Add "File" menu to the menu bar


[Link](fileMenu);

// Set the menu bar for the frame


setJMenuBar(menuBar);
68
}

public static void main(String[] args) {


// Create and display the frame
[Link](() -> {
MenuExample frame = new MenuExample();
[Link](true);
});
}
}

Output :

Q 35. Write a Swing program where clicking a JButton (using ActionListener)


changes the text of a JLabel.
69
Code :
import [Link].*;
import [Link].*;
import [Link].*;

public class ButtonClickExample extends JFrame {

private JLabel label;


private JButton button;

public ButtonClickExample() {
// Set up the frame
setTitle("Swing Button Click Example");
setSize(300, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Create label and button


label = new JLabel("Click the button!");
button = new JButton("Click Me");

// Add ActionListener to the button


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
}
});

// Add components to the frame


add(label);
add(button);
}

public static void main(String[] args) {


[Link](() -> {
ButtonClickExample frame = new ButtonClickExample();
[Link](true);
});
}
}

70
Output :

71

You might also like