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

Java Labmanual Complete LR23

The document contains multiple Java programming examples demonstrating various concepts such as class and object implementation, constructors, inheritance, method overloading and overriding, interfaces, abstract classes, exception handling, threading, and thread synchronization. Each section includes code snippets and expected outputs to illustrate the concepts effectively. The examples cover a wide range of fundamental programming principles in Java.

Uploaded by

riyazmd10001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views37 pages

Java Labmanual Complete LR23

The document contains multiple Java programming examples demonstrating various concepts such as class and object implementation, constructors, inheritance, method overloading and overriding, interfaces, abstract classes, exception handling, threading, and thread synchronization. Each section includes code snippets and expected outputs to illustrate the concepts effectively. The examples cover a wide range of fundamental programming principles in Java.

Uploaded by

riyazmd10001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

1. a) Write a Java sample program to implement class and object concepts.

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

// Main class to test the Student


public class Main {
public static void main(String[] args) {
// Creating an object of the Student class
Student student1 = new Student();

// Setting values directly (no constructor)


student1.name = "Alice";
student1.age = 20;
student1.grade = "A";

// Calling method on the object to display student information


student1.displayStudentInfo();

// Creating another student object and setting values


Student student2 = new Student();
student2.name = "Bob";
student2.age = 22;
student2.grade = "B";

// Calling method on the second student object to display info


student2.displayStudentInfo();
}
}

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

Student Name: Alice


Student Age: 20
Student Grade: A
Student Name: Bob
Student Age: 22
Student Grade: B
2.a) Write a Java program to illustrate the concept of Single level and Multi level Inheritance.
// Base class: Bank
class Bank {
// Property of the Bank class
String bankName;
// Constructor to initialize bank name
public Bank(String bankName) {
this.bankName = bankName;
}

// Method to display bank information


public void displayBankInfo() {
System.out.println("Bank Name: " + bankName);
}
}

// Single Level Inheritance: SavingsAccount is a subclass of Bank


class SavingsAccount extends Bank {
// Property of SavingsAccount class
double balance;

// Constructor to initialize SavingsAccount with balance and bank name


public SavingsAccount(String bankName, double balance) {
super(bankName); // Call the parent (Bank) constructor
this.balance = balance;
}

// Method to display savings account balance


public void displayBalance() {
System.out.println("Savings Account Balance: $" + balance);
}

// Method to deposit money into savings account


public void deposit(double amount) {
balance += amount;
System.out.println("Deposited $" + amount + " into Savings Account.");
}
}

// Multi-Level Inheritance: CheckingAccount is a subclass of SavingsAccount


class CheckingAccount extends SavingsAccount {
// Property of CheckingAccount class
double overdraftLimit;

// Constructor to initialize CheckingAccount with overdraft limit and balance


public CheckingAccount(String bankName, double balance, double overdraftLimit) {
super(bankName, balance); // Call the parent (SavingsAccount) constructor
this.overdraftLimit = overdraftLimit;
}

// Method to display checking account info including overdraft limit


public void displayCheckingInfo() {
System.out.println("Checking Account Balance: $" + balance);
System.out.println("Overdraft Limit: $" + overdraftLimit);
}

// Method to withdraw money from checking account (with overdraft protection)


public void withdraw(double amount) {
if (amount <= balance + overdraftLimit) {
balance -= amount;
System.out.println("Withdrew $" + amount + " from Checking Account.");
} else {
System.out.println("Insufficient funds. Cannot withdraw more than available balance + overdraft limit.");
}
}
}

// Main class to test the inheritance


public class Main2 {
public static void main(String[] args) {
// Single level inheritance: SavingsAccount object
System.out.println("---- Savings Account ----");
SavingsAccount savings = new SavingsAccount("City Bank", 5000);
savings.displayBankInfo(); // Inherited from Bank
savings.displayBalance(); // Own method
savings.deposit(1500); // Own method
savings.displayBalance(); // Check updated balance

// Multi-level inheritance: CheckingAccount object


System.out.println("\n---- Checking Account ----");
CheckingAccount checking = new CheckingAccount("City Bank", 3000, 500);
checking.displayBankInfo(); // Inherited from Bank
checking.displayCheckingInfo(); // Own method
checking.withdraw(3500); // Withdraw with overdraft
checking.displayCheckingInfo(); // Check updated info
}
}

Output:

Bank Name: City Bank


Savings Account Balance: $5000.0
Deposited $1500.0 into Savings Account.
Savings Account Balance: $6500.0
Bank Name: City Bank
Checking Account Balance:
$3000.0 Overdraft Limit:
$500.0
Withdrew $3500.0 from Checking
Account. Checking Account
Balance: $-500.0
Overdraft Limit: $500.0
2.b) Write a Java program to illustrate the concept of class with method overloading and method
overriding
Method Overloading Program
import java.util.Scanner;

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

Shape shape = new Shape();


Scanner scanner = new Scanner(System.in);
System.out.print("radius of the circle: ");
double radius = scanner.nextDouble();
double circleArea = shape.calculateArea(radius);
System.out.printf("Area of the circle: %.2f\n", circleArea);
System.out.print("length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("width of the rectangle: ");
double width = scanner.nextDouble();
double rectangleArea = shape.calculateArea(length, width);
System.out.printf("Area of the rectangle: %.2f\n", rectangleArea);
System.out.print("side length of the square: ");
int side = scanner.nextInt();
double squareArea = shape.calculateArea(side);
System.out.printf("Area of the square: %.2f\n", squareArea);
scanner.close();
}
}

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

ScientificCalculator scientificCalculator = new ScientificCalculator();


System.out.println("a*b: " + scientificCalculator.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);

System.out.println("Addition: " + result1);


System.out.println("Subtraction: " + result2);
System.out.println("Multiplication: " + result3);
System.out.println("Division: " + result4);

}
}

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

class FindArea extends CalcArea {


@Override
double triangleArea(double b, double h) {
return 0.5 * b * h;
}
@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 (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();

System.out.println("Area of triangle : "+area.triangleArea(arg1, arg2));


System.out.println("Area of rectangle : "+ area.rectangleArea(arg1, arg2));
System.out.println("Area of square : "+area.squareArea(arg1));
System.out.println("Area of circle : "+area.circleArea(arg2));
}
}
// Write all the classes with definitions

Output:

Area·of·triangle·:·7.529400000000001
Area·of·rectangle·:·15.058800000000002
Area·of·square·:·12.6736
Area·of·circle·:·56.18370600000001

3 b) Write a Java program to implement the concept of exception handling.


import java.util.*;
class CheckWeight {

// Method to validate the weight and throw the custom exception


public static void validateWeight(int weight) throws InvalidWeight {
if (weight > 100) {
throw new InvalidWeight("Exception caught: "+weight+" is invalid
weight");
}
else
System.out.println(weight+" is the valid weight");
}

// Main method to test the validWeight method


public static void main(String[] args) {

// Create an instance of CheckWeight class


CheckWeight Ck=new CheckWeight();
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the weight
System.out.print("Enter weight: ");
// Read the weight from the user
int weight = scanner.nextInt();
// Call the validWeight method and handle the custom exception
try {
// Validate the weight
validateWeight(weight);
}
// Catch and handle the InvalidWeight exception
catch (InvalidWeight e) {

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.

// Using Thread class


class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread (Thread Class): " + i);
try {
Thread.sleep(500); // Sleep for 500ms
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}

// Using Runnable interface


class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread (Runnable Interface): " + i);
try {
Thread.sleep(500); // Sleep for 500ms
} catch (InterruptedException e) {
System.out.println("Runnable interrupted.");
}
}
}
}

public class ThreadingExample {


public static void main(String[] args) {
// Using Thread class
MyThread thread1 = new MyThread();
// Using Runnable interface
MyRunnable runnable = new MyRunnable();
Thread thread2 = new Thread(runnable);

// Start both threads


thread1.start();
thread2.start();
}
}

Output:

Thread (Thread Class): 1


Thread (Runnable Interface): 1
Thread (Thread Class): 2
Thread (Runnable Interface): 2
Thread (Thread Class): 3
Thread (Runnable Interface): 3
Thread (Thread Class): 4
Thread (Runnable Interface): 4
Thread (Thread Class): 5
Thread (Runnable Interface): 5

4. Write a Java program to illustrate the concept of Thread synchronization.


package q18198;
import java.util.Scanner;

class TablePrinter implements Runnable {


private int tableNumber;

public TablePrinter(int tableNumber) {


this.tableNumber = tableNumber;
}

//write your code....


public void run() {
try {
for (int i = 1; i <= 10; i++) {
// Print the multiplication result for this table number
System.out.println( + tableNumber + " * " + i + " = " + (tableNumber * i));
// Sleep for 100 milliseconds to add a small delay
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of tables:");
int numTables = scanner.nextInt();
Thread[] threads = new Thread[numTables];

//write your code....


for (int i = 1; i <= numTables; i++) {
TablePrinter tablePrinter = new TablePrinter(i); // Create a new TablePrinter for table
i
threads[i - 1] = new Thread(tablePrinter); // Assign the thread to the array
threads[i - 1].start(); // Start the thread
}
try {
for (int i = 0; i < numTables; i++) {
threads[i].join(); // Wait for each thread to finish
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted: " + e.getMessage());
}
scanner.close();

}
}

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

// Print the current number


System.out.println(num);

// Add the current number to the sum


sum += num;
}
System.out.println(sum);
}
}
Output:
123456
1
2
3
4
5
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 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);

// Check if the input file exists


if (!inputFile.exists()) {
System.out.println("No such file");
return;
}

fileInputStream = new FileInputStream(inputFile);

// Create FileOutputStream to write data to the output file


fileOutputStream = new FileOutputStream(outputFile);

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

// Close the output file stream


}
catch (IOException e) {
System.out.println("No such file");
} finally {
try {
// Close the streams to release resources
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
System.err.println("Error while closing streams: " + e.getMessage());
}
}
}
}

Output:
file name:hello.txt
Contents of the output file:
Hello IT Department

7. a) Write a Java applet program to implement Color and Graphics class

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.*;

public class SimpleAWTExample extends Frame implements ActionListener {

// Components
Label label;
Button button;

// Constructor to set up the UI


public SimpleAWTExample() {
// Set frame title
setTitle("AWT Example");

// Set layout
setLayout(new FlowLayout());

// Initialize components
label = new Label("Click the button");
button = new Button("Click Me");

// Add action listener to button


button.addActionListener(this);

// Add components to frame


add(label);
add(button);

// Set size and make it visible


setSize(300, 150);
setVisible(true);

// Window close handler


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose(); // Close the window
}
});
}

// Handle button click event


public void actionPerformed(ActionEvent e) {
label.setText("Button clicked!");
}

// Main method
public static void main(String[] args) {
new SimpleAWTExample();
}
}

8. Write a java Applet program to implement Mouse and Key events

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/* <applet code="MouseKeyApplet" width=400 height=300></applet> */

public class MouseKeyApplet extends Applet implements MouseListener,


MouseMotionListener, KeyListener {
String message = "";
int mouseX = 0, mouseY = 0;

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
setBackground(Color.lightGray);
setFocusable(true); // Important for key events
}

public void paint(Graphics g) {


g.drawString(message, mouseX, mouseY);
}

// MouseListener methods
public void mouseClicked(MouseEvent e) {
message = "Mouse Clicked";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

public void mouseEntered(MouseEvent e) {


message = "Mouse Entered";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

public void mouseExited(MouseEvent e) {


message = "Mouse Exited";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

public void mousePressed(MouseEvent e) {


message = "Mouse Pressed";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

public void mouseReleased(MouseEvent e) {


message = "Mouse Released";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

// MouseMotionListener methods
public void mouseDragged(MouseEvent e) {
message = "Mouse Dragged";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

public void mouseMoved(MouseEvent e) {


message = "Mouse Moved";
mouseX = e.getX();
mouseY = e.getY();
repaint();
}

// KeyListener methods
public void keyPressed(KeyEvent e) {
message = "Key Pressed: " + e.getKeyChar();
repaint();
}

public void keyReleased(KeyEvent e) {


message = "Key Released: " + e.getKeyChar();
repaint();
}

public void keyTyped(KeyEvent e) {


message = "Key Typed: " + e.getKeyChar();
repaint();
}
}

To Run the Applet


1. Save the file as `MouseKeyApplet.java`.
2. Compile: `javac MouseKeyApplet.java`
3. Run using an applet viewer:

appletviewer MouseKeyApplet.java
9. Write a Java applet program to implement Adapter classes

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/* <applet code="MouseAdapterExample" width=400 height=300></applet> */

public class MouseAdapterExample extends Applet {

String message = "";


int x = 0, y = 0;

public void init() {


setBackground(Color.white);

// Attach custom mouse adapter


addMouseListener(new MyMouseAdapter());
}

public void paint(Graphics g) {


g.drawString(message, x, y);
}

// Custom adapter class


class MyMouseAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
message = "Mouse Clicked at (" + x + ", " + y + ")";
repaint();
}
}
}

1. Save as `MouseAdapterExample.java`
2. Compile: `javac MouseAdapterExample.java`
3. Run with: `appletviewer MouseAdapterExample.java
OutPut:

10. Write a JDBC program to implement CURD operation


/*Create a table in database as follows
create table students(id number(20) primary key, name varchar(20),grade number)/*

import java.sql.*;
import java.util.Scanner;

public class StudentJDBCApp {


static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
static final String USER = "system";
static final String PASS = "system"; // Replace with your MySQL password

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

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:

C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>javac -cp .;lib\ojdbc14.jar


StudentJDBCApp.java

To run the code:


C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>java -cp .;lib\ojdbc14.jar
StudentJDBCApp

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 class SimpleCalculator extends Frame implements ActionListener {


TextField display;
String operator = "";
double num1 = 0, num2 = 0;

public SimpleCalculator() {
setTitle("Simple Calculator");
setLayout(new BorderLayout());

// Text field at the top


display = new TextField();
add(display, BorderLayout.NORTH);

// Panel with buttons


Panel panel = new Panel();
panel.setLayout(new GridLayout(4, 4, 5, 5));

String[] buttons = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", "%", "=", "C"
};

for (String b : buttons) {


Button btn = new Button(b);
btn.addActionListener(this);
panel.add(btn);
}

add(panel, BorderLayout.CENTER);

setSize(300, 300);
setVisible(true);

// Close window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}

public void actionPerformed(ActionEvent e) {


String cmd = e.getActionCommand();

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

public static void main(String[] args) {


new SimpleCalculator();
}
}

12. Write Servlet application for following


i. Html & Servlet Communication
ii. Select record from database
iii. Application for login page
iv. Insert record into database

Structure of the Project:

WebApp/
├── index.html
├── login.html
├── insert.html
├── WEB-INF/
│ └── web.xml
└── src/
├── LoginServlet.java
├── InsertServlet.java
├── SelectServlet.java

1. index.html (HTML to Servlet communication)


<!DOCTYPE html>
<html>
<head><title>HTML Servlet Communication</title></head>
<body>
<h2>Welcome Page</h2>
<form action="login.html">
<input type="submit" value="Login">
</form>
<form action="insert.html">
<input type="submit" value="Insert Record">
</form>
<form action="select" method="get">
<input type="submit" value="View Records">
</form>
</body>
</html>
Output:

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.*;

public class LoginServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String user = request.getParameter("username");


String pass = request.getParameter("password");

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.*;

public class InsertServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String name = request.getParameter("name");


String email = request.getParameter("email");

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.*;

public class SelectServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

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

-- Step 2: Create a sequence for generating unique IDs


CREATE SEQUENCE users_seq
START WITH 1
INCREMENT BY 1
NOCACHE;

-- Step 3: Create a trigger to assign sequence value to ID


CREATE OR REPLACE TRIGGER users_trigger
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
SELECT users_seq.NEXTVAL INTO :new.id FROM dual;
END;
/

insert into users values(1,'naga','naga','naga','[email protected]')

select * from users

You might also like