JAVA Lab Record (All)
JAVA Lab Record (All)
ANDMACHINELEARNING
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
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.
Quality Policy
Values
Academic Freedom Professionalism
Innovation Inclusiveness
Integrity Social Responsibility
DEPARTMENT of AI & ML
Vision
Mission
To disseminate strong theoretical and practical exposure to meet the emerging trends in the industry.
To develop value based socially responsible professionals with high degree of leadership skills will
support for betterment of the society.
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)
PSO1:Develop models in Data Science, Machine learning, Deep learning and Bigdata technologies,
using acquired AI knowledge and modern tools.
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
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.
Not written 1
Answers correctly 2
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.
Not written 0
Assessment Marks: 50
Not written 0
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
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 {
// Check length
if (password.length() <8) {
return"Password must be at least 8 characters long.";
}
// 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.";
}
}
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;
}
// 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;
}
// 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;
}
18
Vehicle myTruck = new Truck("Ford", 2018, 2.5);
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;
SThread(int no) {
number = no;
}
20
CThread(int no) {
number = no;
}
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;
String line;
try {
writer.write(multipliedValue + " "); // Write the multiplied value to the output file
} catch (NumberFormatException e) {
} catch (IOException e) {
e.printStackTrace();
OUTPUT
23
EXPERIMENT NO:6
class Singleton {
// Volatile variable to ensure visibility and prevent instruction reordering
private static volatile Singleton instance;
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 and initial deposit
public BankAccount(String accountHolder, double initialDeposit) {
this.accountHolder = accountHolder;
this.balance = initialDeposit; // Set the initial balance
}
25
System.out.println("Insufficient funds or invalid amount.");
}
}
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();
}
// Circle class
class Circle extends Shape
{
private double 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;
@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";
}
}
30
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
Shape square = new Square(3);
OUTPUT
31
EXPERIMENT NO: 9
import java.util.InputMismatchException;
import java.util.Scanner;
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.
Create two threads (Thread A and Thread B). Each thread will try to acquire locks on both
Resource A and Resource B.
Main Program:
class Resource {
this.name = name;
return name;
36
public ThreadA(Resource resourceA, Resource resourceB) {
this.resourceA = resourceA;
this.resourceB = resourceB;
@Override
synchronized (resourceA) {
try {
} catch (InterruptedException e) {
e.printStackTrace();
synchronized (resourceB) {
37
class ThreadB extends Thread {
this.resourceA = resourceA;
this.resourceB = resourceB;
@Override
synchronized (resourceB) {
try {
} catch (InterruptedException e) {
e.printStackTrace();
synchronized (resourceA) {
}
38
public class Main {
threadA.start();
threadB.start();
try {
threadA.join();
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
OUTPUT
39
EXPERIMENT NO: 11
// Adding elements
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
// Removing an element
arrayList.remove("Banana");
System.out.println("After removing Banana: " + arrayList);
// Demonstrating LinkedList
System.out.println("\nLinkedList Demonstration:");
List<String> linkedList = new LinkedList<>();
// Adding elements
linkedList.add("Dog");
linkedList.add("Cat");
linkedList.add("Mouse");
// Removing an element
40
linkedList.remove("Cat");
System.out.println("After removing Cat: " + linkedList);
EXPERIMENT :11b.Create a Java program to manage books and users in a library using
different packages.
package library;
this.title = title;
this.author = author;
this.isbn = isbn;
return title;
return author;
41
}
return isbn;
@Override
return "Title: " + title + ", Author: " + author + ", ISBN: " + isbn; }}
Library.java
java
Copy code
package library;
import java.util.ArrayList;
import java.util.List;
public Library() {
books.add(book);
42
for (Book book : books) {
System.out.println(book);
//Package: user
//User.java
package user;
this.name = name;
this.userId = userId;
return name;
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 UserManager() {
users.add(user);
System.out.println("Registered users:");
System.out.println(user);
44
}
//Main Class
//Main.java
import library.Book;
import library.Library;
import user.User;
import user.UserManager;
library.addBook(book1);
library.addBook(book2);
library.listBooks();
45
// Add users
userManager.addUser(user1);
userManager.addUser(user2);
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;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(null);
// Create a label
frame.add(label);
// Create a button
frame.add(button);
button.addActionListener(new ActionListener() {
@Override
label.setText("Button Clicked!");
});
47
frame.setVisible(true);
OUTPUT
48
VIVA QUESTIONS
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
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
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.
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.
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\}
Class is a template for a set of objects that share a common structure and a common behaviour.
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.
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.
52