Java Labmanual Complete LR23
Java Labmanual Complete LR23
class Student {
// Properties (Fields)
String name;
int age;
String grade;
// Method to display student detail
public void displayStudentInfo() {
System.out.println("Student Name: " + name);
System.out.println("Student Age: " + age);
System.out.println("Student Grade: " + grade);
}
}
Output:
C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>javac Main.java
C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>java Main
Student Name: Alice
Student Age: 20
Student Grade: A
Student Name: Bob
Student Age: 22
Student Grade: B
1. b) Write a Java program to illustrate types of constructors.
class Student {
// Properties (Fields)
String name;
int age;
String grade;
// Constructor to initialize the Student object
public Student(String name, int age, String grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
// Method to display student details
public void displayStudentInfo() {
System.out.println("Student Name: " + name);
System.out.println("Student Age: " + age);
System.out.println("Student Grade: " + grade);
}
}
// Main class to test the Student class
public class Main1 {
public static void main(String[] args) {
// Creating Student objects and initializing them with constructor
Student student1 = new Student("Alice", 20, "A");
Student student2 = new Student("Bob", 22, "B");
// Calling method on the student objects to display their details
student1.displayStudentInfo();
student2.displayStudentInfo();
}
}
Output:
C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>javac Main1.java
C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>java Main1
Output:
class Shape {
double calculateArea(double r)
{
return Math.PI*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 java.util.*;
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(System.in);
Calculator calculator = new Calculator();
System.out.print("a = ");
double a=sc.nextDouble();
System.out.print("b = ");
double b=sc.nextDouble();
System.out.println("a+b: " + calculator.calculate(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 java.util.*;
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 {
public static void main(String[] args) {
Calculator calculator = new BasicCalculator();
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
double result1 = calculator.add(a, b);
double result2 = calculator.subtract(a, b);
double result3 = calculator.multiply(a, b);
double result4 = calculator.divide(a, b);
}
}
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 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 (args.length < 2) {
System.out.println("Please provide two arguments.");
return;
}
double arg1 = Double.parseDouble(args[0]);
double arg2 = Double.parseDouble(args[1]);
FindArea area = new FindArea();
Output:
Area·of·triangle·:·7.529400000000001
Area·of·rectangle·:·15.058800000000002
Area·of·square·:·12.6736
Area·of·circle·:·56.18370600000001
System.out.println(e.getMessage());
}
scanner.close();
}
}
// 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.
Output:
}
}
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 java.util)
import java.util.Scanner;
import java.util.StringTokenizer;
public class sumofIntegers {
public static void main(String args[]) {
Scanner scanner=new Scanner(System.in);
String input = scanner.nextLine();
StringTokenizer tokenizer = new StringTokenizer(input);
int sum = 0;
while (tokenizer.hasMoreTokens()) {
// Parse each token as an integer
int num = Integer.parseInt(tokenizer.nextToken());
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 java.io.File;
import java.util.Scanner;
public class FileInfo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user for the file name
System.out.print("Enter the file name (with path if necessary): ");
String fileName = scanner.nextLine();
// Create a File object
File file = new File(fileName);
// Check if the file exists
if (file.exists()) {
System.out.println("File exists: Yes");
// Check if the file is readable
System.out.println("Readable: " + (file.canRead() ? "Yes" : "No"));
// Check if the file is writable
System.out.println("Writable: " + (file.canWrite() ? "Yes" : "No"));
// Get the file type (directory or file)
if (file.isDirectory()) {
System.out.println("Type: Directory");
} else {
System.out.println("Type: File");
}
// Get the length of the file in bytes
System.out.println("Length: " + file.length() + " bytes");
} else {
System.out.println("File exists: No");
}
// Close the scanner
scanner.close();
}
}
Output:
Enter the file name (with path if necessary): C:\Users\batch_vfqr8xp\OneDrive\Desktop\
JAVA_PGMS\hello.txt
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 java.io.*;
import java.util.Scanner;
public class IOStreamExample {
public static void main(String[] args) {
// File paths for input and output files
Scanner scanner = new Scanner(System.in);
System.out.print("file name:");
String inputFileName = scanner.nextLine();
String outputFile = "output.txt";
// 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 = fileInputStream.read()) != -1 ){
fileOutputStream.write(content);
}
// Reading from the output file and printing its contents
FileInputStream outputFileStream = new FileInputStream(outputFile);
StringBuilder outputContent = new StringBuilder();
while ((content = outputFileStream.read()) != -1) {
outputContent.append((char) content);
}
System.out.println("Contents of the output file:");
System.out.print(outputContent.toString());
Output:
file name:hello.txt
Contents of the output file:
Hello IT Department
import java.awt.*;
import java.applet.*;
import java.awt.color.ColorSpace;
/*<applet code="GraphicDemo" width=350 height=700> </applet> */
public class GraphicDemo extends Applet {
public void init()
{
Color c1 = Color.WHITE;
setBackground(c1);
Color c2=Color.BLUE;
setForeground(c2);
}
public void paint(Graphics g) {
// Draw lines.
g.drawLine(0, 0, 100, 90);
g.drawLine(0, 90, 100, 10);
g.drawLine(40, 25, 250, 80);
// Draw rectangles.
g.drawRect(10, 150, 60, 50);
g.fillRect(100, 150, 60, 50);
g.drawRoundRect(190, 150, 60, 50, 15, 15);
g.fillRoundRect(280, 150, 60, 50, 30, 40);
// Draw Ellipses and Circles
g.drawOval(10, 250, 50, 50);
g.fillOval(90, 250, 75, 50);
g.drawOval(190, 260, 100, 40);
// Draw Arcs
g.drawArc(10, 350, 70, 70, 0, -180); g.fillArc(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;
g.drawPolygon(xpoints, ypoints, num);
int xmpoints[]={40,40,50,60,60};
int ympoints[]={60,40,50,40,60}; //Another polygon
g.drawPolygon(xmpoints, ympoints, num); }
}
Output:
7.b) write a simple java program to implement AWT class
import java.awt.*;
import java.awt.event.*;
// 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();
}
}
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
// MouseListener methods
public void mouseClicked(MouseEvent e) {
message = "Mouse Clicked";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}
// MouseMotionListener methods
public void mouseDragged(MouseEvent e) {
message = "Mouse Dragged";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}
// KeyListener methods
public void keyPressed(KeyEvent e) {
message = "Key Pressed: " + e.getKeyChar();
repaint();
}
appletviewer MouseKeyApplet.java
9. Write a Java applet program to implement Adapter classes
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
1. Save as `MouseAdapterExample.java`
2. Compile: `javac MouseAdapterExample.java`
3. Run with: `appletviewer MouseAdapterExample.java
OutPut:
import java.sql.*;
import java.util.Scanner;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
while (true) {
System.out.println("\n1. Add Student");
System.out.println("2. View Students");
System.out.println("3. Update Student Grade");
System.out.println("4. Delete Student");
System.out.println("5. Exit");
System.out.print("Choose an option: ");
int choice = sc.nextInt();
sc.nextLine(); // consume newline
switch (choice) {
case 1:
System.out.print("Enter ID: ");
int id = sc.nextInt();
sc.nextLine();
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter grade: ");
int grade = sc.nextInt();
String insert = "INSERT INTO students (id,name, grade) VALUES
("+id+",'" + name + "', " + grade + ")";
stmt.executeUpdate(insert);
System.out.println("Student added.");
break;
case 2:
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
System.out.println("ID | Name | Grade");
while (rs.next()) {
System.out.println(rs.getInt("id") + " | " + rs.getString("name") + " |
" + rs.getInt("grade"));
}
break;
case 3:
System.out.print("Enter student ID: ");
int id1 = sc.nextInt();
System.out.print("Enter new grade: ");
int newGrade = sc.nextInt();
stmt.executeUpdate("UPDATE students SET grade = " + newGrade +
" WHERE id = " + id1);
System.out.println("Grade updated.");
break;
case 4:
System.out.print("Enter student ID to delete: ");
int delId = sc.nextInt();
stmt.executeUpdate("DELETE FROM students WHERE id = " +
delId);
System.out.println("Student deleted.");
break;
case 5:
System.out.println("Goodbye!");
stmt.close();
conn.close();
sc.close();
return;
default:
System.out.println("Invalid choice.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
//Note Create lib folder in current directory paste ojdbc14.jar 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.
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 java.awt.*;
import java.awt.event.*;
public SimpleCalculator() {
setTitle("Simple Calculator");
setLayout(new BorderLayout());
String[] buttons = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", "%", "=", "C"
};
add(panel, BorderLayout.CENTER);
setSize(300, 300);
setVisible(true);
// Close window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
if (cmd.equals("C")) {
display.setText("");
operator = "";
num1 = num2 = 0;
} else if (cmd.equals("=")) {
num2 = Double.parseDouble(display.getText());
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;
}
display.setText(String.valueOf(result));
operator = "";
} else if ("+-*%".contains(cmd)) {
num1 = Double.parseDouble(display.getText());
operator = cmd;
display.setText("");
} else {
display.setText(display.getText() + cmd);
}
}
WebApp/
├── index.html
├── login.html
├── insert.html
├── WEB-INF/
│ └── web.xml
└── src/
├── LoginServlet.java
├── InsertServlet.java
├── SelectServlet.java
Login.html
<!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:
Insert.html
<!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:
LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"system", "system");
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE
username=? AND password=?");
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
out.println("<h2>Welcome, " + user + "</h2>");
} else {
out.println("<h2>Invalid Credentials</h2>");
}
con.close();
} catch (Exception e) {
out.println(e);
}
}
}
InsertServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"system", "system");
PreparedStatement ps = con.prepareStatement("INSERT INTO users(name,email)
VALUES(?,?)");
ps.setString(1, name);
ps.setString(2, email);
int i = ps.executeUpdate();
if (i > 0) {
out.println("<h2>Record inserted successfully</h2>");
}
con.close();
} catch (Exception e) {
out.println(e);
}
}
}
SelectServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"system", "system");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
out.println("<h2>User Records:</h2>");
out.println("<table border='1'><tr><th>ID</th><th>Name</th><th>Email</th></tr>");
while (rs.next()) {
out.println("<tr><td>" + rs.getInt("id") + "</td><td>" +
rs.getString("name") + "</td><td>" + rs.getString("email") + "</td></tr>");
}
out.println("</table>");
con.close();
} catch (Exception e) {
out.println(e);
}
}
}
web.xml
<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>
<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:
--http://127.0.0.1:8080/apex/
--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)
);