Java Programming Lab Exercises 2024
Java Programming Lab Exercises 2024
Session: 2024-25
(CSE-423)
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!");
// Displaying results
[Link]("Integer value: " + a);
[Link]("Double value: " + b);
[Link]("Character value: " + c);
[Link]("Boolean value: " + d);
[Link]("String value: " + e);
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];
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];
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};
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}
};
// 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];
}
}
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;
}
[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;
}
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;
}
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
}
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;
}
// 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;
}
// Derived class
class Circle extends Shape {
private double radius;
// Constructor
public Circle(double radius) {
[Link] = radius;
}
// 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;
}
// Derived class
class Employee extends Person {
private String jobTitle;
private double salary;
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);
}
}
// 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
}
// Constructor
public MusicPlayer(String songTitle) {
[Link] = songTitle;
}
// Constructor
public VideoPlayer(String videoTitle) {
[Link] = videoTitle;
}
28
// Test play method for MusicPlayer
[Link]("Music Player:");
[Link]();
[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 :
Output :
Q 16. Write a program that uses classes from built-in packages like
[Link] and [Link] to perform operations.
Code :
import [Link];
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;
}
Q 18. Rewrite the multithreaded program from Q17 by implementing the Runnable
interface.
Code :
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;
}
37
[Link]("All threads have finished execution.");
}
}
Output :
class BankAccount {
private double balance;
private String accountNumber;
38
// Constructor
public BankAccount(String accountNumber, double initialBalance) {
[Link] = accountNumber;
[Link] = initialBalance;
}
// Constructor
public TransactionThread(BankAccount account, String threadName, double
amount, boolean isWithdrawal) {
super(threadName);
[Link] = account;
[Link] = amount;
[Link] = isWithdrawal;
}
Output :
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);
}
}
// Thread class
class CounterThread extends Thread {
private Counter counter;
private String threadName;
// Main class
public class SynchronizedCounterDemo {
public static void main(String[] args) {
Counter sharedCounter = new Counter();
[Link]();
[Link]();
[Link]();
// Shared resource
43
class Buffer {
private final Queue<Integer> queue = new LinkedList<>();
private final int capacity = 5;
[Link](value);
[Link]("Producer produced: " + value);
notifyAll(); // notify consumer(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;
}
// Main class
public class ProducerConsumerDemo {
public static void main(String[] args) {
Buffer sharedBuffer = new Buffer();
45
[Link]();
[Link]();
}
}
Output :
try {
// Input two numbers
[Link]("Enter numerator: ");
int numerator = [Link]();
// Attempt division
int result = numerator / denominator;
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];
try {
// User input for index
[Link]("Enter an array index (0 to 4): ");
int index = [Link]([Link]());
} 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.");
}
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];
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);
}
}
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];
Output :
Q 29. Create an AWT application with a Label, TextField, and Button using
FlowLayout.
57
Code :
import [Link].*;
import [Link].*;
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");
// Frame settings
setTitle("AWT FlowLayout Example");
setSize(300, 120);
setVisible(true);
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 BorderLayoutDemo() {
// Set BorderLayout for the Frame
setLayout(new BorderLayout());
// Frame settings
setTitle("BorderLayout Example");
setSize(400, 300);
setVisible(true);
public GridLayoutDemo() {
// Set GridLayout with 3 rows and 3 columns
setLayout(new GridLayout(3, 3));
// Frame settings
setTitle("GridLayout 3x3 Example");
setSize(300, 300);
setVisible(true);
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].*;
// Create a JPanel
JPanel panel = new JPanel();
Output :
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");
// JComboBox
String[] countries = { "USA", "India", "Germany", "Canada", "Australia" };
JComboBox<String> countryBox = new JComboBox<>(countries);
// JButton
JButton submitButton = new JButton("Submit");
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 MenuExample() {
// Set title and size
setTitle("Swing Menu Example");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Output :
public ButtonClickExample() {
// Set up the frame
setTitle("Swing Button Click Example");
setSize(300, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
70
Output :
71