0% found this document useful (0 votes)
3 views31 pages

Java Lab Report

The document is a Java Programming Lab Report submitted by Tarun P at B.M.S. College of Engineering, detailing various programming tasks and projects related to Java. It includes a laboratory certificate confirming the completion of the Java Programming course and outlines multiple programming assignments covering topics such as object-oriented programming, exception handling, and GUI development. Each assignment includes specific classes, methods, and expected outputs, demonstrating practical applications of Java concepts.

Uploaded by

tarun.p03052004
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)
3 views31 pages

Java Lab Report

The document is a Java Programming Lab Report submitted by Tarun P at B.M.S. College of Engineering, detailing various programming tasks and projects related to Java. It includes a laboratory certificate confirming the completion of the Java Programming course and outlines multiple programming assignments covering topics such as object-oriented programming, exception handling, and GUI development. Each assignment includes specific classes, methods, and expected outputs, demonstrating practical applications of Java concepts.

Uploaded by

tarun.p03052004
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

B.M.S.

COLLEGE OF ENGINEERING
(Autonomous College under VTU, Approved by AICTE, Accredited by NAAC)
MASTER OF COMPUTER APPLICATIONS
(Accredited by NBA)

Java Programming Lab Report

Submitted
by
Tarun P
(1BM25MC100)

Under the Guidance of


K Girish

(Professor)
B.M.S. COLLEGE OF ENGINEERING
(Autonomous College under VTU, Approved by AICTE, Accredited by NAAC)
MASTER OF COMPUTER APPLICATIONS
(Accredited by NBA)

LABORATORY CERTIFICATE

This is to certify that Tarun P (1BM25MC100) has satisfactorily


completed the course of practical in “Java Programming –
MMC204” Laboratory prescribed by BMS College of Engineering
(Autonomous college under VTU) 2nd semester MCA course in this
college during the year 2025 - 2026.

Signature of Batch in charge Signature of HOD

K Girish Dr. S Uma

Examiner:

1.
2.
CONTENTS

SLNO PROGRAMS PAGE


NO

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
1-4
• 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 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
Constructor: Initializes all fields.
Abstract methods: double calculateBonus(), String getDetails()
• Subclass: Manager
Field: department, Bonus: 20% of base salary
Overrides getDetails()
• Subclass: Intern
Field: university, Bonus: Fixed: $500 4-7
Overrides getDetails()
• Subclass: Developer
Field: level (Junior, Mid, Senior), Bonus: Junior (10%), Mid (15%), Senior
(25%) of base salary
Overrides getDetails()
• Interface: Taxable
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 sounds. Use
dynamic method dispatch to invoke the correct sound at runtime via a base 7-8
class reference.
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) 9-10
• In your main class (outside package):
• Import both classes.
• Use them to perform addition and subtraction.

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.
b) Develop an interface for transaction actions.
10-12
• 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 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: 12-13
• Arithmetic Exception if the user tries to divide by zero.
• InputMismatch Exception if the user inputs non-integer values.

7 Write a program to implement user defined exception for 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. 13-14
Create a Voter class with: A field age.
o A method checkVotingEligibility() that throws InvalidVotingAge
Exception if the age is under18.
• In the main method:
o Create a Voter object and check if they are eligible to vote.

8 Write a program using thread communication with wait() and 14-15


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, GREEN. Each


constant should have a duration (in seconds). 15-16
Add a method getDuration() and display behavior based on the current light.

10 Write a program to create a List of [Link] the list in: Alphabetical order,
Reverse alphabetical order 17
Use lambda expressions with [Link]() or [Link]().

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 17-19
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 contents into a third 19-20
file. Use BufferedReader for reading and BufferedWriter for writing.

13 Write a program to implement a book reservation system where users can


reserve books in a queue.
• Use Queue to maintain the list of users who have reserved a book. • When 21
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 (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 22-24
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 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: 24-26
o JMenuBar, JMenu, JMenuItem for the menu.
o JTextField for input.
o JLabel for displaying the result.
MMC204: Java Programming

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.

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 = new ArrayList<>();

Member(String name, int memberId) {


[Link] = name;
[Link] = memberId;
}
}

class Library {

Department of Computer Applications, BMSCE Page |1


MMC204: Java Programming

ArrayList<Book> books = new ArrayList<>();


ArrayList<Member> members = new ArrayList<>();

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) {


Member member = null;

for (Member m : members) {


if ([Link] == memberId) {
member = m;
break;
}
}

if (member != null) {
for (Book b : [Link]) {
if ([Link](isbn)) {
[Link] = true;
[Link](b);
[Link]([Link] + " returned " + [Link]);

Department of Computer Applications, BMSCE Page |2


MMC204: Java Programming

return;
}
}
}

[Link]("Return failed");
}

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]);
}
}
}
}
}

public class lab1{


public static void main(String[] args) {
Library lib = new Library();

[Link](new Book("Java Programming", "James Gosling", "B101"));


[Link](new Book("Python Basics", "Guido", "B102"));

[Link](new Member("Arun", 1));


[Link](new Member("Priya", 2));

[Link]();

[Link]("B101", 1);

[Link]();

[Link](1);

Department of Computer Applications, BMSCE Page |3


MMC204: Java Programming

[Link]("B101", 1);

[Link]();
}
}

Output:

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, Fields: name, id, baseSalary

Constructor: Initializes all fields.


Abstract methods: double calculateBonus(), String getDetails()

• Subclass: Manager

Field: department, Bonus: 20% of base salary


Overrides getDetails()

• Subclass: Intern

Field: university, Bonus: Fixed: $500


Overrides getDetails()
• Subclass: Developer

Field: level (Junior, Mid, Senior), Bonus: Junior (10%), Mid (15%), Senior
(25%) of base salary
Overrides getDetails()
• Interface: Taxable

Method: double calculateTax()


• All employees are taxable: Tax is 10% of baseSalary + 5% of bonus

Department of Computer Applications, BMSCE Page |4


MMC204: Java Programming

• Main class: Company


➢ Print details of each employee. Display total salary, bonuses and taxes.

abstract class Employee {


String name;
int id;
double baseSalary;

Employee(String name, int id, double baseSalary) {


[Link] = name;
[Link] = id;
[Link] = baseSalary;
}

abstract double calculateBonus();


abstract String getDetails();
}

interface Taxable {
double calculateTax();
}

class Manager extends Employee implements Taxable {


String department;

Manager(String name, int id, double baseSalary, String department) {


super(name, id, baseSalary);
[Link] = department;
}

double calculateBonus() {
return baseSalary * 0.20;
}

public double calculateTax() {


return baseSalary * 0.10 + calculateBonus() * 0.05;
}

String getDetails() {
return "Manager: " + name + ", ID: " + id + ", Department: " + department;
}
}

class Intern extends Employee implements Taxable {


String university;

Department of Computer Applications, BMSCE Page |5


MMC204: Java Programming

Intern(String name, int id, double baseSalary, String university) {


super(name, id, baseSalary);
[Link] = university;
}

double calculateBonus() {
return 500;
}

public double calculateTax() {


return baseSalary * 0.10 + calculateBonus() * 0.05;
}

String getDetails() {
return "Intern: " + name + ", ID: " + id + ", University: " + university;
}
}

class Developer extends Employee implements Taxable {


String level;

Developer(String name, int id, double baseSalary, String level) {


super(name, id, baseSalary);
[Link] = level;
}

double calculateBonus() {
if ([Link]("Junior"))
return baseSalary * 0.10;
else if ([Link]("Mid"))
return baseSalary * 0.15;
else
return baseSalary * 0.25;
}

public double calculateTax() {


return baseSalary * 0.10 + calculateBonus() * 0.05;
}

String getDetails() {
return "Developer: " + name + ", ID: " + id + ", Level: " + level;
}
}

public class Company {


public static void main(String[] args) {

Department of Computer Applications, BMSCE Page |6


MMC204: Java Programming

Employee e1 = new Manager("Ravi", 101, 50000, "HR");


Employee e2 = new Intern("Anu", 102, 15000, "ABC University");
Employee e3 = new Developer("Karthik", 103, 40000, "Senior");

Employee[] employees = {e1, e2, e3};

for (Employee e : employees) {


double bonus = [Link]();
double totalSalary = [Link] + bonus;
double tax = ((Taxable) e).calculateTax();

[Link]([Link]());
[Link]("Base Salary: " + [Link]);
[Link]("Bonus: " + bonus);
[Link]("Total Salary: " + totalSalary);
[Link]("Tax: " + tax);
[Link]();
}
}
}

Output:

Department of Computer Applications, BMSCE Page |7


MMC204: Java Programming

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.

class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

class Cat extends Animal {


void sound() {
[Link]("Cat meows");
}
}

class Cow extends Animal {


void sound() {
[Link]("Cow moos");
}
}

public class lab3{


public static void main(String[] args) {
Animal a;

a = new Dog();
[Link]();

a = new Cat();
[Link]();

a = new Cow();
[Link]();
}
}
Output:

Department of Computer Applications, BMSCE Page |8


MMC204: Java Programming

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.

[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 lab4{


public static void main(String[] args) {
Adder a = new Adder();
Subtractor s = new Subtractor();

[Link]("Addition = " + [Link](20, 10));


[Link]("Subtraction = " + [Link](20, 10));
}
}

Department of Computer Applications, BMSCE Page |9


MMC204: Java Programming

Output:

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.

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 lab51{


public static void main(String[] args) {
Movable m = new Bird();
[Link]();

Flyable f = new Bird();


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

Department of Computer Applications, BMSCE P a g e | 10


MMC204: Java Programming

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.

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);
}

public void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
[Link]("Withdrawn: " + amount);
} else {
[Link]("Insufficient Balance");
}
}

void display() {
[Link]("Account Number: " + accountNumber);
[Link]("Balance: " + balance);
}
}

public class lab52{


public static void main(String[] args) {
BankAccount b = new BankAccount("ACC101", 5000);

Department of Computer Applications, BMSCE P a g e | 11


MMC204: Java Programming

[Link](2000);
[Link](1000);

[Link]();
}
}

Output:

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:
• Arithmetic Exception if the user tries to divide by zero.
• InputMismatch Exception if the user inputs non-integer values.

import [Link].*;

public class lab6{


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

try {
[Link]("Enter first number: ");
int a = [Link]();

[Link]("Enter second number: ");


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 integer values only");
}

Department of Computer Applications, BMSCE P a g e | 12


MMC204: Java Programming

[Link]();
}
}

Output:

7. Write a program to implement user defined exception for 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.
o A method checkVotingEligibility() that throws InvalidVotingAge Exception if
the age is under18.
• In the main method:
o Create a Voter object and check if they are eligible to vote.

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 lab7{


public static void main(String[] args) {
Voter v = new Voter(16);

try {

Department of Computer Applications, BMSCE P a g e | 13


MMC204: Java Programming

[Link]();
} catch (InvalidVotingAgeException e) {
[Link]([Link]());
}
}
}

Output:

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.

class Queue {
int item;
boolean available = false;

synchronized void produce(int item) {


try {
while (available)
wait();

[Link] = item;
[Link]("Produced: " + item);

available = true;
notify();
} catch (Exception e) {
}
}

synchronized void consume() {


try {
while (!available)
wait();

[Link]("Consumed: " + item);

available = false;
notify();
} catch (Exception e) {
}

Department of Computer Applications, BMSCE P a g e | 14


MMC204: Java Programming

}
}

public class lab8{


public static void main(String[] args) {
Queue q = new Queue();

Thread producer = new Thread(() -> {


for (int i = 1; i <= 5; i++) {
[Link](i);
}
});

Thread consumer = new Thread(() -> {


for (int i = 1; i <= 5; i++) {
[Link]();
}
});

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

Output:

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.

enum TrafficLight {
RED(30),
YELLOW(5),

Department of Computer Applications, BMSCE P a g e | 15


MMC204: Java Programming

GREEN(45);

int duration;

TrafficLight(int duration) {
[Link] = duration;
}

int getDuration() {
return duration;
}

void showBehavior() {
switch (this) {
case RED:
[Link]("STOP");
break;
case YELLOW:
[Link]("READY");
break;
case GREEN:
[Link]("GO");
break;
}
[Link]("Duration: " + duration + " seconds");
}
}

public class lab9{


public static void main(String[] args) {
TrafficLight t1 = [Link];
TrafficLight t2 = [Link];
TrafficLight t3 = [Link];

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

Output:

Department of Computer Applications, BMSCE P a g e | 16


MMC204: Java Programming

10. Write a program to create a List<String> of [Link] the list in: Alphabetical order,
Reverse
alphabetical order
Use lambda expressions with [Link]() or [Link]().

import [Link].*;

public class lab10{


public static void main(String[] args) {
List<String> names = new ArrayList<>();

[Link]("Arun");
[Link]("Zara");
[Link]("Kiran");
[Link]("Meena");
[Link]("Bala");

[Link]("Original List:");
[Link](names);

[Link](names, (a, b) -> [Link](b));


[Link]("Ascending Order:");
[Link](names);

[Link](names, (a, b) -> [Link](a));


[Link]("Descending Order:");
[Link](names);
}
}

Output:

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

import [Link].*;

public class Main {

Department of Computer Applications, BMSCE P a g e | 17


MMC204: Java Programming

static boolean isVowel(char c) {


return "aeiouAEIOU".indexOf(c) != -1;
}

static void countVowelsConsonants(String s) {


int vowels = 0, consonants = 0;

for (char c : [Link]()) {


if ([Link](c)) {
if (isVowel(c))
vowels++;
else
consonants++;
}
}

[Link]("Vowels: " + vowels);


[Link]("Consonants: " + consonants);
}

static String removeDuplicates(String s) {


String result = "";

for (char c : [Link]()) {


if ([Link](c) == -1) {
result += c;
}
}
return result;
}

static boolean isAnagram(String s1, String s2) {


s1 = [Link]("\\s", "").toLowerCase();
s2 = [Link]("\\s", "").toLowerCase();

if ([Link]() != [Link]())
return false;

char[] a = [Link]();
char[] b = [Link]();

[Link](a);
[Link](b);

return [Link](a, b);


}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter a string: ");


String str = [Link]();

Department of Computer Applications, BMSCE P a g e | 18


MMC204: Java Programming

countVowelsConsonants(str);

[Link]("String after removing duplicates: " + removeDuplicates(str));

[Link]("Enter first string for anagram check: ");


String s1 = [Link]();

[Link]("Enter second string for anagram check: ");


String s2 = [Link]();

[Link]("Are anagrams? " + isAnagram(s1, s2));

[Link]();
}
}

Output:

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.

import [Link].*;

public class lab12{


public static void main(String[] args) {
try {
BufferedReader br1 = new BufferedReader(new FileReader("C:\\Users\\Student\\
Documents\\Suhas java\\[Link]"));
BufferedReader br2 = new BufferedReader(new FileReader("C:\\Users\\Student\\
Documents\\Suhas java\\[Link]"));
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\Student\\Documents\\
Suhas java\\[Link]"));

String line;

while ((line = [Link]()) != null) {


[Link](line);
[Link]();
}

while ((line = [Link]()) != null)

Department of Computer Applications, BMSCE P a g e | 19


MMC204: Java Programming

[Link](line);
[Link]();
}

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

[Link]("Files merged successfully");

} catch (Exception e) {
[Link](e);
}
}
}

Output:

[Link]

[Link]

[Link]

Department of Computer Applications, BMSCE P a g e | 20


MMC204: Java Programming
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.

import [Link].*;

public class lab13 {


public static void main(String[] args) {
LinkedList queue = new LinkedList();

[Link]("Arun");
[Link]("Bala");
[Link]("Charan");
[Link]("Divya");

[Link]("Reservation Queue: " + queue);

int position = 1;

while (![Link]()) {
String user = (String) [Link]();
[Link](user + " is notified: Your book is available (Position " + position + ")");
position++;
}

[Link]("All reservations processed");


}
}

Output:

Department of Computer Applications, BMSCE P a g e | 21


MMC204: Java Programming
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.

import [Link].*;
import [Link].*;
import [Link].*;

public class ATM extends JFrame {

double balance = 1000;

JTextField amountField;
JTextField balanceField;

public ATM() {
setTitle("ATM System");
setSize(400, 250);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

add(new JLabel("Enter Amount:"));


amountField = new JTextField(10);
add(amountField);

add(new JLabel("Balance:"));
balanceField = new JTextField(10);
[Link](false);
add(balanceField);

JButton depositBtn = new JButton("Deposit");


JButton withdrawBtn = new JButton("Withdraw");
JButton checkBtn = new JButton("Check Balance");

add(depositBtn);
add(withdrawBtn);
add(checkBtn);

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
double amt = [Link]([Link]());
balance += amt;
[Link](null, "Deposited Successfully");
[Link]([Link](balance));

Department of Computer Applications, BMSCE P a g e | 22


MMC204: Java Programming
} catch (Exception ex) {
[Link](null, "Invalid Input");
}
}
});

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
double amt = [Link]([Link]());

if (amt <= balance) {


balance -= amt;
[Link](null, "Withdrawal Successful");
} else {
[Link](null, "Insufficient Balance");
}

[Link]([Link](balance));
} catch (Exception ex) {
[Link](null, "Invalid Input");
}
}
});

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]([Link](balance));
[Link](null, "Current Balance: " + balance);
}
});

setVisible(true);
}

public static void main(String[] args) {


new ATM();
}
}

Output:

Department of Computer Applications, BMSCE P a g e | 23


MMC204: Java Programming

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:
o JMenuBar, JMenu, JMenuItem for the menu.
o JTextField for input.
o JLabel for displaying the result.

import [Link].*;
import [Link].*;
import [Link].*;

public class SimpleCalculator extends JFrame implements ActionListener {

JTextField t1, t2;


JLabel result;
JMenuBar menuBar;
JMenu menu;
JMenuItem addItem, subItem, exitItem;

Department of Computer Applications, BMSCE P a g e | 24


MMC204: Java Programming
public SimpleCalculator() {

setTitle("Simple Calculator");
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

t1 = new JTextField();
t2 = new JTextField();
result = new JLabel("Result: ");

menuBar = new JMenuBar();


menu = new JMenu("Operations");

addItem = new JMenuItem("Add");


subItem = new JMenuItem("Subtract");
exitItem = new JMenuItem("Exit");

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

[Link](addItem);
[Link](subItem);
[Link](exitItem);
[Link](menu);
setJMenuBar(menuBar);

setLayout(new GridLayout(3, 1));


add(t1);
add(t2);
add(result);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if ([Link]() == exitItem) {
[Link](0);
}

try {
double a = [Link]([Link]());
double b = [Link]([Link]());

if ([Link]() == addItem) {
[Link]("Result: " + (a + b));
} else if ([Link]() == subItem) {
[Link]("Result: " + (a - b));
}
} catch (NumberFormatException ex) {
[Link]("Enter valid numbers");
}
}

Department of Computer Applications, BMSCE P a g e | 25


MMC204: Java Programming
public static void main(String[] args) {

new SimpleCalculator();
}
}

Output:

Department of Computer Applications, BMSCE P a g e | 26

You might also like