0% found this document useful (0 votes)
20 views44 pages

Java Lab File

All Java Practicals of sem 5

Uploaded by

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

Java Lab File

All Java Practicals of sem 5

Uploaded by

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

Practical -2

➢ Aim: Create a Java Program to implement stack and Queue concepts.

SOURCE CODE
class Stack {
private int maxSize;
private int top;
private int[] stackArray;

// Constructor to initialize stack


public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}

// Push method to add elements to the stack


public void push(int value) {
if (isFull()) {
System.out.println("Stack is full. Cannot push " + value);
} else {
stackArray[++top] = value;
System.out.println("Pushed " + value + " to the stack.");
}
}

// Pop method to remove elements from the stack


public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty. Nothing to pop.");
return -1;
} else {
int value = stackArray[top--];
System.out.println("Popped " + value + " from the stack.");
return value;
}
}

// Peek method to check the top element


public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty.");
return -1;
} else {
return stackArray[top];
}
}
// Method to check if the stack is empty
public boolean isEmpty() {
return (top == -1);
}

// Method to check if the stack is full


public boolean isFull() {
return (top == maxSize - 1);
}
}
// Queue implementation in Java
class Queue {
private int maxSize;
private int front;
private int rear;
private int[] queueArray;
private int nItems;

// Constructor to initialize queue


public Queue(int size) {
maxSize = size;
queueArray = new int[maxSize];
front = 0;
rear = -1;
nItems = 0;
}

// Insert method to add elements to the queue


public void insert(int value) {
if (isFull()) {
System.out.println("Queue is full. Cannot insert " + value);
} else {
if (rear == maxSize - 1) {
rear = -1; // Circular queue wrap-around
}
queueArray[++rear] = value;
nItems++;
System.out.println("Inserted " + value + " to the queue.");
}
}

// Remove method to remove elements from the queue


public int remove() {
if (isEmpty()) {
System.out.println("Queue is empty. Nothing to remove.");
return -1;
} else {
int value = queueArray[front++];
if (front == maxSize) {
front = 0; // Circular queue wrap-around
}
nItems--;
System.out.println("Removed " + value + " from the queue.");
return value;
}
}

// Peek method to check the front element


public int peekFront() {
if (isEmpty()) {
System.out.println("Queue is empty.");
return -1;
} else {
return queueArray[front];
}
}

// Method to check if the queue is empty


public boolean isEmpty() {
return (nItems == 0);
}

// Method to check if the queue is full


public boolean isFull() {
return (nItems == maxSize);
}

// Method to get the size of the queue


public int size() {
return nItems;
}
}
public class Main {
public static void main(String[] args) {
// Stack demonstration
System.out.println("Stack Operations:");
Stack stack = new Stack(5);
stack.push(10);
stack.push(20);
stack.push(30);

System.out.println("Top element is: " + stack.peek());


stack.push(40);
stack.push(50);
if(stack.isFull()){
System.out.println("Stack is Full");
}
stack.pop();
stack.pop();
stack.pop();
stack.pop(); // Trying to pop from an empty stack
System.out.println("Top element is: " + stack.peek());
System.out.println("\nQueue Operations:");
// Queue demonstration
Queue queue = new Queue(5);
queue.insert(100);
queue.insert(200);
queue.insert(300);
System.out.println("Front element is: " + queue.peekFront());
queue.remove();
queue.remove();
queue.remove();
queue.remove(); // Trying to remove from an empty queue
}
}

OUTPUT
Practical -4
➢ Aim: WAP to implement the concept of String and String Buffer.

SOURCE CODE
public class StringVsStringBuffer {
public static void main(String[] args) {

String str1 = "Hello";


System.out.println("Original String: " + str1);

str1 = str1 + " World!";


System.out.println("String after concatenation: " + str1);

String substring = str1.substring(0, 5);


System.out.println("Substring from String: " + substring);

int strLength = str1.length();


System.out.println("Length of String: " + strLength);

System.out.println("\n--- Using StringBuffer ---\n");

StringBuffer buffer = new StringBuffer("Hello");


System.out.println("Original StringBuffer: " + buffer);

buffer.append(" World!");
System.out.println("StringBuffer after append: " + buffer);

buffer.insert(5, ",");
System.out.println("StringBuffer after insert: " + buffer);

buffer.reverse();
System.out.println("StringBuffer after reverse: " + buffer);

buffer.reverse();
System.out.println("StringBuffer after re-reverse: " + buffer);

buffer.replace(0, 5, "Hi");
System.out.println("StringBuffer after replace: " + buffer);
System.out.println("Length of StringBuffer: " + buffer.length());
System.out.println("Capacity of StringBuffer: " + buffer.capacity());
}
}

OUTPUT
Practical -5
➢ Aim: WAP in java to implement the concept of Exception Handling with five
Keywords: -TRY, CATCH, FINALLY, THROW and THROWS.

SOURCE CODE
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
class InvalidDepositException extends Exception {
public InvalidDepositException(String message) {
super(message);
}
}
class BankAccount {
private double balance;

public BankAccount(double balance) {


this.balance = balance;
}
public void deposit(double amount) throws InvalidDepositException {
if (amount <= 0) {
// Throwing an exception for invalid deposit
throw new InvalidDepositException("Deposit amount must be positive.");
}
balance += amount;
System.out.println("Deposited: " + amount + ". New balance: " + balance);
}

// Method to withdraw money, throws InsufficientBalanceException for insufficient funds


public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
// Throwing an exception for insufficient balance
throw new InsufficientBalanceException("Insufficient balance. You cannot withdraw " +
amount);
}
balance -= amount;
System.out.println("Withdrew: " + amount + ". Remaining balance: " + balance);
}
// Method to check the balance
public double getBalance() {
return balance;
}
}
public class BankSystem {
public static void main(String[] args) {
BankAccount account = new BankAccount(5000); // Initial balance of 5000
try {
// Trying to deposit money
System.out.println("Depositing $2000...");
account.deposit(2000);

// Trying to withdraw money


System.out.println("Withdrawing $1000...");
account.withdraw(1000);

// Trying to withdraw an amount larger than the current balance


System.out.println("Withdrawing $7000...");
account.withdraw(7000); // This will throw InsufficientBalanceException

} catch (InvalidDepositException | InsufficientBalanceException e) {


// Catching both custom exceptions
System.out.println("Exception: " + e.getMessage());
} finally {
// Finally block that always executes
System.out.println("Transaction Completed. Current Balance: $" + account.getBalance());
}
// Another example to demonstrate a thrown exception manually
try {
System.out.println("\nManually throwing an exception...");
// Throwing an exception manually using throw keyword
throw new ArithmeticException("Manually triggered arithmetic exception");
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally {
System.out.println("This finally block executes after manual exception handling.");
}
}
}

OUTPUT
Practical -6
➢ Aim: Write a java program to show the concept of multithreading.

SOURCE CODE
class SAITM {
private int availableSeats;

// Constructor to initialize available seats


public SAITM(int seats) {
this.availableSeats = seats;
}

// Synchronized method to handle admission requests

public synchronized void applyForAdmission(String studentName) {


if (availableSeats > 0) {
System.out.println(studentName + " applied for admission in AIML.");
availableSeats--;
System.out.println("Admission granted to " + studentName + ". Remaining seats: " +
availableSeats);
} else {
System.out.println("Sorry, " + studentName + ". No seats are available in AIML.");
}
}
}

// Admission class implementing Runnable to create admission threads


class Admission implements Runnable {
private SAITM saitm;
private String studentName;

// Constructor to initialize SAITM and student's name


public Admission(SAITM saitm, String studentName) {
this.saitm = saitm;
this.studentName = studentName;
}

@Override
public void run() {
// Apply for admission
saitm.applyForAdmission(studentName);
}
}
public class CollegeAdmissionSystem {
public static void main(String[] args) {

SAITM saitm = new SAITM(3);

Thread student1 = new Thread(new Admission(saitm, "Vijay"));


Thread student2 = new Thread(new Admission(saitm, "Kirti"));
Thread student3 = new Thread(new Admission(saitm, "Charlie"));
Thread student4 = new Thread(new Admission(saitm, "Keshav"));

student1.start();
student2.start();
student3.start();
student4.start();
}
}

OUTPUT
Practical -3
➢ Aim: Write a java package to show dynamic polymorphism
and interfaces.

SOURCE CODE
package polymorphism; // package polymorphism declared for all classes

public interface Greeting {


void greeting();
}

public class America implements Greeting {


public void greeting() {
System.out.println("Hello");
}
}

public class French implements Greeting {


//Overiding the Greet function
public void greeting() {
System.out.println("Bonjour");
}
}

public class India implements Greeting {


public void greeting() {
System.out.println("Namaste");
}
}

public class Japan implements Greeting{


public void greeting() {
System.out.println("konnichiwa");
}
}

public class Spanish implements Greeting {

public void greeting() {


System.out.println("Hola");
}
}
package polymorphism;

public class Polymorphism {


public static void main(String[] args) {
Greeting greet;
// The greeting function will Dynamically get updated on the call of the Particualr class greet
function.
greet = new India();
greet.greeting();
greet = new Spanish();
greet.greeting();
greet = new America();
greet.greeting();
greet = new French();
greet.greeting();
greet = new Japan();
greet.greeting();
}
}

OUTPUT
Practical -8
➢ Aim: WAP in Java to create a Calculator using AWT.

SOURCE CODE
public class myCalculator extends javax.swing.JFrame {
double num1=0,num2=0;
String operator=null;
/**
* Creates new form myCalculator
*/
public myCalculator() {
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jButton3 = new javax.swing.JButton();


jButton4 = new javax.swing.JButton();
jButton15 = new javax.swing.JButton();
jButton16 = new javax.swing.JButton();
jButton17 = new javax.swing.JButton();
jButton18 = new javax.swing.JButton();
jButton20 = new javax.swing.JButton();
jButton21 = new javax.swing.JButton();
jButton23 = new javax.swing.JButton();
jButton24 = new javax.swing.JButton();
jButton19 = new javax.swing.JButton();
jButton22 = new javax.swing.JButton();
jButton28 = new javax.swing.JButton();
jButton30 = new javax.swing.JButton();
jButton31 = new javax.swing.JButton();
jButton32 = new javax.swing.JButton();
jButton33 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
t1 = new javax.swing.JTextField();
b7 = new javax.swing.JButton();
bdiv = new javax.swing.JButton();
b8 = new javax.swing.JButton();
b9 = new javax.swing.JButton();
bmul = new javax.swing.JButton();
b5 = new javax.swing.JButton();
b6 = new javax.swing.JButton();
b4 = new javax.swing.JButton();
bsub = new javax.swing.JButton();
b2 = new javax.swing.JButton();
b3 = new javax.swing.JButton();
b1 = new javax.swing.JButton();
badd = new javax.swing.JButton();
bdot = new javax.swing.JButton();
bequal = new javax.swing.JButton();
b0 = new javax.swing.JButton();
bclear = new javax.swing.JButton();
bback = new javax.swing.JButton();

jButton3.setText("jButton1");

jButton4.setText("jButton1");

jButton15.setText("jButton1");

jButton16.setText("jButton1");

jButton17.setText("jButton1");

jButton18.setText("jButton1");

jButton20.setText("-");

jButton21.setText("2");

jButton23.setText("3");

jButton24.setText("1");

jButton19.setText("jButton1");

jButton22.setText("jButton1");

jButton28.setText("1");

jButton30.setText("0");

jButton31.setText("+");

jButton32.setText(".");

jButton33.setText("=");

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N


jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("My Calculator");

t1.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N


t1.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

b7.setText("7");
b7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b7ActionPerformed(evt);
}
});

bdiv.setText("/");
bdiv.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bdivActionPerformed(evt);
}
});

b8.setText("8");
b8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b8ActionPerformed(evt);
}
});

b9.setText("9");
b9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b9ActionPerformed(evt);
}
});

bmul.setText("x");
bmul.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bmulActionPerformed(evt);
}
});

b5.setText("5");
b5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b5ActionPerformed(evt);
}
});

b6.setText("6");
b6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b6ActionPerformed(evt);
}
});

b4.setText("4");
b4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b4ActionPerformed(evt);
}
});

bsub.setText("-");
bsub.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bsubActionPerformed(evt);
}
});

b2.setText("2");
b2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b2ActionPerformed(evt);
}
});

b3.setText("3");
b3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b3ActionPerformed(evt);
}
});

b1.setText("1");
b1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b1ActionPerformed(evt);
}
});

badd.setText("+");
badd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
baddActionPerformed(evt);
}
});

bdot.setText(".");
bdot.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bdotActionPerformed(evt);
}
});
bequal.setText("=");
bequal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bequalActionPerformed(evt);
}
});

b0.setText("0");
b0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b0ActionPerformed(evt);
}
});

bclear.setText("Clear");
bclear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bclearActionPerformed(evt);
}
});

bback.setText("Back");
bback.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bbackActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());


getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(t1)
.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(bclear, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING,
layout.createSequentialGroup()
.addComponent(b0, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(bdot, javax.swing.GroupLayout.PREFERRED_SIZE, 66,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(bequal, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(badd, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(bback, javax.swing.GroupLayout.PREFERRED_SIZE, 148,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(b4, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b5, javax.swing.GroupLayout.PREFERRED_SIZE, 66,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b6, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(bmul, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(b7, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b8, javax.swing.GroupLayout.PREFERRED_SIZE, 66,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b9, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(bdiv, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(b1, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b2, javax.swing.GroupLayout.PREFERRED_SIZE, 66,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b3, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(bsub, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(12, 12, 12))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 35,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b7, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b8, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b9, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bdiv, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b4, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b5, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b6, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bmul, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b1, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b2, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b3, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bsub, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bdot, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bequal, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(badd, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b0, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bback, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bclear, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void bmulActionPerformed(java.awt.event.ActionEvent evt) {


num1=Double.parseDouble(t1.getText());
t1.setText("");

operator="*";
}

private void b7ActionPerformed(java.awt.event.ActionEvent evt) {

t1.setText(t1.getText()+"7");
}

private void b8ActionPerformed(java.awt.event.ActionEvent evt) {


t1.setText(t1.getText()+"8");
}

private void b9ActionPerformed(java.awt.event.ActionEvent evt) {


t1.setText(t1.getText()+"9");
}

private void b4ActionPerformed(java.awt.event.ActionEvent evt) {


t1.setText(t1.getText()+"4");
}

private void b5ActionPerformed(java.awt.event.ActionEvent evt) {


t1.setText(t1.getText()+"5");
}

private void b6ActionPerformed(java.awt.event.ActionEvent evt) {


t1.setText(t1.getText()+"6");
}

private void b1ActionPerformed(java.awt.event.ActionEvent evt) {


t1.setText(t1.getText()+"1");
}

private void b2ActionPerformed(java.awt.event.ActionEvent evt) {


t1.setText(t1.getText()+"2");
}

private void b3ActionPerformed(java.awt.event.ActionEvent evt) {


t1.setText(t1.getText()+"3");
}

private void b0ActionPerformed(java.awt.event.ActionEvent evt) {


t1.setText(t1.getText()+"0");
}

private void bdotActionPerformed(java.awt.event.ActionEvent evt) {


t1.setText(t1.getText()+".");
}

private void bdivActionPerformed(java.awt.event.ActionEvent evt) {


num1=Double.parseDouble(t1.getText());
t1.setText("");

operator="/";
}

private void bsubActionPerformed(java.awt.event.ActionEvent evt) {


num1=Double.parseDouble(t1.getText());
t1.setText("");

operator="-";
}

private void baddActionPerformed(java.awt.event.ActionEvent evt) {


num1=Double.parseDouble(t1.getText());
t1.setText("");

operator="+";
}

private void bequalActionPerformed(java.awt.event.ActionEvent evt) {

num2 = Double.parseDouble(t1.getText());

double ans=0;

if(operator =="+")
{
ans= num1 + num2;
}
if(operator =="*")
{
ans= num1 * num2;
}
if(operator =="-")
{
ans= num1 - num2;
}
if(operator =="/")
{
ans= num1 / num2;
}

t1.setText(""+ans);
operator=null;
}

private void bclearActionPerformed(java.awt.event.ActionEvent evt) {

t1.setText("");
}

private void bbackActionPerformed(java.awt.event.ActionEvent evt) {

String str= t1.getText();

t1.setText(str.substring(0,str.length()-1));

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(myCalculator.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(myCalculator.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(myCalculator.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(myCalculator.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
}
//</editor-fold>

/* Create and display the form */


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new myCalculator().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton b0;
private javax.swing.JButton b1;
private javax.swing.JButton b2;
private javax.swing.JButton b3;
private javax.swing.JButton b4;
private javax.swing.JButton b5;
private javax.swing.JButton b6;
private javax.swing.JButton b7;
private javax.swing.JButton b8;
private javax.swing.JButton b9;
private javax.swing.JButton badd;
private javax.swing.JButton bback;
private javax.swing.JButton bclear;
private javax.swing.JButton bdiv;
private javax.swing.JButton bdot;
private javax.swing.JButton bequal;
private javax.swing.JButton bmul;
private javax.swing.JButton bsub;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton17;
private javax.swing.JButton jButton18;
private javax.swing.JButton jButton19;
private javax.swing.JButton jButton20;
private javax.swing.JButton jButton21;
private javax.swing.JButton jButton22;
private javax.swing.JButton jButton23;
private javax.swing.JButton jButton24;
private javax.swing.JButton jButton28;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton30;
private javax.swing.JButton jButton31;
private javax.swing.JButton jButton32;
private javax.swing.JButton jButton33;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField t1;
// End of variables declaration
}

OUTPUT
Practical -9
➢ Aim: Create an editor like MS-word using swings.

SOURCE CODE
package ms.word.application;

import java.awt.Font;
import javax.swing.*;
import java.awt.event.*;
import java.awt.print.PrinterException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.filechooser.FileNameExtensionFilter;

public class MSWordApplication extends JFrame implements ActionListener {

JMenuBar menubar = new JMenuBar();


JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenu view = new JMenu("View"); // New View menu
JMenu help = new JMenu("Help");

JMenuItem newFile = new JMenuItem("New");


JMenuItem openFile = new JMenuItem("Open");
JMenuItem saveFile = new JMenuItem("Save");
JMenuItem print = new JMenuItem("Print");
JMenuItem exit = new JMenuItem("Exit");

JMenuItem cut = new JMenuItem("Cut");


JMenuItem copy = new JMenuItem("Copy");
JMenuItem paste = new JMenuItem("Paste");
JMenuItem selectall = new JMenuItem("Select All");

JMenuItem zoomIn = new JMenuItem("Zoom In"); // Zoom In menu item


JMenuItem zoomOut = new JMenuItem("Zoom Out"); // Zoom Out menu item

JMenuItem about = new JMenuItem("About");

JTextArea textArea = new JTextArea();

MSWordApplication() {
setTitle("MS Word Application");
setBounds(100, 100, 800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

ImageIcon icon = new ImageIcon(getClass().getResource("icon.jpg"));


setIconImage(icon.getImage());

setJMenuBar(menubar);
menubar.add(file);
menubar.add(edit);
menubar.add(view); // Add View menu to menu bar
menubar.add(help);

file.add(newFile);
file.add(openFile);
file.add(saveFile);
file.add(print);
file.add(exit);

edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(selectall);

view.add(zoomIn); // Add Zoom In to View menu


view.add(zoomOut); // Add Zoom Out to View menu
help.add(about);

JScrollPane scrollpane = new JScrollPane(textArea);


add(scrollpane);
scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollpane.setBorder(BorderFactory.createEmptyBorder());
textArea.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);

newFile.addActionListener(this);
openFile.addActionListener(this);
saveFile.addActionListener(this);
print.addActionListener(this);
exit.addActionListener(this);
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectall.addActionListener(this);
zoomIn.addActionListener(this); // Add action listener for Zoom In
zoomOut.addActionListener(this); // Add action listener for Zoom Out
about.addActionListener(this);

newFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
KeyEvent.CTRL_DOWN_MASK));
openFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
KeyEvent.CTRL_DOWN_MASK));
saveFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
KeyEvent.CTRL_DOWN_MASK));
print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
KeyEvent.CTRL_DOWN_MASK));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
KeyEvent.CTRL_DOWN_MASK));
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
KeyEvent.CTRL_DOWN_MASK));
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
KeyEvent.CTRL_DOWN_MASK));
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
KeyEvent.CTRL_DOWN_MASK));
selectall.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
KeyEvent.CTRL_DOWN_MASK));
zoomIn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS,
KeyEvent.CTRL_DOWN_MASK));
zoomOut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS,
KeyEvent.CTRL_DOWN_MASK));
about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_J,
KeyEvent.CTRL_DOWN_MASK));
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("New")) {
textArea.setText(null);
} else if (e.getActionCommand().equalsIgnoreCase("Open")) {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter textFilter = new FileNameExtensionFilter("Only Text Files(.txt)",
"txt");
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addChoosableFileFilter(textFilter);

int action = fileChooser.showOpenDialog(null);

if (action != JFileChooser.APPROVE_OPTION) {
return;
} else {
try {
BufferedReader reader = new BufferedReader(new
FileReader(fileChooser.getSelectedFile()));
textArea.read(reader, null);
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} else if (e.getActionCommand().equalsIgnoreCase("Save")) {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter textFilter = new FileNameExtensionFilter("Only Text Files(.txt)",
"txt");
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addChoosableFileFilter(textFilter);

int action = fileChooser.showSaveDialog(null);


if (action != JFileChooser.APPROVE_OPTION) {
return;
} else {
String fileName = fileChooser.getSelectedFile().getAbsolutePath();
if (!fileName.contains(".txt")) {
fileName = fileName + ".txt";
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
textArea.write(writer);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} else if (e.getActionCommand().equalsIgnoreCase("Print")) {
try {
textArea.print();
} catch (PrinterException ex) {
Logger.getLogger(MSWordApplication.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (e.getActionCommand().equalsIgnoreCase("Exit")) {
System.exit(0);
} else if (e.getActionCommand().equalsIgnoreCase("Cut")) {
textArea.cut();
} else if (e.getActionCommand().equalsIgnoreCase("Copy")) {
textArea.copy();
} else if (e.getActionCommand().equalsIgnoreCase("Paste")) {
textArea.paste();
} else if (e.getActionCommand().equalsIgnoreCase("Select All")) {
textArea.selectAll();
} else if (e.getActionCommand().equalsIgnoreCase("Zoom In")) {
Font currentFont = textArea.getFont();
textArea.setFont(new Font(currentFont.getFontName(), currentFont.getStyle(),
currentFont.getSize() + 2));
} else if (e.getActionCommand().equalsIgnoreCase("Zoom Out")) {
Font currentFont = textArea.getFont();
textArea.setFont(new Font(currentFont.getFontName(), currentFont.getStyle(),
Math.max(currentFont.getSize() - 2, 2)));
} else if (e.getActionCommand().equalsIgnoreCase("About")) {
new About().setVisible(true);
}
}

public static void main(String[] args) throws Exception {


UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new MSWordApplication().setVisible(true);
}
}

OUTPUT
Practical -1
➢ Aim: Write a program in java to print your details (Name, Rollno, Class, Sem,
College Name) and create the JAR file of this program with both outputs i.e.
.java and .jar.

SOURCE CODE
package studentdetails;

import java.util.Scanner;
public class StudentDetails {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input details from the user


System.out.print("Enter your Name: ");
String name = scanner.nextLine();

System.out.print("Enter your Roll Number: ");


String rollNo = scanner.nextLine();

System.out.print("Enter your Class: ");


String className = scanner.nextLine();

System.out.print("Enter your Semester: ");


String semester = scanner.nextLine();

System.out.print("Enter your College Name: ");


String collegeName = scanner.nextLine();

// Close the scanner


scanner.close();

// Print the details


System.out.println("\n--- Student Details ---");
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNo);
System.out.println("Class: " + className);
System.out.println("Semester: " + semester);
System.out.println("College Name: " + collegeName);

}
OUTPUT

(JAR FILE OUTPUT)


Practical -10
➢ Aim: Write a java program to show the concept of Collections.

SOURCE CODE
import java.util.*;

public class CollectionsExample {

public static void main(String[] args) {


// Queue example
Queue<Integer> queue = new LinkedList<>();
System.out.println("Queue Operations:");
queue.add(10);
queue.add(20);
queue.add(30);
System.out.println("Initial Queue: " + queue);
System.out.println("Peek (Front Element): " + queue.peek());
queue.poll();
System.out.println("After Poll: " + queue);
queue.offer(40);
System.out.println("After Offer (Add): " + queue);
System.out.println("Size of Queue: " + queue.size());
System.out.println("Queue contains 20? " + queue.contains(20)); // Check if element exists
queue.clear(); // Clear the queue
System.out.println("Queue after clear: " + queue);

System.out.println("\nSet Operations:");
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
System.out.println("Initial Set: " + set);
set.remove("Banana");
System.out.println("After Removing 'Banana': " + set);
System.out.println("Contains 'Apple'? " + set.contains("Apple"));
set.add("Date");
set.add("Elderberry");
System.out.println("Set after adding new elements: " + set);
System.out.println("Size of Set: " + set.size());
System.out.println("Is Set empty? " + set.isEmpty()); // Check if set is empty
set.clear(); // Clear the set
System.out.println("Set after clear: " + set);

System.out.println("\nMap Operations:");
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
System.out.println("Initial Map: " + map);
System.out.println("Get value for key 2: " + map.get(2));
map.remove(1);
System.out.println("Map after removing key 1: " + map);
System.out.println("Contains key 3? " + map.containsKey(3));
map.put(4, "Four");
map.put(5, "Five");
System.out.println("Final Map: " + map);
System.out.println("Size of Map: " + map.size());
System.out.println("Contains value 'Four'? " + map.containsValue("Four")); // Check if value
exists
map.replace(2, "Second"); // Replace value for a key
System.out.println("Map after replace operation on key 2: " + map);
}

OUTPUT
Practical -7
➢ Aim: WAP in java to create package in java.

SOURCE CODE
package shapes; //package shapes declared for all classes

public class Circle {


private double radius;

// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Method to calculate the area of the circle


public double getArea() {
return Math.PI * radius * radius;
}

// Method to calculate the perimeter (circumference) of the circle


public double getPerimeter() {
return 2 * Math.PI * radius;
}
}

public class Rectangle {


private double length;
private double width;

// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Method to calculate the area of the rectangle


public double getArea() {
return length * width;
}

// Method to calculate the perimeter of the rectangle


public double getPerimeter() {
return 2 * (length + width);
}
}
public class Square {
private double side;

// Constructor
public Square(double side) {
this.side = side;
}

// Method to calculate the area of the square


public double getArea() {
return side * side;
}

// Method to calculate the perimeter of the square


public double getPerimeter() {
return 4 * side;
}

package geometryapp;

import shapes.Circle;
import shapes.Rectangle;
import shapes.Square;

public class GeometryApp {


public static void main(String[] args) {
// Create objects for each shape
Circle circle = new Circle(5.0); // Circle with radius 5
Rectangle rectangle = new Rectangle(4.0, 6.0); // Rectangle with length 4 and width 6
Square square = new Square(4.0); // Square with side 4

// Calculate and display area and perimeter for each shape


System.out.println("Circle:");
System.out.println("Area: " + circle.getArea());
System.out.println("Perimeter: " + circle.getPerimeter());

System.out.println("\nRectangle:");
System.out.println("Area: " + rectangle.getArea());
System.out.println("Perimeter: " + rectangle.getPerimeter());

System.out.println("\nSquare:");
System.out.println("Area: " + square.getArea());
System.out.println("Perimeter: " + square.getPerimeter());
}

}
OUTPUT
Practical -2
➢ Aim: Create a registration page with JDBC connectivity.

SOURCE CODE
package dbconnect;

import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.*;

public class DBConnect {

public static void main(String[] args) throws SQLException {


try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","Pavitra@123");
System.out.println(con);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
}
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class StudentAppRedesigned extends JFrame implements ActionListener {


JTextField regnField, nameField, rollnoField, branchField, semesterField;
JButton addButton, deleteButton, updateButton, displayButton;
JTextArea displayArea;
Connection con;

public StudentAppRedesigned() {
// Set up JFrame
setTitle("Student Management System");
setSize(700, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));

// Top Panel with Title


JLabel titleLabel = new JLabel("Student Information Form", JLabel.CENTER);
titleLabel.setFont(new Font("Serif", Font.BOLD, 24));
add(titleLabel, BorderLayout.NORTH);
// Input Panel with Labels and TextFields
JPanel inputPanel = new JPanel(new GridBagLayout());
inputPanel.setBorder(BorderFactory.createTitledBorder("Student Details"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.anchor = GridBagConstraints.WEST;

Font labelFont = new Font("Serif", Font.BOLD, 16);

gbc.gridx = 0;
gbc.gridy = 0;
JLabel regnLabel = new JLabel("Registration No:");
regnLabel.setFont(labelFont);
inputPanel.add(regnLabel, gbc);

gbc.gridx = 1;
regnField = new JTextField(20);
regnField.setFont(new Font("Serif", Font.PLAIN, 16));
inputPanel.add(regnField, gbc);

gbc.gridx = 0;
gbc.gridy = 1;
JLabel nameLabel = new JLabel("Name:");
nameLabel.setFont(labelFont);
inputPanel.add(nameLabel, gbc);

gbc.gridx = 1;
nameField = new JTextField(20);
nameField.setFont(new Font("Serif", Font.PLAIN, 16));
inputPanel.add(nameField, gbc);

gbc.gridx = 0;
gbc.gridy = 2;
JLabel rollnoLabel = new JLabel("Roll No:");
rollnoLabel.setFont(labelFont);
inputPanel.add(rollnoLabel, gbc);

gbc.gridx = 1;
rollnoField = new JTextField(20);
rollnoField.setFont(new Font("Serif", Font.PLAIN, 16));
inputPanel.add(rollnoField, gbc);

gbc.gridx = 0;
gbc.gridy = 3;
JLabel branchLabel = new JLabel("Branch:");
branchLabel.setFont(labelFont);
inputPanel.add(branchLabel, gbc);

gbc.gridx = 1;
branchField = new JTextField(20);
branchField.setFont(new Font("Serif", Font.PLAIN, 16));
inputPanel.add(branchField, gbc);

gbc.gridx = 0;
gbc.gridy = 4;
JLabel semesterLabel = new JLabel("Semester:");
semesterLabel.setFont(labelFont);
inputPanel.add(semesterLabel, gbc);

gbc.gridx = 1;
semesterField = new JTextField(20);
semesterField.setFont(new Font("Serif", Font.PLAIN, 16));
inputPanel.add(semesterField, gbc);

add(inputPanel, BorderLayout.WEST);

// Button Panel
JPanel buttonPanel = new JPanel(new GridLayout(4, 1, 10, 10)); // 4 rows, 1 column, 10px
horizontal and vertical gap
addButton = new JButton("Add");
deleteButton = new JButton("Delete");
updateButton = new JButton("Update");
displayButton = new JButton("Display");

Font buttonFont = new Font("Serif", Font.BOLD, 14);

// Set the same size for all buttons


Dimension buttonSize = new Dimension(200, 40); // Set preferred size for buttons
addButton.setPreferredSize(buttonSize);
deleteButton.setPreferredSize(buttonSize);
updateButton.setPreferredSize(buttonSize);
displayButton.setPreferredSize(buttonSize);

addButton.setFont(buttonFont);
deleteButton.setFont(buttonFont);
updateButton.setFont(buttonFont);
displayButton.setFont(buttonFont);

// Add buttons to the panel


buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(updateButton);
buttonPanel.add(displayButton);
add(buttonPanel, BorderLayout.CENTER);

// Display Area
displayArea = new JTextArea(10, 50);
displayArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
displayArea.setEditable(false);
add(new JScrollPane(displayArea), BorderLayout.SOUTH);
// Add Action Listeners
addButton.addActionListener(this);
deleteButton.addActionListener(this);
updateButton.addActionListener(this);
displayButton.addActionListener(this);

// Initialize Database Connection


try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/StudentDB", "root",
"Pavitra@123");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Database Connection Failed: " + e.getMessage());
}
}

@Override
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == addButton) {
String query = "INSERT INTO Student (registration_no, name, rollno, branch, semester)
VALUES (?, ?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, Integer.parseInt(regnField.getText()));
ps.setString(2, nameField.getText());
ps.setString(3, rollnoField.getText());
ps.setString(4, branchField.getText());
ps.setInt(5, Integer.parseInt(semesterField.getText()));
ps.executeUpdate();
JOptionPane.showMessageDialog(this, "Student Added Successfully!");
} else if (e.getSource() == deleteButton) {
String query = "DELETE FROM Student WHERE registration_no = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, Integer.parseInt(regnField.getText()));
ps.executeUpdate();
JOptionPane.showMessageDialog(this, "Student Deleted Successfully!");
} else if (e.getSource() == updateButton) {
String query = "UPDATE Student SET name = ?, rollno = ?, branch = ?, semester = ?
WHERE registration_no = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, nameField.getText());
ps.setString(2, rollnoField.getText());
ps.setString(3, branchField.getText());
ps.setInt(4, Integer.parseInt(semesterField.getText()));
ps.setInt(5, Integer.parseInt(regnField.getText()));
ps.executeUpdate();
JOptionPane.showMessageDialog(this, "Student Updated Successfully!");
} else if (e.getSource() == displayButton) {
String query = "SELECT * FROM Student";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
displayArea.setText("---------------------------------------------------\n");
displayArea.append("Registration No : Name : Roll No : Branch : Semester\n");
displayArea.append("---------------------------------------------------\n");
while (rs.next()) {
displayArea.append(
"Regn No: " + rs.getInt("registration_no") + "\n" +
"Name: " + rs.getString("name") + "\n" +
"Roll No: " + rs.getString("rollno") + "\n" +
"Branch: " + rs.getString("branch") + "\n" +
"Semester: " + rs.getInt("semester") + "\n" +
"---------------------------------------------------\n"
);
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}

public static void main(String[] args) {


new StudentAppRedesigned().setVisible(true);
}
}

OUTPUT

You might also like