B. M. S.
COLLEGE OF ENGINEERING, BENGALURU
(Autonomous College under VTU, Approved by AICTE, Accredited by NAAC)
DEPARTMENT OF COMPUTER APPLICATIONS
Academic Year: 2025-26
LAB RECORD
of
JAVA PROGRAMMING
(MMC204)
Submitted by
Adith Kushal B.A (1BM25MC002)
Under the Guidance of
Dr. V PADMAPRIYA
Associate Professor
Department of Computer Applications
B. M. S. COLLEGE OF ENGINEERING, BENGALURU
(Autonomous College under VTU, Approved by AICTE, Accredited by NAAC)
DEPARTMENT OF COMPUTER APPLICATIONS
Certificate of Practical Work Completion
This is to certify that Adith Kushal B.A (1BM25MC002) has satisfactorily
completed the course of practical in “Java Programming – MMC204” Laboratory,
prescribed for the 2nd Semester MCA program at BMS College of Engineering,
during the AY 2025–2026.
Signature of batch in-charge Signature of HoD
Dr. V Padmapriya Dr. S Uma
Associate Professor Professor & HoD
Dept. of Computer Applications Dept. of Computer Applications
Examiner:
1.
2.
TABLE OF CONTENTS
Sl. No. Description Page No.
1. Write a program to manage books, members, and borrowing 1-4
transactions according to the Instructions.
Classes to Create:
• Book (fields: title, author, ISBN, isAvailable)
• Member (fields: name, memberId, borrowedBooks[])
• Library
• Stores list of Book and Member objects
Methods:
• borrowBook(String isbn, int memberId)
• returnBook(String isbn, int memberId)
• listAvailableBooks()
• listBorrowedBooks(int memberId)
Print the necessary values.
2. Develop a program for an organization that manages different 5-8
types of employees. There are general employees, managers,
and interns. Each type of employee has different ways of
calculating bonuses and benefits.
• Abstract Class: Employee, Fields: name, id, baseSalary
o Constructor: Initializes all fields.
o Abstract methods: double calculateBonus(), String
getDetails()
• Subclass: Manager
o Field: department, Bonus: 20% of base salary
o Overrides getDetails()
• Subclass: Intern
o Field: university, Bonus: Fixed: $500
o Overrides getDetails()
• Subclass: Developer
o Field: level (Junior, Mid, Senior), Bonus: Junior
(10%), Mid (15%), Senior
(25%) of base salary
o Overrides getDetails()
• Interface: Taxable
o Method: double calculateTax()
• All employees are taxable: Tax is 10% of baseSalary +
5% of bonus
• Main class: Company
Print details of each employee. Display total salary, bonuses
and taxes.
3. Create a class hierarchy where different animals make different 9-10
sounds. Use dynamic method dispatch to invoke the correct
sound at runtime via a base class reference.
4. Write a program using the Java package for the following 11-12
scenario.
Package: calculator
Classes:
Adder → int add (int a, int b)
Subtractor → int subtract (int a, int b)
In your main class (outside package):
Import both classes.
Use them to perform addition and subtraction.
5. a. Develop the interfaces extending other interfaces. 13-15
Instructions:
• Create interface Movable with void move ().
• Create interface Flyable that extends Movable and adds
void fly ().
• Implement Flyable in class Bird.
• In main class, use both Movable and Flyable references.
b. Develop an interface for transaction actions.
• Create interface Transaction with methods:
• void deposit (double amount)
• void withdraw (double amount)
• Implement it in class BankAccount.
• Add fields: accountNumber, balance.
• Demonstrate deposit and withdraw in main method.
6. Develop a program implementing try-catch block for the below 16-17
given scenario:
• Write a program that asks the user to input two integers.
• Try to divide the first number by the second.
• Use a try-catch block to handle:
o Arithmetic Exception if the user tries to divide by
zero.
o InputMismatch Exception if the user inputs non-
integer values.
7. Write a program to implement user defined exception for 18-19
invalid voting age input.
Create a custom exception InvalidVotingAge Exception that
extends Exception.
The exception should take a message indicating that the
user is not eligible for voting
due to age.
Create a Voter class with: A field age.
A method checkVotingEligibility() that throws
InvalidVotingAge Exception if
the age is under18.
In the main method: Create a Voter object and check if they are
eligible to vote.
8. Write a program using thread communication with wait() and 20-21
notify().
Create a Queue class with:
• A produce() method that simulates adding items to the
queue.
• A consume() method that simulates removing items
from the queue.
Use two threads:
• One thread produces items (prints "Produced: [item]").
• One thread consumes items (prints "Consumed:
[item]").
• Use wait() and notify() to synchronize the producer and
consumer threads.
9. Create an enum TrafficLight with constants: RED, YELLOW, 22-23
GREEN. Each constant should have a duration (in seconds).
Add a method getDuration() and display behavior based on the
current light.
10. Write a program to create a List<String> of [Link] the list 24
in: Alphabetical order, Reverse alphabetical order. Use lambda
expressions with [Link]() or [Link]().
11. Write a Java program using string handling 25-26
• A string input is taken and the number of vowels and
consonants is counted.
• Remove duplicate characters from a string while
maintaining the order of first occurrences. Example:
"programming" → "progamin"
• Check whether two strings are anagrams of each other.
Example: "listen" and "silent" → true
12. Write a java program to read two text files and merge their 27
contents into a third file.
Use BufferedReader for reading and BufferedWriter for
writing.
13. Write a program to implement a book reservation system where 28-29
users can reserve books in a queue.
• Use Queue<String> to maintain the list of users who
have reserved a book.
• When a book becomes available, process the next user
in the queue.
• Keep track of each user's position in the queue and
notify when their book is available.
14. Develop a simple ATM system with a graphical user interface 30-32
(GUI) using Swing. The user can check balance, withdraw
money, and deposit funds.
Process:
• Use JTextField to display balance and take user input
for amounts to withdraw or
deposit.
• Use JButton for actions (Withdraw, Deposit, Check
Balance).
• Validate inputs (e.g., check for sufficient funds before
withdrawal).
• Display a message with JOptionPane if the transaction
is successful or failed.
15. Develop a simple calculator that allows the user to select basic 33-35
operations (add, subtract) from a menu.
• Create a menu with options for Add, Subtract, and Exit.
• Use a JTextField to get two numbers from the user, and
perform the selected operation when the user selects an
option from the menu
Swing Components:
o JMenuBar, JMenu, JMenuItem for the menu.
o JTextField for input.
o JLabel for displaying the result.
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
1. Write a program to manage books, members, and borrowing transactions according
to the Instructions.
Classes to Create:
• Book (fields: title, author, ISBN, isAvailable)
• Member (fields: name, memberId, borrowedBooks[])
• Library
• Stores list of Book and Member objects
Methods:
• borrowBook(String isbn, int memberId)
• returnBook(String isbn, int memberId)
• listAvailableBooks()
• listBorrowedBooks(int memberId)
Print the necessary values.
Program:
import [Link].*;
class Book {
String title;
String author;
String ISBN;
boolean isAvailable;
Book(String title, String author, String ISBN) {
[Link] = title;
[Link] = author;
[Link] = ISBN;
[Link] = true;
}
}
class Member {
String name;
int memberId;
ArrayList<Book> borrowedBooks;
Member(String name, int memberId) {
[Link] = name;
[Link] = memberId;
borrowedBooks = new ArrayList<>();
}
}
Department of Computer Applications, BMSCE 1
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
class Library {
ArrayList<Book> books = new ArrayList<>();
ArrayList<Member> members = new ArrayList<>();
void addBook(Book book) {
[Link](book);
}
void addMember(Member member) {
[Link](member);
}
void borrowBook(String isbn, int memberId) {
Book book = null;
Member member = null;
for (Book b : books) {
if ([Link](isbn)) {
book = b;
break;
}
}
for (Member m : members) {
if ([Link] == memberId) {
member = m;
break;
}
}
if (book != null && member != null && [Link]) {
[Link] = false;
[Link](book);
[Link]([Link] + " borrowed " + [Link]);
} else {
[Link]("Book cannot be borrowed");
}
}
void returnBook(String isbn, int memberId) {
for (Member m : members) {
if ([Link] == memberId) {
Iterator<Book> it = [Link]();
while ([Link]()) {
Book b = [Link]();
if ([Link](isbn)) {
Department of Computer Applications, BMSCE 2
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
[Link] = true;
[Link]();
[Link]([Link] + " returned " + [Link]);
return;
}
}
}
}
[Link]("Book not found");
}
void listAvailableBooks() {
[Link]("Available Books:");
for (Book b : books) {
if ([Link]) {
[Link]([Link] + " - " + [Link]);
}
}
}
void listBorrowedBooks(int memberId) {
for (Member m : members) {
if ([Link] == memberId) {
[Link]("Borrowed Books by " + [Link] + ":");
for (Book b : [Link]) {
[Link]([Link]);
}
return;
}
}
}
}
public class Main {
public static void main(String[] args) {
Library library = new Library();
[Link](new Book("Java Programming", "James Gosling", "101"));
[Link](new Book("Python Basics", "Guido van Rossum", "102"));
[Link](new Member("Alice", 1));
[Link](new Member("Bob", 2));
[Link]("101", 1);
[Link]();
[Link](1);
Department of Computer Applications, BMSCE 3
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
[Link]("101", 1);
[Link]();
}
}
Output:
Department of Computer Applications, BMSCE 4
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
2. Develop a program for an organization that manages different types of employees.
There are general employees, managers, and interns. Each type of employee has
different ways of calculating bonuses and benefits.
Abstract Class: Employee
o Fields: name, id, baseSalary
o Constructor: Initializes all fields
o Abstract methods:
double calculateBonus()
String getDetails()
Subclass: Manager
o Field: department
o Bonus: 20% of base salary
o Overrides getDetails()
Subclass: Intern
o Field: university
o Bonus: Fixed $500
o Overrides getDetails()
Subclass: Developer
o Field: level (Junior, Mid, Senior)
o Bonus:
Junior: 10% of base salary
Mid: 15% of base salary
Senior: 25% of base salary
o Overrides getDetails()
Interface: Taxable
o Method: double calculateTax()
All employees are taxable:
o Tax = 10% of baseSalary + 5% of bonus
Main Class: Company
Print details of each employee. Display total salary, bonuses, and taxes.
Program:
interface Taxable {
double calculateTax();
}
abstract class Employee implements Taxable {
String name;
int id;
double baseSalary;
Employee(String name, int id, double baseSalary) {
[Link] = name;
Department of Computer Applications, BMSCE 5
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
[Link] = id;
[Link] = baseSalary;
}
abstract double calculateBonus();
abstract String getDetails();
public double calculateTax() {
return (0.10 * baseSalary) + (0.05 * calculateBonus());
}
double totalSalary() {
return baseSalary + calculateBonus();
}
}
class Manager extends Employee {
String department;
Manager(String name, int id, double baseSalary, String department) {
super(name, id, baseSalary);
[Link] = department;
}
double calculateBonus() {
return 0.20 * baseSalary;
}
String getDetails() {
return "Manager: " + name + ", ID: " + id + ", Department: " + department;
}
}
class Intern extends Employee {
String university;
Intern(String name, int id, double baseSalary, String university) {
super(name, id, baseSalary);
[Link] = university;
}
double calculateBonus() {
return 500;
}
String getDetails() {
return "Intern: " + name + ", ID: " + id + ", University: " + university;
}
}
Department of Computer Applications, BMSCE 6
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
class Developer extends Employee {
String level;
Developer(String name, int id, double baseSalary, String level) {
super(name, id, baseSalary);
[Link] = level;
}
double calculateBonus() {
if ([Link]("Junior"))
return 0.10 * baseSalary;
else if ([Link]("Mid"))
return 0.15 * baseSalary;
else
return 0.25 * baseSalary;
}
String getDetails() {
return "Developer: " + name + ", ID: " + id + ", Level: " + level;
}
}
public class Company {
public static void main(String[] args) {
Employee[] employees = {
new Manager("Alice", 101, 5000, "HR"),
new Intern("Bob", 102, 2000, "MIT"),
new Developer("Charlie", 103, 4000, "Senior")
};
for (Employee e : employees) {
[Link]([Link]());
[Link]("Base Salary: $" + [Link]);
[Link]("Bonus: $" + [Link]());
[Link]("Tax: $" + [Link]());
[Link]("Total Salary: $" + [Link]());
[Link]();
}
}
}
Department of Computer Applications, BMSCE 7
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
Output:
Department of Computer Applications, BMSCE 8
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
3. Create a class hierarchy where different animals make different sounds. Use dynamic
method dispatch to invoke the correct sound at runtime via a base class reference.
Program:
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
void makeSound() {
[Link]("Cat meows");
}
}
class Cow extends Animal {
void makeSound() {
[Link]("Cow moos");
}
}
public class Main {
public static void main(String[] args) {
Animal a;
a = new Dog();
[Link]();
a = new Cat();
[Link]();
a = new Cow();
[Link]();
}
}
Department of Computer Applications, BMSCE 9
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
Output:
Department of Computer Applications, BMSCE 10
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
4 .Write a program using the Java package for the following scenario.
Package : calculator
Classes:
Adder → int add(int a, int b)
Subtractor → int subtract(int a, int b)
In your main class (outside package):
Import both classes.
Use them to perform addition and subtraction.
Program:
[Link]
package calculator;
public class Adder {
public int add(int a, int b) {
return a + b;
}
}
[Link]
package calculator;
public class Subtractor {
public int subtract(int a, int b) {
return a - b;
}
}
[Link]
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Adder adder = new Adder();
Subtractor subtractor = new Subtractor();
int sum = [Link](20, 10);
int difference = [Link](20, 10);
[Link]("Addition = " + sum);
[Link]("Subtraction = " + difference);
Department of Computer Applications, BMSCE 11
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
}
}
Output:
5.
Department of Computer Applications, BMSCE 12
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
5. a) Develop the interfaces extending other interfaces.
Instructions:
Create interface Movable with void move().
Create interface Flyable that extends Movable and adds void fly().
Implement Flyable in class Bird.
In main class, use both Movable and Flyable references.
Program:
interface Movable {
void move();
}
interface Flyable extends Movable {
void fly();
}
class Bird implements Flyable {
public void move() {
[Link]("Bird is moving");
}
public void fly() {
[Link]("Bird is flying");
}
}
public class Main {
public static void main(String[] args) {
Movable m = new Bird();
[Link]();
Flyable f = new Bird();
[Link]();
[Link]();
}
}
Output:
Department of Computer Applications, BMSCE 13
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
b) Develop an interface for transaction actions.
Create interface Transaction with methods:
o void deposit(double amount)
o void withdraw(double amount)
Implement it in class BankAccount.
Add fields: accountNumber, balance.
Demonstrate deposit and withdraw in main method.
Program:
interface Transaction {
void deposit(double amount);
void withdraw(double amount);
}
class BankAccount implements Transaction {
String accountNumber;
double balance;
BankAccount(String accountNumber, double balance) {
[Link] = accountNumber;
[Link] = balance;
}
public void deposit(double amount) {
balance += amount;
[Link]("Deposited: " + amount);
[Link]("Balance: " + balance);
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount);
[Link]("Balance: " + balance);
} else {
[Link]("Insufficient Balance");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount("ACC101", 5000);
[Link](1000);
[Link](2000);
}
}
Department of Computer Applications, BMSCE 14
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
Output:
Department of Computer Applications, BMSCE 15
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
6. Develop a program implementing try-catch block for the below given scenario.
Write a program that asks the user to input two integers.
Try to divide the first number by the second.
Use a try-catch block to handle:
ArithmeticException if the user tries to divide by zero.
InputMismatchException if the user inputs non-integer values.
Program:
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter first integer: ");
int a = [Link]();
[Link]("Enter second integer: ");
int b = [Link]();
int result = a / b;
[Link]("Result = " + result);
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero.");
} catch (InputMismatchException e) {
[Link]("Error: Please enter only integer values.");
}
[Link]();
}
}
Output 1:
Department of Computer Applications, BMSCE 16
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
Output 2:
Output 3:
Department of Computer Applications, BMSCE 17
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
7. Write a program to implement a user-defined exception for invalid voting age input.
Create a custom exception InvalidVotingAgeException that extends Exception.
The exception should take a message indicating that the user is not eligible for voting
due to age.
Create a Voter class with:
o A field age.
o A method checkVotingEligibility() that throws
InvalidVotingAgeException if the age is under 18.
In the main method:
o Create a Voter object and check if they are eligible to vote.
Program:
class InvalidVotingAgeException extends Exception {
InvalidVotingAgeException(String message) {
super(message);
}
}
class Voter {
int age;
Voter(int age) {
[Link] = age;
}
void checkVotingEligibility() throws InvalidVotingAgeException {
if (age < 18) {
throw new InvalidVotingAgeException("Not eligible for voting. Age must be 18 or
above.");
}
[Link]("Eligible for voting.");
}
}
public class Main {
public static void main(String[] args) {
Voter voter = new Voter(16);.
try {
[Link]();
} catch (InvalidVotingAgeException e) {
[Link]([Link]());
}
}
}
Department of Computer Applications, BMSCE 18
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
Output :
Department of Computer Applications, BMSCE 19
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
8. Write a program using thread communication with wait() and notify().
Create a Queue class with:
A produce() method that simulates adding items to the queue.
A consume() method that simulates removing items from the queue.
Use two threads:
One thread produces items (prints "Produced: [item]").
One thread consumes items (prints "Consumed: [item]").
Use wait() and notify() to synchronize the producer and consumer threads.
Program:
import [Link];
class Queue {
int item;
boolean available = false;
synchronized void produce(int item) {
try {
while (available) {
wait();
}
[Link] = item;
available = true;
[Link]("Produced: " + item);
notify();
} catch (InterruptedException e) {
[Link]([Link]());
}
}
synchronized void consume() {
try {
while (!available) {
wait();
}
[Link]("Consumed: " + item);
available = false;
notify();
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}
public class P8_ProducerConsumer {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Queue q = new Queue();
Department of Computer Applications, BMSCE 20
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
[Link]("Enter item: ");
int n = [Link]();
Thread producer = new Thread(() -> {
[Link](n);
});
Thread consumer = new Thread(() -> {
[Link]();
});
[Link]();
[Link]();
[Link]();
}
}
Output:
Department of Computer Applications, BMSCE 21
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
9. Create an enum TrafficLight with constants: RED, YELLOW, GREEN.
Each constant should have a duration (in seconds).
Add a method getDuration() and display behavior based on the current light.
Program:
enum TrafficLight {
RED(30),
YELLOW(5),
GREEN(40);
private int duration;
TrafficLight(int duration) {
[Link] = duration;
}
public int getDuration() {
return duration;
}
public void display() {
[Link]([Link]() + " light - Duration: " + duration + " seconds");
if (this == RED) {
[Link]("Stop");
} else if (this == YELLOW) {
[Link]("Get Ready");
} else if (this == GREEN) {
[Link]("Go");
}
}
}
public class Main {
public static void main(String[] args) {
for (TrafficLight light : [Link]()) {
[Link]();
[Link]();
}
}
}
Department of Computer Applications, BMSCE 22
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
Output:
Department of Computer Applications, BMSCE 23
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
10. Write a program to create a List<String> of names. Sort the list in:
Alphabetical order
Reverse alphabetical order
Use lambda expressions with [Link]() or [Link]().
Program:
import [Link].*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
List<String> names = new ArrayList<>();
[Link]("Enter 3 names: ");
for (int i = 0; i < 3; i++) {
[Link]([Link]());
}
[Link]((a, b) -> [Link](b));
[Link]("Alphabetical: " + names);
[Link]((a, b) -> [Link](a));
[Link]("Reverse: " + names);
[Link]();
}
}
Output:
Department of Computer Applications, BMSCE 24
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
11. Write a Java program using string handling
A string input is taken and the number of vowels and consonants is counted.
Remove duplicate characters from a string while maintaining the order of first
occurrences. Example: "programming" → "progamin"
Check whether two strings are anagrams of each other. Example: "listen" and "silent" →
true
Program:
import [Link].*;
public class StringHandling {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]().toLowerCase();
int vowels = 0, consonants = 0;
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if ([Link](ch)) {
if ("aeiou".indexOf(ch) != -1)
vowels++;
else
consonants++;
}
}
[Link]("Vowels: " + vowels);
[Link]("Consonants: " + consonants);
String result = "";
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if ([Link](ch) == -1)
result += ch;
}
[Link]("String after removing duplicates: " + result);
[Link]("Enter first string: ");
String s1 = [Link]().toLowerCase().replaceAll("\\s+", "");
[Link]("Enter second string: ");
String s2 = [Link]().toLowerCase().replaceAll("\\s+", "");
Department of Computer Applications, BMSCE 25
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
char[] a1 = [Link]();
char[] a2 = [Link]();
[Link](a1);
[Link](a2);
[Link]("Anagram: " + [Link](a1, a2));
}
}
Output:
Department of Computer Applications, BMSCE 26
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
12. Write a Java program to read two text files and merge their contents into a third
file. Use BufferedReader for reading and BufferedWriter for writing.
Program:
import [Link].*;
public class FileMerge {
public static void main(String[] args) {
try {
BufferedReader br1 = new BufferedReader(new FileReader("[Link]"));
BufferedReader br2 = new BufferedReader(new FileReader("[Link]"));
BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"));
String line;
while ((line = [Link]()) != null) {
[Link](line);
[Link]();
}
while ((line = [Link]()) != null) {
[Link](line);
[Link]();
}
[Link]();
[Link]();
[Link]();
[Link]("Files merged successfully.");
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
Output:
Department of Computer Applications, BMSCE 27
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
13. Write a program to implement a book reservation system where users can reserve
books in a queue.
Use Queue<String> to maintain the list of users who have reserved a book.
When a book becomes available, process the next user in the queue.
Keep track of each user's position in the queue and notify when their book is
available.
Program:
import [Link].*;
public class BookReservation {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
[Link]("David");
[Link]("Reservation Queue:");
int position = 1;
for (String user : queue) {
[Link](user + " - Position " + position++);
}
[Link]("\nBook Available:");
while (![Link]()) {
String user = [Link]();
[Link]("Notification sent to " + user + ": Your book is available.");
}
}
}
Department of Computer Applications, BMSCE 28
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
Output:
Department of Computer Applications, BMSCE 29
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
14. Develop a simple ATM system with a graphical user interface (GUI) using Swing.
The user can check balance, withdraw money, and deposit funds.
Process:
Use JTextField to display balance and take user input for amounts to withdraw or
deposit.
Use JButton for actions (Withdraw, Deposit, Check Balance).
Validate inputs (e.g., check for sufficient funds before withdrawal).
Display a message with JOptionPane if the transaction is successful or failed.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
public class ATMSystem extends JFrame implements ActionListener {
JTextField balanceField, amountField;
JButton withdrawBtn, depositBtn, checkBtn;
double balance = 1000;
ATMSystem() {
setTitle("ATM System");
setSize(300, 200);
setLayout(new GridLayout(4, 2));
add(new JLabel("Balance"));
balanceField = new JTextField([Link](balance));
[Link](false);
add(balanceField);
add(new JLabel("Amount"));
amountField = new JTextField();
add(amountField);
withdrawBtn = new JButton("Withdraw");
depositBtn = new JButton("Deposit");
checkBtn = new JButton("Check Balance");
[Link](this);
[Link](this);
[Link](this);
add(withdrawBtn);
add(depositBtn);
add(checkBtn);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Department of Computer Applications, BMSCE 30
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
public void actionPerformed(ActionEvent e) {
try {
double amount = 0;
if ([Link]() != checkBtn) {
amount = [Link]([Link]());
}
if ([Link]() == depositBtn) {
balance += amount;
[Link](this, "Deposit Successful");
} else if ([Link]() == withdrawBtn) {
if (amount <= balance) {
balance -= amount;
[Link](this, "Withdrawal Successful");
} else {
[Link](this, "Insufficient Funds");
}
} else if ([Link]() == checkBtn) {
[Link](this, "Balance: " + balance);
}
[Link]([Link](balance));
} catch (Exception ex) {
[Link](this, "Invalid Input");
}
}
public static void main(String[] args) {
new ATMSystem();
}
}
Output1:
Department of Computer Applications, BMSCE 31
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
Output2:
Output3:
Department of Computer Applications, BMSCE 32
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
15. Develop a simple calculator that allows the user to select basic operations (Add,
Subtract) from a menu.
Create a menu with options for Add, Subtract, and Exit.
Use a JTextField to get two numbers from the user, and perform the selected
operation when the user selects an option from the menu.
Swing Components:
JMenuBar, JMenu, JMenuItem for the menu.
JTextField for input.
JLabel for displaying the result.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
public class CalculatorMenu extends JFrame implements ActionListener {
JTextField t1, t2;
JLabel result;
JMenuItem add, sub, exit;
CalculatorMenu() {
setTitle("Calculator");
setSize(300, 200);
setLayout(new GridLayout(3, 2));
t1 = new JTextField();
t2 = new JTextField();
result = new JLabel("Result");
add(new JLabel("Number 1"));
add(t1);
add(new JLabel("Number 2"));
add(t2);
add(result);
JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("Operations");
add = new JMenuItem("Add");
sub = new JMenuItem("Subtract");
exit = new JMenuItem("Exit");
[Link](this);
[Link](this);
[Link](this);
Department of Computer Applications, BMSCE 33
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
[Link](add);
[Link](sub);
[Link](exit);
[Link](menu);
setJMenuBar(mb);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if ([Link]() == exit) {
[Link](0);
}
try {
double a = [Link]([Link]());
double b = [Link]([Link]());
if ([Link]() == add)
[Link]("Result: " + (a + b));
else if ([Link]() == sub)
[Link]("Result: " + (a - b));
} catch (Exception ex) {
[Link]("Invalid Input");
}
}
public static void main(String[] args) {
new CalculatorMenu();
}
}
Output1:
Department of Computer Applications, BMSCE 34
MMC204: Java Programming Adith Kushal B.A (1BM25MC002)
Output2:
Department of Computer Applications, BMSCE 35