0% found this document useful (0 votes)
2 views

JAVA Lab Record (All)

The document is a lab manual for the Object Oriented Programming with Java course (Course Code: 22AIL33) for the academic year 2024-2025. It outlines the department's vision, mission, program educational objectives, specific outcomes, and detailed lab experiments including assessment criteria and prerequisites for using Eclipse IDE. The manual includes various Java programming tasks aimed at enhancing students' understanding of object-oriented programming concepts.

Uploaded by

S.Y Suprabhath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JAVA Lab Record (All)

The document is a lab manual for the Object Oriented Programming with Java course (Course Code: 22AIL33) for the academic year 2024-2025. It outlines the department's vision, mission, program educational objectives, specific outcomes, and detailed lab experiments including assessment criteria and prerequisites for using Eclipse IDE. The manual includes various Java programming tasks aimed at enhancing students' understanding of object-oriented programming concepts.

Uploaded by

S.Y Suprabhath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

DEPARTMENTOFARTIFICIALINTELLIGENCE

ANDMACHINELEARNING

Object Oriented Programming with Java Lab


Course Code:22AIL33
Lab Manual

Academic Year:2024-2025
BATCH: 2023 – 2027
YEAR: II
SEMESTER: III

Lab-Coordinators:
Prof. Syam Dev RS
Prof.K.S.Shashikala
Prof. Sandyarani V
INSTITUTION

Vision

To emerge as an institute of eminence in the fields of engineering, technology and


management in serving the industry and the nation by empowering students with a high
degree of technical, managerial and practical competence.

Mission
To strengthen the theoretical, practical and ethical dimensions of the learning process
by fostering a culture of research and innovation among faculty members and students.

To encourage long-term interaction between the academia and industry through their
involvement in the design of curriculum and its hands-on implementation.

To strengthen and mould students in professional, ethical, social and environmental


dimensions by encouraging participation in co-curricular and extracurricular activities.
To develop value based socially responsible professionals for the betterment of the
society

Quality Policy

To emerge as an institute of eminence in the fields of engineering, technology and


management in serving the industry and the nation by empowering students with a high
degree of technical, managerial and practical competence.

Values
 Academic Freedom  Professionalism
 Innovation  Inclusiveness
 Integrity  Social Responsibility
DEPARTMENT of AI & ML

Vision

To develop an outstanding AI and ML professionalswith profound practical, research & managerial


skills to meet ever changing Industrial Social and Technological needs of the Society

Mission

To disseminate strong theoretical and practical exposure to meet the emerging trends in the industry.

To promote a freethinking environment with innovative research and teaching-learning pedagogy.

To develop value based socially responsible professionals with high degree of leadership skills will
support for betterment of the society.

Program Educational Objectives (PEOs)

Develop and excel in their chosen profession on technical front and progress
PEO1 towards advanced continuing education or Inter-disciplinary Research and
Entrepreneurship
Become a reputed innovative solution provider- to complex system problems or
PEO2 towards research or challenges relevant to Artificial Intelligence and Machine
learning
Progress as skilled team members achieving leadership qualities with trust and
PEO3 professional ethics, pro-active citizens for progress and overall welfare of the
society
Program Specific Outcomes (PSOs)

A graduate of the Computer Engineering Program will demonstrate

PSO1:Develop models in Data Science, Machine learning, Deep learning and Bigdata technologies,
using acquired AI knowledge and modern tools.

PSO2:Formulate solutions for interdisciplinary problems through acquired programming knowledge


in the respective domains complying with real-time constraints.

Program Outcomes (POs)


PO1 Engineering knowledge: Apply the knowledge of mathematics, science, Engineering
fundamentals, and an Engineering specialization to the solution of complex Engineering
problems in Computer Engineering.
PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex
Engineering problems in Computer Engineering reaching substantiated conclusions
using first principles of mathematics, natural sciences, and Engineering sciences.
PO3 Design / Development of Solutions: Design solutions for complex Engineering
problems and design system components or processes of Computer Engineering that
meet the specified needs with appropriate consideration for the public health and safety,
and the cultural, societal, and Environmental considerations.
PO4 Conduct Investigations of Complex Problems:Use research based knowledge and
research methods including design of experiments in Computer Engineering, analysis
and interpretation of data, and synthesis of the information to provide valid conclusions.
PO5 Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern Engineering and IT tools including prediction and modeling to complex
Engineering activities in Computer Engineering with an understanding of the limitations.
PO6 The Engineer and Society:Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice in Computer
Engineering.
PO7 Environment and Sustainability: Understand the impact of the professional
Engineering solutions of Computer Engineering in societal and Environmental contexts,
demonstrate the knowledge of, and need for sustainable development.
PO8 Ethics:Apply ethical principles and commit to professional ethics, responsibilities, and
norms of the Engineering practice.
PO9 Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10 Communication Skills: Communicate effectively on complex Engineering activities
with the Engineering community and with society, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.
PO11 Project Management and Finance: Demonstrate knowledge and understanding of the
Engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary Environments.

PO12 Life-long Learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
Exp.
No. /
List of Experiments / Programs Hours Cos
Pgm.
No.
2 NA
Basic understanding of computer programming
PART A
Create a Java class named Employee with the following attributes: 22AIL33.1
1. name (String), id (int), department (String), salary (double) 2
1 2. Use constructor to initialize the Employee object
3. Create two Employee objects using the constructor
4. Print the details of each employee object in a clear format
Write a Java program to check the strength of a password based on 2 22AIL33.1
2 specific criteria using String class.
Create a Java program to model a hierarchy of vehicles using 2 22AIL33.3
3 inheritance. Apply various access controls, method overriding.
4 Write a java program that implements a multi-thread 2 22AIL33.1
application that has three threads. First thread generates
random integer every 1 second and if the value is even, second
thread computes the square of the number and prints. If the
value is odd, the third thread will print the value of cube of the
number
5 Write a program to read a given File and multiply by 2 if it 2 22AIL33.1
contains numerical value
6 Write a program to implement Singleton Pattern 2 22AIL33.1

PART B

7 Write a Java program to create a simple banking system where 2 22AIL33.1


a user can check balance, deposit money, and withdraw money
using class, constructor, constructor overloading concepts.
8 Design a Java program to compute area and perimeter for 2 22AIL33.1
different shapes using abstract classes and interfaces.
9 Write a Java program to manage bank account transactions using 2 22AIL33.1
exception handling.
10 Task 1: Creating Shared Resources: 2 22AIL33.2
Define two shared resources (objects) that the threads will
contend for. Let’s call them Resource A and Resource B.
Task 2: Implementing Threads:
Create two threads (Thread A and Thread B). Each thread will try
to acquire locks on both Resource A and Resource B.
Main Program:
Start both threads. Observe threads executions.
11 1. Write a program to demonstrate ArrayListClass, Linked List 22AIL33.2
Class. 2. Create a Java program to manage books and users in a 2
library using different packages.
12 Write a program to demonstrate event handling. 2 22AIL33.4
LAB RUBRICS

Course Name: Object Oriented Programming with Java Lab


Course code : 22AIL33
Semester III
Internal Assessment Marks: 50

Divided into two components:

1. Continuous Assessment: 30 marks


2. Internal Test: 20marks

1. ContinuousAssessment:
i) Will be carried out in every lab (for labs -12programs)
ii)Each program will be evaluated for 10marks
iii) Totally for 12 lab programs, it will be 120 marks. This will be scaled down to30.
iv) Duringthesemester,2internaltestswillbeconductedfor20markseach.Thetotal40marksfor the
internal tests, will be scaled down to20.

Break up of 10 marks (in every lab):

Will be carried out in every lab (for 12 lab programs)

Attributes Descriptors Scores


Complete program with proper variable naming, proper
3
commenting
Complete program with not so proper variable naming,
3
Program Write- poor commenting
up(10)
Incomplete code 2

Not written 1

Passes all specified test cases efficiently 3


Execution &
Fails in some test cases 1
Results
(10)
Incomplete execution 0

Answers correctly 2

Viva Voce(5) Answers satisfactorily 1

Do not answer any question 0

Submits in time and completed (during subsequent lab) 2


Record completion
and submission (5)
Fails to submit the record in time / incomplete submission 0
2. InternalTest:

Break up of 20 marks (for each of the 2 internal tests) which will be added together to 40 marks
after the conduction of 2 internal tests and will be scaled down to 20:

The 1st lab internal will comprise of the first 6 lab programs and the 2nd lab internal will comprise of the
next 6 lab programs.

Attributes Descriptors Scores


Complete program with proper variable naming, proper
5
commenting
Complete program with not so proper variable naming,
3-4
Program Write- poor commenting
up(10)
Incomplete code 1-2

Not written 0

Passes all specified test cases efficiently 10


Execution &
Fails in some test cases 4-9
Results (5)
Incomplete execution 1-3

Answers 100% questions correctly 5

Answers 75% questions correctly 3-4


Viva Voce(5)
Answers satisfactorily 1-2

Does not answer any question 0


SEE

Assessment Marks: 50

Session End Examination is conducted for 50 marks.

Attributes Descriptors Scores


Complete program with proper variable naming, proper
10
commenting
Complete program with not so proper variable naming,
5-9
Program Write- poor commenting
up(10)
Incomplete code 1-2

Not written 0

Passes all specified test cases efficiently 30


Execution &
Fails in some test cases 16-29
Results (30)
Incomplete execution 1-15

Answers 100% questions correctly 10

Answers 75% questions correctly 5-9


Viva Voce(10)
Answers satisfactorily 1-4

Does not answer any question 0


Prerequisites
You need to have the following two things to build a program in Eclipse IDE:

1. JDK(Java Development Kit)


2. Eclipse IDE

How to create a Java Project in Eclipse?


Step 1: To create a new Java project in Eclipse, go to File > New > Project.

Step 2: The New Java Project wizard dialog appears to let you specify configurations for the project.
Select the Java Project option in it.Enter the project name and click the Finish button.

Step 4: It is recommended to create a package for your project. Right-click on the project option, and
select New > Package from the context menu

10
Step 5: In the New Java Package dialog, enter the name of your package. Here I have
entered shashikala .Click the Finish button. You will see a newly created package appears on the left
side.

Step 6:
To create a new Java class under a specified package, right-click on the package and select New >
Class from the context menu.Type the name of the class as HelloWorld and choose the option to
generate the main() method.And click Finish. The HelloWorld class is generated.

Step 8: Edit the generated ‘HelloWorld’ java class and add the code to print hello world.

11
Step 9: Right-click on ‘HelloWorld.java’ and select from context menu Run As > Java Application. Click Ok
in the save and Launch Wizard.

Step 10:
After running the program, you will get the following output:

Thus we created the first Java program in Eclipse to create a HelloWorld program.
Now, we can start developing our programs and applications in Java in the Eclipse IDE.

12
EXPERIMENT NO: 1

Create a Java class named Employee with the following attributes:


1. name (String), id (int), department (String), salary (double)
2. Use constructor to initialize the Employee object
3. Create two Employee objects using the constructor
4. Print the details of each employee object in a clear format

public class Employee {


// Attributes
private String name;
private int id;
private String department;
private double salary;

// Constructor to initialize the Employee object


public Employee(String name, int id, String department, double salary)
{
this.name = name;
this.id = id;
this.department = department;
this.salary = salary;
}

// Method to print employee details


public void printDetails()
{
System.out.println("Employee Details:");
System.out.println("Name: " + name);
System.out.println("ID: " + id);
System.out.println("Department: " + department);
System.out.println("Salary: $" + salary);
System.out.println("-----------------------------");
}

// Main method to create and display employee objects


public static void main(String[] args)
{
// Creating two Employee objects
Employee emp1 = new Employee("John", 101, "HR", 55000.00);
Employee emp2 = new Employee("Jane", 102, "Finance", 62000.00);

// Printing details of each employee


emp1.printDetails();
emp2.printDetails();
}}
13
OUTPUT:

14
EXPERIMENT NO: 2
Write a Java program to check the strength of a password based on specific criteria using String
class.

import java.util.Scanner;

publicclassPasswordStrengthChecker {

// Method to check password strength


publicstatic String checkPasswordStrength(String password) {
booleanhasUpperCase=false;
booleanhasLowerCase=false;
booleanhasDigit=false;
booleanhasSpecialChar=false;
StringspecialCharacters="!@#$%^&*()-_=+<>?/{}[]|~`";

// Check length
if (password.length() <8) {
return"Password must be at least 8 characters long.";
}

// Check each character in the password


for (char c : password.toCharArray()) {
if (Character.isUpperCase(c)) {
hasUpperCase = true;
} elseif (Character.isLowerCase(c)) {
hasLowerCase = true;
} elseif (Character.isDigit(c)) {
hasDigit = true;
} elseif (specialCharacters.indexOf(c) >= 0) {
hasSpecialChar = true;
}
}

// Determine strength
if (hasUpperCase && hasLowerCase && hasDigit && hasSpecialChar) {
return"Strong password.";
} elseif ((hasUpperCase && hasLowerCase && hasDigit) ||
(hasUpperCase && hasLowerCase && hasSpecialChar) ||
(hasUpperCase && hasDigit && hasSpecialChar) ||
(hasLowerCase && hasDigit && hasSpecialChar)) {
return"Medium strength password.";
} else {
return"Weak password.";
}
}

// Main method to execute the program


publicstaticvoidmain(String[] args) {
Scannerscanner=newScanner(System.in);
System.out.print("Enter a password to check its strength: ");
Stringpassword= scanner.nextLine();

Stringstrength= checkPasswordStrength(password);

15
System.out.println(strength);

scanner.close();
}
}

OUTPUT

16
EXPERIMENT NO: 3
Create a Java program to model a hierarchy of vehicles using inheritance. Apply various access
controls, method overriding.
class Vehicle {
// Protected attributes can be accessed by subclasses
protected String brand;
protected int year;

// Constructor
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}

// Method to display vehicle details


public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}

// Method to get the type of vehicle (can be overridden)


public String getType() {
return "Generic Vehicle";
}
}

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

// Constructor
public Car(String brand, int year, int numDoors) {
super(brand, year); // Call to the superclass constructor
this.numDoors = numDoors;
}

// Overriding displayInfo method


@Override
public void displayInfo() {
super.displayInfo(); // Call to superclass method
17
System.out.println("Number of Doors: " + numDoors);
}

// Overriding getType method


@Override
public String getType() {
return "Car";
}
}

// Subclass Truck
class Truck extends Vehicle {
private double loadCapacity;

// Constructor
public Truck(String brand, int year, double loadCapacity) {
super(brand, year); // Call to the superclass constructor
this.loadCapacity = loadCapacity;
}

// Overriding displayInfo method


@Override
public void displayInfo() {
super.displayInfo(); // Call to superclass method
System.out.println("Load Capacity: " + loadCapacity + " tons");
}

// Overriding getType method


@Override
public String getType() {
return "Truck";
}
}

// Main class to demonstrate the hierarchy


public class VehicleDemo {
public static void main(String[] args) {
// Create instances of Car and Truck
Vehicle myCar = new Car("Toyota", 2020, 4);

18
Vehicle myTruck = new Truck("Ford", 2018, 2.5);

// Display vehicle information


System.out.println("Vehicle Type: " + myCar.getType());
myCar.displayInfo();
System.out.println("-------------------------");
System.out.println("Vehicle Type: " + myTruck.getType());
myTruck.displayInfo();
}
}

OUTPUT

19
EXPERIMENT NO: 4
Write a java program that implements a multi-thread application that has three threads. First
thread generates random integer every 1 second and if the value is even, second thread computes
the square of the number and prints. If the value is odd, the third thread will print the value of
cube of the number

import java.util.Random;

class RThread extends Thread {


public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int rnum = random.nextInt(100);
System.out.println("Random Integer generated : " + rnum);
if((rnum%2) == 0) {
SThread sob = new SThread(rnum);
sob.start();
}
else {
CThread cob = new CThread(rnum);
cob.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}

class SThread extends Thread {


int number;

SThread(int no) {
number = no;
}

public void run() {


System.out.println("Square of " + number + " = " + (number * number));
}
}

class CThread extends Thread {


int number;

20
CThread(int no) {
number = no;
}

public void run() {


System.out.println("Cube of " + number + " = " + number * number * number);
}
}

public class RandThread {


public static void main(String args[]) {
RThread rob = new RThread();
rob.start();
}
}

OUTPUT

21
EXPERIMENT NO: 5

Write a program to read a given File and multiply by 2 if it contains numerical value.

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class MultiplyNumbersInFile {

public static void main(String[] args) {

String inputFilePath = "input.txt"; // Input file path

String outputFilePath = "output.txt"; // Output file path

try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));

BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {

String line;

while ((line = reader.readLine()) != null) {

String[] values = line.split("\\s+"); // Split line into words based on whitespace

for (String value : values) {

try {

// Try to parse the number and multiply by 2

double number = Double.parseDouble(value);


22
double multipliedValue = number * 2;

writer.write(multipliedValue + " "); // Write the multiplied value to the output file

} catch (NumberFormatException e) {

// If it's not a number, ignore it

writer.write(value + " "); // Write the original value

writer.newLine(); // Write a new line after each line of input

} catch (IOException e) {

e.printStackTrace();

OUTPUT

23
EXPERIMENT NO:6

Write a program to implement Singleton Pattern.

class Singleton {
// Volatile variable to ensure visibility and prevent instruction reordering
private static volatile Singleton instance;

// Private constructor to prevent instantiation


private Singleton() {
// Initialization code here
}
// Public method to provide access to the singleton instance
public static Singleton getInstance() {
if (instance == null) { // First check (lazy initialization)
synchronized (Singleton.class) { // Lock to ensure thread safety
if (instance == null) { // Second check
instance = new Singleton();
}
}
}
return instance;
}

// Example method in the Singleton class


public void showMessage() {
System.out.println("Hello from Singleton!");
}
}

// Test the Singleton pattern


public class SingletonDemo {
public static void main(String[] args) {
// Get the only instance of the Singleton class
Singleton singleton = Singleton.getInstance();

// Call a method on the singleton instance


singleton.showMessage();
}
}

OUTPUT

24
EXPERIMENT NO :7

Write a Java program to create a simple banking system where a user can check balance, deposit
money, and withdraw money using class, constructor, constructor overloading concepts.

import java.util.Scanner;

class BankAccount {
private String accountHolder;
private double balance;

// Constructor to initialize account with account holder's name


public BankAccount(String accountHolder) {
this.accountHolder = accountHolder;
this.balance = 0.0; // Initial balance set to zero
}

// Constructor to initialize account with account holder's name and initial deposit
public BankAccount(String accountHolder, double initialDeposit) {
this.accountHolder = accountHolder;
this.balance = initialDeposit; // Set the initial balance
}

// Method to check balance


public double checkBalance() {
return balance;
}

// Method to deposit money


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
} else {
System.out.println("Deposit amount must be positive.");
}
}

// Method to withdraw money


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {

25
System.out.println("Insufficient funds or invalid amount.");
}
}

// Method to display account information


public void displayAccountInfo() {
System.out.println("Account Holder: " + accountHolder);
System.out.println("Current Balance: $" + balance);
}
}

public class BankingSystem {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Create a bank account with the account holder's name


System.out.print("Enter account holder's name: ");
String name = scanner.nextLine();
BankAccount account = new BankAccount(name);

// Menu for banking operations


int choice;
do {
System.out.println("\n--- Banking System ---");
System.out.println("1. Check Balance");
System.out.println("2. Deposit Money");
System.out.println("3. Withdraw Money");
System.out.println("4. Display Account Info");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.println("Current Balance: $" + account.checkBalance());
break;
case 2:
System.out.print("Enter amount to deposit: $");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 3:
System.out.print("Enter amount to withdraw: $");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);

26
break;
case 4:
account.displayAccountInfo();
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 5);

scanner.close();
}
}

27
28
EXPERIMENT NO: 8

Design a Java program to compute area and perimeter for different shapes using abstract classes and
interfaces.

interface ShapeOperations
{
double calculateArea();
double calculatePerimeter();
}

// Abstract class Shape


abstract class Shape implements ShapeOperations
{
// Abstract method to be implemented by subclasses
public abstract String getShapeName();
}

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

public Circle(double radius)


{
this.radius = radius;
}

@Override
public double calculateArea()
{
return Math.PI * radius * radius;
}

@Override
public double calculatePerimeter()
{
return 2 * Math.PI * radius;
}

@Override
public String getShapeName()
{

29
return "Circle";
}
}

// Rectangle class
class Rectangle extends Shape {
private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
public double calculateArea() {
return width * height;
}

@Override
public double calculatePerimeter() {
return 2 * (width + height);
}

@Override
public String getShapeName() {
return "Rectangle";
}
}

// Square class
class Square extends Rectangle {
public Square(double side) {
super(side, side); // Call the Rectangle constructor
}

@Override
public String getShapeName() {
return "Square";
}
}

// Main class to test the shapes


public class ShapeCalculator {
public static void main(String[] args) {

30
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
Shape square = new Square(3);

// Display area and perimeter for each shape


displayShapeInfo(circle);
displayShapeInfo(rectangle);
displayShapeInfo(square);
}

private static void displayShapeInfo(Shape shape) {


System.out.println("Shape: " + shape.getShapeName());
System.out.println("Area: " + shape.calculateArea());
System.out.println("Perimeter: " + shape.calculatePerimeter());
System.out.println("---------------------------");
}
}

OUTPUT

31
EXPERIMENT NO: 9
import java.util.InputMismatchException;
import java.util.Scanner;

// Custom exception for insufficient funds


class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}

// Class to represent a bank account


class BankAccount1 {
private String accountHolder;
private double balance;

// Constructor to initialize account holder's name and initial balance


public BankAccount1(String accountHolder) {
this.accountHolder = accountHolder;
this.balance = 0.0; // Initial balance set to zero
}

// Method to deposit money


public void deposit(double amount) {
if (amount <= 0) {
System.out.println("Deposit amount must be positive.");
return;
}
balance += amount;
System.out.println("Deposited: $" + amount);
}

// Method to withdraw money


public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0) {
System.out.println("Withdrawal amount must be positive.");
return;
32
}
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds for withdrawal.");
}
balance -= amount;
System.out.println("Withdrawn: $" + amount);
}

// Method to check balance


public double checkBalance() {
return balance;
}

// Method to get account holder's name


public String getAccountHolder() {
return accountHolder;
}
}

// Main class to manage the bank account transactions


public class BAM {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Get account holder's name and create the account


System.out.print("Enter account holder's name: ");
String name = scanner.nextLine();
BankAccount1 account = new BankAccount1(name);

int choice = -1;


do {
// Display menu
System.out.println("\n--- Bank Account Management ---");
System.out.println("1. Check Balance");
System.out.println("2. Deposit Money");
System.out.println("3. Withdraw Money");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");

33
try {
choice = scanner.nextInt(); // Get user's menu choice

switch (choice) {
case 1:
System.out.println("Current Balance: $" + account.checkBalance());
break;
case 2:
System.out.print("Enter amount to deposit: $");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 3:
System.out.print("Enter amount to withdraw: $");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} catch (InsufficientFundsException e) {
// Handle insufficient funds exception
System.out.println("Error: " + e.getMessage());
} catch (InputMismatchException e) {
// Handle invalid input (non-integer or non-double values)
System.out.println("Invalid input. Please enter a number.");
scanner.next(); // Clear the invalid input
}
} while (choice != 4);

scanner.close();
}
}

34
OUTPUT

35
EXPERIMENT NO:10
Task 1: Creating Shared Resources:

Define two shared resources (objects) that the threads will contend for. Let’s call them Resource
A and Resource B.

Task 2: Implementing Threads:

Create two threads (Thread A and Thread B). Each thread will try to acquire locks on both
Resource A and Resource B.

Main Program:

Start both threads. Observe threads executions.

class Resource {

private String name;

public Resource(String name) {

this.name = name;

public String getName() {

return name;

class ThreadA extends Thread {

private Resource resourceA;

private Resource resourceB;

36
public ThreadA(Resource resourceA, Resource resourceB) {

this.resourceA = resourceA;

this.resourceB = resourceB;

@Override

public void run() {

synchronized (resourceA) {

System.out.println("Thread A locked " + resourceA.getName());

// Simulating some processing

try {

Thread.sleep(100); // Sleep for 100ms

} catch (InterruptedException e) {

e.printStackTrace();

synchronized (resourceB) {

System.out.println("Thread A locked " + resourceB.getName());

// Simulating some processing

System.out.println("Thread A is using resources.");

37
class ThreadB extends Thread {

private Resource resourceA;

private Resource resourceB;

public ThreadB(Resource resourceA, Resource resourceB) {

this.resourceA = resourceA;

this.resourceB = resourceB;

@Override

public void run() {

synchronized (resourceB) {

System.out.println("Thread B locked " + resourceB.getName());

// Simulating some processing

try {

Thread.sleep(100); // Sleep for 100ms

} catch (InterruptedException e) {

e.printStackTrace();

synchronized (resourceA) {

System.out.println("Thread B locked " + resourceA.getName());

// Simulating some processing

System.out.println("Thread B is using resources.");

}
38
public class Main {

public static void main(String[] args) {

Resource resourceA = new Resource("Resource A");

Resource resourceB = new Resource("Resource B");

ThreadA threadA = new ThreadA(resourceA, resourceB);

ThreadB threadB = new ThreadB(resourceA, resourceB);

// Start both threads

threadA.start();

threadB.start();

// Wait for both threads to finish

try {

threadA.join();

threadB.join();

} catch (InterruptedException e) {

e.printStackTrace();

} System.out.println("Main thread finished.");

OUTPUT

39
EXPERIMENT NO: 11

a. Write a program to demonstrate ArrayListClass, Linked List Class.


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ListDemo {


public static void main(String[] args) {
// Demonstrating ArrayList
System.out.println("ArrayList Demonstration:");
List<String> arrayList = new ArrayList<>();

// Adding elements
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");

// Printing the ArrayList


System.out.println("ArrayList: " + arrayList);

// Removing an element
arrayList.remove("Banana");
System.out.println("After removing Banana: " + arrayList);

// Iterating through the ArrayList


System.out.println("Iterating through ArrayList:");
for (String fruit : arrayList) {
System.out.println(fruit);
}

// Demonstrating LinkedList
System.out.println("\nLinkedList Demonstration:");
List<String> linkedList = new LinkedList<>();

// Adding elements
linkedList.add("Dog");
linkedList.add("Cat");
linkedList.add("Mouse");

// Printing the LinkedList


System.out.println("LinkedList: " + linkedList);

// Removing an element
40
linkedList.remove("Cat");
System.out.println("After removing Cat: " + linkedList);

// Iterating through the LinkedList


System.out.println("Iterating through LinkedList:");
for (String animal : linkedList) {
System.out.println(animal);
}
}
}

EXPERIMENT :11b.Create a Java program to manage books and users in a library using
different packages.

package library;

public class Book {

private String title;

private String author;

private String isbn;

public Book(String title, String author, String isbn) {

this.title = title;

this.author = author;

this.isbn = isbn;

public String getTitle() {

return title;

public String getAuthor() {

return author;

41
}

public String getIsbn() {

return isbn;

@Override

public String toString() {

return "Title: " + title + ", Author: " + author + ", ISBN: " + isbn; }}

Library.java

java

Copy code

package library;

import java.util.ArrayList;

import java.util.List;

public class Library {

private List<Book> books;

public Library() {

this.books = new ArrayList<>();

public void addBook(Book book) {

books.add(book);

System.out.println("Book added: " + book);

public void listBooks() {

System.out.println("Books in the library:");

42
for (Book book : books) {

System.out.println(book);

//Package: user

//User.java

package user;

public class User {

private String name;

private String userId;

public User(String name, String userId) {

this.name = name;

this.userId = userId;

public String getName() {

return name;

public String getUserId() {

return userId;

@Override

43
public String toString() {

return "User Name: " + name + ", User ID: " + userId;

UserManager.java

package user;

import java.util.ArrayList;

import java.util.List;

public class UserManager {

private List<User> users;

public UserManager() {

this.users = new ArrayList<>();

public void addUser(User user) {

users.add(user);

System.out.println("User added: " + user);

public void listUsers() {

System.out.println("Registered users:");

for (User user : users) {

System.out.println(user);

44
}

//Main Class

//Main.java

import library.Book;

import library.Library;

import user.User;

import user.UserManager;

public class Main {

public static void main(String[] args) {

// Create library and user manager

Library library = new Library();

UserManager userManager = new UserManager();

// Create some books

Book book1 = new Book("1984", "George Orwell", "9780451524935");

Book book2 = new Book("To Kill a Mockingbird", "Harper Lee", "9780061120084");

// Add books to the library

library.addBook(book1);

library.addBook(book2);

// List all books

library.listBooks();

// Create some users

User user1 = new User("Alice", "U001");

User user2 = new User("Bob", "U002");

45
// Add users

userManager.addUser(user1);

userManager.addUser(user2);

// List all users

userManager.listUsers();

OUTPUT

EXPERIMEMT NO:12
Writea program to demonstrate Event Handling.

import javax.swing.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class EventHandlingExample {

public static void main(String[] args) {


46
// Create the main frame

JFrame frame = new JFrame("Event Handling Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(300, 200);

frame.setLayout(null);

// Create a label

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

label.setBounds(80, 30, 150, 30);

frame.add(label);

// Create a button

JButton button = new JButton("Click Me");

button.setBounds(90, 80, 120, 30);

frame.add(button);

// Add an action listener to the button

button.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

label.setText("Button Clicked!");

});

// Make the frame visible

47
frame.setVisible(true);

OUTPUT

48
VIVA QUESTIONS

1. Can you pass the negative number as an array size?

No. You can’t pass the negative integer as an array size. If you pass, there will be no compile time error
but you will get NegativeArraySizeException at run time

2. What are the differences between Array and ArrayList in java?

Arrays are of fixed length. ArrayList is of variable length. You can’t change the size of the array once
you create it. Size of the ArrayList grows and shrinks as you add or remove the elements.

Array does not support generics. ArrayList supports generics. You can use arrays to store both primitive
types as well as reference types. You can store only reference types in an ArrayList

3. What are the Exception Handling Keywords in Java?

There are four keywords used in java exception handling.

1. throw: Sometimes we explicitly want to create exception object and then throw it to halt the normal
processing of the program. throw keyword is used to throw exception to the runtime to handle it.

2. throws: When we are throwing any checked exception in a method and not handling it, then we need
to use throws

keyword in method signature to let caller program know the exceptions that might be thrown by the
method. The caller method might handle these exceptions or propagate it to it’s caller method using
throws keyword. We can provide multiple exceptions in the throws clause and it can be used with
main() method also.

3. try-catch: We use try-catch block for exception handling in our code. try is the start of the block and
catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try
and try-catch block can be nested also. catch block requires a parameter that should be of type
Exception.

4. finally: finally block is optional and can be used only with try-catch block. Since exception halts the
process of execution, we might have some resources open that will not get closed, so we can use finally
block. finally block gets executed always, whether exception occurs or not.

4. What is difference between throw and throws keyword in Java?

49
throws keyword is used with method signature to declare the exceptions that the method might throw
whereas throw keyword is used to disrupt the flow of program and handing over the exception object to
runtime to handle it.

5. Define an access specifiers? Give example


Java provides a number of access modifiers to set access levels for classes, variables,methods and
constructors. The four access levels are:
Visible to the package. The default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected)

6. What are the kinds of variables in Java?


Java has three kinds of variables namely,
a. Instance variables
b. Local variables
c. Class variables

7. Describe output streams and input streams in Java.


I/O in Java is built on streams. Input streams read data. Output streams write data. Different
fundamental stream classes such as java.io.FileInputStream read and write particular sources of data.

8. Mention the purpose of the keyword final?


Final in java is very important keyword and can be applied to class, method, and variables in Java. A
variable can be declared as final. Doing so prevents its contents from being modified. This means that
you must initialize a final variable when it is declared

9. What is the difference between constructor and method?


Constructors can't be called directly; they are called implicitly when the new keyword creates an object.
Methods can be called directly on an object that has already been created with new. Constructors create
and initialize objects that don't exist yet, while methods perform operations on objects that already exist.

10. How to define an interface?

Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:
Example:
/* File name : NameOfInterface.java */
import java.lang.*;
50
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\}

11. What is a Class?

Class is a template for a set of objects that share a common structure and a common behaviour.

12. What is meant by abstraction?

Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of
objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the
viewer. It is the process of focusing on the essential characteristics of an object. Abstraction is one of
the fundamental elements of the object model.

13. Differentiate between a Class and an Object?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to
represent the classes and interfaces that are loaded by a Java program.

The Class class is used to obtain information about an object's design. A Class is only a definition or
prototype of real life object.

Whereas an object is an instance or living representation of real life object. Every object belongs to a
class and every class contains one or more related objects.

14. What is meant by Polymorphism?


Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being
able to assign a different behavior or value in a subclass, to something that was declared in a parent
class.

15. What is Dynamic Binding?


Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding (also known as late binding) means that the code associated with a given procedure
call is not known until the time of the call at run-time. It is associated with polymorphism and
inheritance.

16. What is final modifier?


The final modifier keyword makes that the programmer cannot change the value anymore.
The actual meaning depends on whether it is applied to a class, a variable, or a method.
51
final Classes- A final class cannot have subclasses.
final Variables- A final variable cannot be changed once it is initialized.
final Methods- A final method cannot be overridden by subclasses.

17. What is an Interface?


Interface is an outside view of a class or object which emphasises its abstraction while hiding its
structure and secrets of its behaviour.

18. What is a base class?


Base class is the most generalised class in a class structure. Most applications have such root classes. In
Java, Object is the base class for all classes.

19. Define super class and subclass?


Superclass is a class from which another class inherits.Subclass is a class that inherits from one or more
classes.

20. What is meant by Binding, Static binding, Dynamic binding?


Binding:
Binding denotes association of a name with a class
Static binding:
Static binding is a binding in which the class association is made during compile time. This is also
called as Early binding.
Dynamic binding:
Dynamic binding is a binding in which the class association is not made until the object is created at
execution time. It is also called as Late binding.

52

You might also like