Complete Java Lab Manual LR23
Complete Java Lab Manual LR23
Y 2024-2025
C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>java Main
Student Name: Alice
Student Age: 20
Student Grade: A
Student Name: Bob
1|Page Faculty Name: B Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
Student Age: 22
Student Grade: B
// Method to withdraw money from checking account (with overdra protec on)
public void withdraw(double amount) {
if (amount <= balance + overdra Limit) {
balance -= amount;
[Link]("Withdrew $" + amount + " from Checking Account.");
} else {
[Link]("Insufficient funds. Cannot withdraw more than available balance + overdra limit.");
}
}
}
Output:
class Shape {
double calculateArea(double r)
{
return [Link]*r*r;
}
double calculateArea(double l,double w)
{
return l*w;
}
double calculateArea(int s)
{
return s*s;
}
}
public class MethodOverloadingExample {
public static void main(String[] args) {
Output:
radius of the circle: 3.5
Area of the circle: 38.48
length of the rectangle: 0
width of the rectangle: 5
Area of the rectangle: 0.00
side length of the square: 6
Area of the square: 36.00
MethodOverridingExample
import [Link].*;
class Calculator {
double calculate(double a,double b)
{
return a+b;
}
}
class ScientificCalculator extends Calculator {
// @Override
double calculate(double a,double b)
{
return a*b;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
Calculator calculator = new Calculator();
[Link]("a = ");
double a=[Link]();
[Link]("b = ");
double b=[Link]();
[Link]("a+b: " + [Link](a,b));
Output:
a = 96.2
b = 63.5
a+b: 159.7
a*b: 6108.7
3.a) Write a Java program to demonstrate the Interfaces & Abstract Classes.
package q18023;
// import required classes
// Define interface Calculator { }
import [Link].*;
interface Calculator
{
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
}
class BasicCalculator implements Calculator {
// Define required methods
public double add(double a,double b)
{
return a+b;
}
public double subtract(double a, double b)
{
return a-b;
}
public double multiply(double a, double b)
{
return a*b;
}
public double divide(double a, double b){
return a/b;
}
}
public class Calc {
}
}
Output:
5
10
Addition:·15.0
Subtraction:·-5.0
Multiplication:·50.0
Division:·0.5
Abastractclass implements
package q11286;
abstract class CalcArea {
abstract double triangleArea(double b, double h);
abstract double rectangleArea(double l, double b);
abstract double squareArea(double s);
abstract double circleArea(double r);
}
@Override
double rectangleArea(double l, double b) {
return l * b;
}
@Override
double squareArea(double s) {
return s * s;
}
@Override
double circleArea(double r) {
return 3.14 * r * r;
}
}
public class Area {
public static void main(String args[]) {
if ([Link] < 2) {
[Link]("Please provide two arguments.");
return;
}
double arg1 = [Link](args[0]);
double arg2 = [Link](args[1]);
FindArea area = new FindArea();
Output:
Area·of·triangle·:·7.529400000000001
Area·of·rectangle·:·15.058800000000002
10 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
Area·of·square·:·12.6736
Area·of·circle·:·56.18370600000001
import [Link].*;
class CheckWeight {
[Link]([Link]());
}
[Link]();
11 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
}
}
// Define a user-defined exception named InvalidWeight
class InvalidWeight extends Exception {
public InvalidWeight(String message) {
super(message);
}
}
Output:
Enter·weight:·101
Exception·caught:·101·is·invalid·weight
3.c) Write a Java program to illustrate the concept of threading using Thread Class
and runnable Interface.
12 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
}
}
Output:
13 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
}
}
14 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
Output:
Enter the number of tables:1
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1*9=9
1 * 10 = 10
5. Write a Java Program that reads a line of integers, and then displays each
integer, and the sum of all the integers (Use String Tokenizer class of [Link])
import [Link];
import [Link];
public class sumofIntegers {
public static void main(String args[]) {
Scanner scanner=new Scanner([Link]);
String input = [Link]();
StringTokenizer tokenizer = new StringTokenizer(input);
int sum = 0;
while ([Link]()) {
// Parse each token as an integer
int num = [Link]([Link]());
6
21
6.a) Write a Java program that reads a file name from the user, and then displays
inform action about whether the file exists, whether the file is readable, whether the file
is writable, the type of file and the ength of the file in bytes.
import [Link];
import [Link];
public class FileInfo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt user for the file name
[Link]("Enter the file name (with path if necessary): ");
String fileName = [Link]();
// Create a File object
File file = new File(fileName);
// Check if the file exists
if ([Link]()) {
[Link]("File exists: Yes");
// Check if the file is readable
[Link]("Readable: " + ([Link]() ? "Yes" : "No"));
// Check if the file is writable
[Link]("Writable: " + ([Link]() ? "Yes" : "No"));
// Get the file type (directory or file)
if ([Link]()) {
[Link]("Type: Directory");
} else {
[Link]("Type: File");
}
// Get the length of the file in bytes
[Link]("Length: " + [Link]() + " bytes");
} else {
[Link]("File exists: No");
}
// Close the scanner
[Link]();
}
}
16 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
Output:
Enter the file name (with path if necessary):
C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS\[Link]
File exists: Yes
Readable: Yes
Writable: Yes
Type: File
Length: 19 bytes
6.b) Write a Java program to illustrate the concept of I/O Streams.
import [Link].*;
import [Link];
public class IOStreamExample {
public static void main(String[] args) {
// File paths for input and output files
Scanner scanner = new Scanner([Link]);
[Link]("file name:");
String inputFileName = [Link]();
String outputFile = "[Link]";
// Create InputStream and OutputStream objects
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
// Create FileInputStream to read data from the input file
File inputFile = new File(inputFileName);
int content;
// Read each byte from the input file and write it to the output file
while ( (content = [Link]()) != -1 ){
[Link](content);
}
// Reading from the output file and printing its contents
17 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
}
catch (IOException e) {
[Link]("No such file");
} finally {
try {
// Close the streams to release resources
if (fileInputStream != null) {
[Link]();
}
if (fileOutputStream != null) {
[Link]();
}
} catch (IOException e) {
[Link]("Error while closing streams: " + [Link]());
}
}
}
}
Output:
file name:[Link]
Contents of the output file:
Hello IT Department
18 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
import [Link].*;
import [Link].*;
import [Link];
/*<applet code="GraphicDemo" width=350 height=700> </applet> */
public class GraphicDemo extends Applet {
public void init()
{
Color c1 = [Link];
setBackground(c1);
Color c2=[Link];
setForeground(c2);
}
public void paint(Graphics g) {
// Draw lines.
[Link](0, 0, 100, 90);
[Link](0, 90, 100, 10);
[Link](40, 25, 250, 80);
// Draw rectangles.
[Link](10, 150, 60, 50);
[Link](100, 150, 60, 50);
[Link](190, 150, 60, 50, 15, 15);
[Link](280, 150, 60, 50, 30, 40);
// Draw Ellipses and Circles
[Link](10, 250, 50, 50);
[Link](90, 250, 75, 50);
[Link](190, 260, 100, 40);
// Draw Arcs
[Link](10, 350, 70, 70, 0, -180); [Link](60, 350, 70, 70, 0, -90);
// Draw a polygon
int xpoints[] = {10, 200, 10, 200, 10};
int ypoints[] = {450, 450, 650, 650, 450};
int num = 5;
[Link](xpoints, ypoints, num);
int xmpoints[]={40,40,50,60,60};
int ympoints[]={60,40,50,40,60}; //Another polygon
[Link](xmpoints, ympoints, num); }
}
Output:
19 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
// Components
Label label;
Button button;
// Set layout
setLayout(new FlowLayout());
// Initialize components
label = new Label("Click the button");
button = new Button("Click Me");
// Main method
public static void main(String[] args) {
new SimpleAWTExample();
}
}
21 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
import [Link];
import [Link].*;
import [Link].*;
// MouseListener methods
public void mouseClicked(MouseEvent e) {
message = "Mouse Clicked";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
22 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
// MouseMotionListener methods
public void mouseDragged(MouseEvent e) {
message = "Mouse Dragged";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
// KeyListener methods
public void keyPressed(KeyEvent e) {
message = "Key Pressed: " + [Link]();
repaint();
}
23 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
appletviewer [Link]
import [Link];
import [Link].*;
import [Link].*;
setBackground([Link]);
1. Save as `[Link]`
2. Compile: `javac [Link]`
3. Run with: `appletviewer [Link]
OutPut:
25 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
import [Link].*;
import [Link];
try {
[Link]("[Link]");
Connection conn = [Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
while (true) {
[Link]("\n1. Add Student");
[Link]("2. View Students");
[Link]("3. Update Student Grade");
[Link]("4. Delete Student");
[Link]("5. Exit");
[Link]("Choose an option: ");
int choice = [Link]();
[Link](); // consume newline
switch (choice) {
case 1:
[Link]("Enter ID: ");
int id = [Link]();
[Link]();
[Link]("Enter name: ");
String name = [Link]();
[Link]("Enter grade: ");
int grade = [Link]();
String insert = "INSERT INTO students (id,name, grade) VALUES
("+id+",'" + name + "', " + grade + ")";
[Link](insert);
[Link]("Student added.");
break;
case 2:
ResultSet rs = [Link]("SELECT * FROM students");
26 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
case 3:
[Link]("Enter student ID: ");
int id1 = [Link]();
[Link]("Enter new grade: ");
int newGrade = [Link]();
[Link]("UPDATE students SET grade = " + newGrade +
" WHERE id = " + id1);
[Link]("Grade updated.");
break;
case 4:
[Link]("Enter student ID to delete: ");
int delId = [Link]();
[Link]("DELETE FROM students WHERE id = " +
delId);
[Link]("Student deleted.");
break;
case 5:
[Link]("Goodbye!");
[Link]();
[Link]();
[Link]();
return;
default:
[Link]("Invalid choice.");
}
}
} catch (Exception e) {
[Link]();
}
}
}
27 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
Output:
//Note Create lib folder in current directory paste [Link] folder and follow
the instructions
To compile:
1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 1
Enter ID: 7
Enter name: naga
Enter grade: 5
Student added.
1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 2
ID | Name | Grade
1 | null | 3
2 | null | 4
7 | naga | 5
1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 3
Enter student ID: 7
Enter new grade: 1
Grade updated.
28 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 2
ID | Name | Grade
1 | null | 3
2 | null | 4
7 | naga | 1
1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 4
Enter student ID to delete: 1
Student deleted.
1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 2
ID | Name | Grade
2 | null | 4
7 | naga | 1
1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option:5
11. Write a Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -, *, % operations. Add a text field to
display the result.
import [Link].*;
import [Link].*;
29 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
public SimpleCalculator() {
setTitle("Simple Calculator");
setLayout(new BorderLayout());
String[] buttons = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", "%", "=", "C"
};
add(panel, [Link]);
setSize(300, 300);
setVisible(true);
// Close window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
30 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
if ([Link]("C")) {
[Link]("");
operator = "";
num1 = num2 = 0;
} else if ([Link]("=")) {
num2 = [Link]([Link]());
double result = 0;
switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "%": result = num1 % num2; break;
}
[Link]([Link](result));
operator = "";
} else if ("+-*%".contains(cmd)) {
num1 = [Link]([Link]());
operator = cmd;
[Link]("");
} else {
[Link]([Link]() + cmd);
}
}
31 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
WebApp/
├── [Link]
├── [Link]
├── [Link]
├── WEB-INF/
│ └── [Link]
└── src/
├── [Link]
├── [Link]
├── [Link]
</form>
<form action="[Link]">
<input type="submit" value="Insert Record">
</form>
<form action="select" method="get">
<input type="submit" value="View Records">
</form>
</body>
</html>
Output:
[Link]
<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body>
<h2>Login Form</h2>
<form action="login" method="post">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Output:
33 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
[Link]
<!DOCTYPE html>
<html>
<head><title>Insert</title></head>
<body>
<h2>Insert New Record</h2>
<form action="insert" method="post">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Output:
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
34 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
[Link]("text/html");
PrintWriter out = [Link]();
try {
[Link]("[Link]");
Connection con = [Link]("jdbc:oracle:thin:@localhost:1521:xe",
"system", "system");
PreparedStatement ps = [Link]("SELECT * FROM users WHERE
username=? AND password=?");
[Link](1, user);
[Link](2, pass);
ResultSet rs = [Link]();
if ([Link]()) {
[Link]("<h2>Welcome, " + user + "</h2>");
} else {
[Link]("<h2>Invalid Credentials</h2>");
}
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
35 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
[Link]("text/html");
PrintWriter out = [Link]();
try {
[Link]("[Link]");
Connection con = [Link]("jdbc:oracle:thin:@localhost:1521:xe",
"system", "system");
PreparedStatement ps = [Link]("INSERT INTO users(name,email)
VALUES(?,?)");
[Link](1, name);
[Link](2, email);
int i = [Link]();
if (i > 0) {
[Link]("<h2>Record inserted successfully</h2>");
}
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
[Link]("text/html");
PrintWriter out = [Link]();
try {
[Link]("[Link]");
36 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
[Link]("<h2>User Records:</h2>");
[Link]("<table border='1'><tr><th>ID</th><th>Name</th><th>Email</th></tr>");
while ([Link]()) {
[Link]("<tr><td>" + [Link]("id") + "</td><td>" +
[Link]("name") + "</td><td>" + [Link]("email") + "</td></tr>");
}
[Link]("</table>");
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
[Link]
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>InsertServlet</servlet-name>
<servlet-class>InsertServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertServlet</servlet-name>
<url-pattern>/insert</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SelectServlet</servlet-name>
37 | P a g e Faculty Name: B
Nagalakshmi IT
Java Programming Lab LR23 A.Y 2024-2025
<servlet-class>SelectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SelectServlet</servlet-name>
<url-pattern>/select</url-pattern>
</servlet-mapping>
</web-app>
//Create database in Oracle 10g
--login to oracle10 express edition:
--[Link]
--username: system
--password: system
-- Step 1: Create the table
CREATE TABLE users (
id NUMBER PRIMARY KEY,
username VARCHAR2(50),
password VARCHAR2(50),
name VARCHAR2(50),
email VARCHAR2(50)
);
38 | P a g e Faculty Name: B
Nagalakshmi IT