Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Sujal Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 70

VIVEKANANDA INSTITUTE OF PROFESSIONAL STUDIES 

VIVEKANANDA SCHOOL OF INFORMATION TECHNOLOGY 

 
 
BACHELOR OF COMPUTER APPLICATION
 
“JAVA” PROGRAMMING LAB
  
BCA 272

 
  Guru Gobind Singh Indraprastha University
  Sector - 16C, Dwarka, Delhi - 110078 

 
 
SUBMITTED TO:                                           SUBMITTED BY:  
Ms. Sakshi Khullar Sujal
Assistant Professor 06217702021
VSIT BCA-4B
2

INDEX – PRACRICAL

Sno. Practical Questions Signature


1 WAP to find out factorial of a number through recursion.

2 WAP to print Fibonacci series.

3 WAP to accept Command line arguments & print them.

4 WAP to obtain a number by a user & check if it’s prime or


not.

5 WAP to obtain a number by a user & check if it’s prime or


not.

6 WAP that creates a class Accounts with following


details:Instance variables: ac_no., name, ac_name,
balance .Methods: withdrawal(), deposit(),display().Use
constructors to initialize members.

7 WAP to implement constructor overloading.


8 WAP to count the no. of objects created in a program.
9 WAP to show call by value & call by reference.

10 WAP to implement method over ridding & method


overloading.

11 WAP that demonstrates all the usages of “super” keyword.


12 Create a class box having height, width , depth as the
instance variables & calculate its volume. Implement
constructor overloading in it. Create a subclass named
box_new that has weight as an instance variable. Use super
in the box_new class to initialize members of the base class.

13 WAP that implements multilevel inheritance.


14 Consider a university where students who participate in the
national games or Olympics are given some grace marks.
Therefore, the final marks awarded = Exam_Marks +
Sports_Grace_Marks. A class diagram representing this
scenario is as follow
15 WAP to implement Run time polymorphism.
16 WAP to implement interface. Create an interface named
Shape having area() & perimeter() as its methods. Create
three classes circle, rectangle & square that implement this
3

interface.

17 WAP to show multiple inheritance


18 WAP to implement exception handling. The program should
accept two numbers from the user & divide the first no. by
the second. It should throw a Arithmetic Exception if an
attempt is made to divide the no. by zero. Use try, catch &
finally .Implement multi-catch statements also .

19 Create a user defined exception named “NoMatchException”


that is fired when the number entered by the user is not
10.Use the throws & throw keyword.

20 WAP that creates three threads which print no.s from 1 to 5,


6 to 10 and 11 to 15 respectively .Set the name & priority of
the threads.

21 WAP to print even & odd numbers using threads


22 WAP that implements the concept of synchronization in
threads using both syncronized method and synchronized
block.
23 WAP that demonstrates the use of sleep and join methods in
thread. Use minimum three threads.

24 1. WAP to demonstrate the use of equals(), trim() ,length() ,


substring(), compareTo() of String class.

25 WAP to implement file handling . The program should copy


the content from one file to another.

26 10. WAP to implement all mouse events and mouse motion


events. Change the background color, text and foreground
color at each mouse event.

27 11. WAP to implement keyboard events.


12. WAP that creates a button in Swings. On clicking the button,
the content of the button should be displayed on a label.

28 13. W.a.p a Java program that simulates a traffic light. The


program lets the user select one of three lights: red, yellow,
or green. When a button is selected, the light is turned on,
and only one light can be on at a time No light is on when
the program starts.

29 WAP using AWT to create a simple calculator.


Integer.parseInt(String val)
4

30 Write an Jframe that contains three choices and 30 * 30 pixel


canvas. The three check boxes should be labeled
“red” ,”Green” and “Blue” .The selections of the choice
should determine the color of the background.
31 Write an Jframe that contains three choices and 30 * 30 pixel
canvas. The three check boxes should be labeled
“red” ,”Green” and “Blue” .The selections of the choice
should determine the color of the background.
32 Create a login form using AWT controls like labels, buttons,
textboxes, checkboxes, list, radio button. The selected
checkbox item names should be displayed.

33 14. Create an program using Combobox and textfield as per the


below figure:

34 15. WAP to show all Layout managers. (4 Layout managers).

35 16. Create a simple JDBC program that displays & updates(insert


or delete) the content of a table named employee having
fields (id,name,deptt).
5

1. WAP to find factorial of a number through recursion.


Code:
import java.util.Scanner;

class q1{
public static int factorial(int num){
        if(num ==0 || num==1)
        return 1;
        else
        return num*factorial(num-1);
    }

    public static void main(String args[]){


        Scanner sc = new Scanner(System.in);
        System.out.println(" Enter number to find factorial: ");
        int num= sc.nextInt();
        int factorial =factorial(num);
        System.out.println( " factorial of "+ num + " is "+ factorial);
    }
   
}

Output:
6

2. WAP to print Fibonacci series.


Code:
import java.util.Scanner;

class q1{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        System.out.println(" Enter number to find fibonacci series : ");
        int num= sc.nextInt();
        int fibonacci =fibonacci(num);
        System.out.println( " fibonacci of "+ num + " is "+ fibonacci);
    }
   
    public static int fibonacci(int num){
        if(num<=1)
        return num;
        else
        return fibonacci(num-1)+fibonacci(num-2);
    }
}

Output:
7

3. WAP to accept Command line Argument & print them.

class q1{
    public static void main(String args[]){
        System.out.println("Command line arguments:");
        for ( int i=0 ;i<args.length ;i++)
        System.out.println( " Argument : "+ args[i]);
    }

Output:
8

4. WAP to obtain a number by a user & check if it’s prime or not.

Code: import java.util.Scanner;

class q1{
    public static void main(String args[]){
        System.out.println("Enter a Number to check if it's prime or not : \
n");
        Scanner sc = new Scanner(System.in);
        int num= sc.nextInt();
        if( prime(num)){
            System.out.println(" yes ,it is prime ");
        }
        else{System.out.println(" no ,it is not prime ");}
    }
   
    public static boolean prime(int num){
        if(num<=1)
        return false;
        else{
            for ( int i=2; i<= Math.sqrt(num);i++){
                if( num % i==0){
                    return false;
                }
            }
        }
        return true;
    }
}
9

Output:
10

5. WAP that creates a class Accounts with following details :


Instance variables: ac_no., name, ac_name,  balance
Methods: withdrawal(), deposit(),display().Use constructors to
initialize members.
CODE:
import java.util.Scanner;

class Accounts{

    int acount_no;
    String name,acount_name;
    double balance;
    Scanner sc = new Scanner(System.in);

   public Accounts(){
        System.out.print(" \nEnter your Account Number : ");
        acount_no=sc.nextInt();  

        System.out.print(" \nEnter your name: ");


        name=sc.next();

        System.out.print(" \nEnter your Account name: ");


        acount_name=sc.next();

        System.out.print(" \nEnter your Balance: ");


       balance =  sc.nextDouble();

    }
    public boolean withdrawl(){
        System.out.print("\nEnter your amount for withdrawal: ");
        double amount =  sc.nextDouble();
        balance -=amount;
        display();
        return true;
    }
   public boolean deposit(){
        System.out.print(" \nEnter your amount for deposit : ");
        double amount =  sc.nextDouble();
        balance +=amount;
        display();
        return true;
     }
    public void display(){
        System.out.print("\n----------------- Details:------------- \nAccount
Number : "+acount_no);
        System.out.print("\n Name: "+name);
        System.out.print("\n Account name: "+acount_name);
        System.out.print(" \n Balance: "+balance);
11

     
    }
};

class q1{
    public static void main (String[] args){
    Accounts a1= new Accounts();
    a1.display();
    a1.deposit();
    a1.withdrawl();
    }
}

Output:
12

6. WAP to implement constructor overloading. 


Code:
class Shape{
    int length,breadth,height;
    String color;

    Shape(){
     length=breadth=height=0;
     color=null;
    }
    Shape(int l,int b,int h){
        length=l;
        breadth=b;
        height=l;
        color="blue";

    }
    Shape(String c){
        length=breadth=height=70;
     color="Green";
    }
    public void display(){
        System.out.println("-------Details of Shape :_--------"+"\
nlength:"+length+"\nbreadth: "+breadth+ "\nheight: "+height+"\n Color:
"+color);
    }
}

class q1{
    public static void main (String[] args){
    Shape a1= new Shape();
    Shape a2= new Shape(23,34,56);
    Shape a3= new Shape("cyan");
    a1.display();
    a2.display();
    a3.display();
    }
}
13

Output:
14

7. WAP to count the no. of objects created in a program. 


Code:
class Shape{
    int length,breadth,height;
    String color;
    static int counter;
   
    Shape(int l,int b,int h,String c){
        length=l;
        breadth=b;
        height=l;
        color="blue";
       counter++;
    }
   
    public void display(){
        System.out.println("count object : "+ counter );
        System.out.println("-------Details of Shape :_--------"+"\
nlength:"+length+"\nbreadth: "+breadth+ "\nheight: "+height+"\n Color:
"+color);
    }
}

class q1{
    public static void main (String[] args){
    Shape a1= new Shape(12,24,45,"blue");
    Shape a2= new Shape(23,34,56,"cyan");
    Shape a3= new Shape(23,56,78,"cyan");
    // a1.display();
    // a2.display();
    a3.display();
    }
}

Output:
15

8. WAP to show call by value & call by reference. 


Code:
import java.util.Scanner;
class MyClass{
      private int var1;
      public MyClass(int v){
        var1=v;
      }
      public void putdata(int a){
        var1=a;
      }
      public int getdata(){
     return var1;
      }
     

class q1{
        public static void ChangeValue(int value){
            value+=4;
            System.out.println(" Inside function value of variable : "
+value);
        }

       public static void ChangeValue( MyClass c1){


        c1.putdata(78);
        System.out.println(" inside function call : value of object data
member : " +c1.getdata());
       
       }

       public static void main(String[] args){


        int variable;
        Scanner sc =new Scanner(System.in);
        System.out.println("Enter value of Variable : ");
        variable= sc.nextInt();
        System.out.println(" \n--------show call by value ---------\nBefore
function call : value of variable : " +variable);  
        ChangeValue(variable);
        System.out.println(" After function call : value  of variable : "
+variable);  

        MyClass c= new MyClass(13);


16

        System.out.println("\n--------show call by reference ---------\n


Before function call : value of object data member : " +c.getdata());
        ChangeValue(c);
        System.out.println("  After function call : value of object data
member : " +c.getdata());

       }

Output:
17

9. WAP to implement method over ridding & method overloading. 

Code:
// method overriding
class Animal{
  public void makeSound(){
    System.out.println(" The animal make sound ");
  }
}
class Dog extends Animal{
    public void makeSound(){
        System.out.println("\nBark Bark");

    }
}
class Cat extends Animal{
    public void makeSound(){
        System.out.println("\nMeow\n");

    }
}
// method overloading
class Calculator{
      public int add(int a, int b){
        return a+b;
      }
      public int add(int a, int b, int c){
            return a+b+c;
      }
}
class q1{
      public static void main(String[] args){
        System.out.println("\nMethod overriding");
        Cat c= new Cat();
        System.out.println("Cat sound");
       c.makeSound();
       Dog d =new Dog();
       System.out.println("Dog sound");
       d.makeSound();
       
       System.out.println("\nMethod overloading");
       Calculator cal= new Calculator();
       System.out.println("Sum of two number 3+4 = "+ cal.add(3,4));
       System.out.println("Sum of three number 3+4+8 = "+ cal.add(3,4,8));

      }
}
18

Output:
19

10.WAP that demonstrates all the usages of “super” keyword. 

Code:

class BaseClass{
 protected int var;
 
 public BaseClass(int v){
    this.var=v;
    System.out.println("this is Base class");

 }

 public void getdata()


 {
     System.out.println("Value of var of base class: "+var);

 }

}
 class DrivedClass extends BaseClass{
    protected int var;
    DrivedClass(int b,int d){
        super(b);   //super(b); call parent constructor
        var=d;

    }
  public  void getdata(){
        super.getdata();// super.getdata(); //call parent member function
        System.out.println("Value of var of base + Drived class: "+
(super.var+this.var));
        //super.var //value of parent data member
    }

}
 class q10 {
 public static void main(String[] args){
      DrivedClass obj= new DrivedClass(89, 43);
      obj.getdata();

 }
}
20

Output:
21

11. Create a class box having height, width , depth as the instance
variables & calculate its volume. Implement  constructor overloading
in it. Create a subclass named box_new that has weight as an instance
variable. Use  super in the box_new class to initialize members of the
base class. 

Code:

import java.util.Scanner;

class  Box{
protected double height,width,depth;
Scanner sc= new Scanner(System.in);

Box(){
    height=width=depth=0.0;
    System.out.print("you wont to input data (y/n): ");
     char op= sc.next().charAt(0);
    // char op = sc.nextChar();
    if (op=='y'){
        System.out.print("Enter Details of Box: ");
       System.out.print("Enter Height: ");
       height=sc.nextDouble();
       System.out.print("Enter width: ");
       width=sc.nextDouble();
       System.out.print("Enter depth: ");
    depth=sc.nextDouble();
    }
   
}
Box(Double value){
    height=width=depth=value;
}
Box(Double h,Double w,Double d){
    height=h;width=w;depth=d;
}
void display(){
    System.out.println("\n Details of box : \n height: "+height+"\nwidth:
"+width+"\n Depth: "+depth);
}
void volume(){
System.out.println("Volume of Box : "+(height*width*depth));
}

}
22

// sub class
class Box_New extends Box{
    protected double weight;
    Box_New(){
        super();
        System.out.print("Enter  Weight of Box_New : ");
        weight=sc.nextDouble();
    }
    Box_New(double v,double w){
        super(v);
        weight=w;
    }
    void display(){
        super.display();
        System.out.println("weight: "+weight);
        super.volume();
    }

public class q11 {


    public static void main(String args[]){
  Box_New b1= new Box_New(45.7,76.8);
  b1.display();

  Box_New b2= new Box_New();


  b2.display();
    }
}
23

Output:
24

12 .WAP that implements multilevel inheritance. 


Code:
// parent class
class Animal{
    void eat(){
        System.out.println("Eating---------------");
    }
}
class Dog extends Animal{
    void bark(){
        System.out.println("Barking--------------------");

    }
}
class Poodle extends Dog{
    void groom(){
        System.out.println("Grooming----------------------");
    }
}

public class q12 {


    public static void main (String args[]){
       Poodle poodle = new Poodle();
       poodle.eat();
       poodle.bark();
       poodle.groom();
    }
}

Output:
25

12.Consider a university where students who participate in the national


games or Olympics are given some  grace marks.

Therefore, the final marks awarded = Exam_Marks +


Sports_Grace_Marks.
A class diagram  representing this scenario is as follow; 

Code:
import java.util.Scanner;

class Student{
   protected  String name;
   protected  long enroll;
   protected  char shift;
    public Student(){
        name= "abc";
        enroll=000000000;
       shift= 'E';
    }
    public Student(String name, long enroll, char shift){
        this.name=name;
        this.enroll=enroll;
        this.shift=shift;
    }
    void Display(){
        System.out.println("\nName :  "+ name+" \nEnrollno : "+enroll+"\nShift
: "+ shift);
    }
}

class Exam extends Student{


26

    double marks ;
   public Exam(){
       
        marks=000;
    }
    public Exam(String name, long enroll, char shift,double marks){
     super(name,enroll,shift);
     this.marks=marks;
    }
    void Display(){
        super.Display();
        System.out.print("\nMarks out of 100 : "+marks);
    }
}
 interface Sports{

    public void putSportGraceMarks(double spmarks);


 public double getSportGraceMarks();
}

class Result extends Exam implements Sports{


    double sportsGmarks,result;

    public Result(String name, long enroll, char shift,double marks,double


spmarks){
        super(name,enroll,shift,marks);
        putSportGraceMarks( spmarks);
        // sportsGmarks=spmarks;
     
     }

     public void putSportGraceMarks(double spmarks){


        sportsGmarks=spmarks;
     }
   public double getSportGraceMarks(){
        return sportsGmarks;
     }
     void Display(){
        super.Display();
        System.out.print("\nSports grace marks (out of  30): ");
        System.out.println(getSportGraceMarks());
        if (sportsGmarks<=30){

            if (marks<=40){
               System.out.print("With Sports Grace Marks===== ") ;
               result=marks+getSportGraceMarks();
            }
            else if(marks>=100){
27

                result=marks;
            }
            System.out.println("\nResult of Student : "+result);
         }
         else{
            System.out.println("Error: Invalid Sports grace marks ");
         }
        }

public class q13 {


    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String name;
        long enroll;
        char shift;
        double marks,sportg;
        System.out.print("\n\nEnter Student Details: \nName :  ");
        name= sc.nextLine();
        System.out.print("Enroll no : ");
        enroll=sc.nextLong();
        System.out.print("Shift : ");
        shift= sc.next().charAt(0);
        System.out.print("Enter marks out of 100 : ");
        marks= sc.nextDouble();
        System.out.println("Enter Sports grace marks : ");
       sportg=sc.nextDouble();

        Result s1= new Result(name,enroll,shift,marks,sportg);


        s1.Display();
    }
   

}
28

OutPut:
29

14.WAP to implement Run time polymorphism. 


15.
Code:
class Animal{
    public void makeSound(){
        System.out.println("Animal makes a sound. ");
    }
}
class Cat extends Animal{
    public void makeSound(){
        System.out.println("The Cat Meows. ");
    }
}
class Dog extends Animal{
    public void makeSound(){
        System.out.println("The Dog Barks ");
    }
}

public class q14 {


    public static void main(String[] args){
    Animal  Aobj = new Animal();
    Cat     Cobj =new Cat();
    Dog      Dobj = new Dog();
   
    Animal refAnimal;

    refAnimal=Aobj;
    refAnimal.makeSound();

    refAnimal=Cobj;
    refAnimal.makeSound();

    refAnimal =Dobj;
    refAnimal.makeSound();

    }
}
30

Output:
31

16.WAP to implement interface. Create an interface named Shape


having area() & perimeter() as its methods.  Create three classes
circle, rectangle & square that implement this interface. 

Code:

import java.util.Scanner;
interface Shape{
  double area();
  double perimeter();
}
class Circle implements Shape{
  protected double radius;

  public Circle(double r){


  radius=r;
  }
  public double area(){
    return Math.PI *radius *radius;
  }
  public double perimeter(){
    return 2*Math.PI*radius;
  }
}
class Rectangle implements Shape{
  protected double length ,breadth;
  public Rectangle(double l,double b){
    length=l;breadth=b;
  }
  public Rectangle(double l){
    length=breadth=l;
  }
  public double area(){
    return length*breadth;
  }
  public double perimeter(){
    return 2*(length+breadth);
  }

class Square implements Shape{


  protected double side;
  public Square(double side){
    this.side=side;
32

  }
  public double area(){
    return side*side;
  }
  public double perimeter(){
    return 4*side;
  }
}

public class q13 {


 
  public static void main(String args[]){
      Scanner sc = new Scanner(System.in);

    double var1,var2;
    System.out.print("\n Enter the Details of  Shape: \
n-----------------------------------------");
    System.out.print("\nEnter radius of circle:");
    var1=sc.nextDouble();

    //object of circle
    Circle c= new Circle(var1);
    System.out.print("Area of circle:  "+ c.area());
    System.out.print("\nPerimeter of circle:  "+ c.perimeter());

    System.out.print("\n\nEnter length of rectangle : ");


    var1 = sc.nextDouble();
    System.out.print("Enter breadth     :  ");
    var2 = sc.nextDouble();
     //object of rectangle
     Rectangle r= new Rectangle(var1,var2);
     System.out.print("Area of Rectangle:  "+r.area());
     System.out.print("\nPerimeter of Rectanlge: "+r.perimeter());

     System.out.print("\n\nEnter the side of square : ");


     var1=sc.nextDouble();
     
     //object of square
     Square s=new Square(var1);
     System.out.print("Area of Square : "+s.area());
     System.out.print("\nPerimeter of Square : "+ s.perimeter());

    }
}
33

Output:
34

17.WAP to show multiple inheritance. 


Code:

interface Tv {
    void turnOn();
    void turnOff();
    void changeChannel(int channel);
    void adjustVolume(int volume);
}
interface SmartDevice{
    void connectWifi(String network_name,String password);
    void browsWeb(String url);
    void sendEmail(String receipient,String subject ,String message);

}
class SmartTv implements Tv, SmartDevice{
    private boolean isOn;
    private int currentChannel,currentVolume;
    private String currentWifi;

    public void turnOn(){


        isOn=true;
        System.out.println("Smart tv turned on ");
    }
    public void turnOff(){
        isOn=false;
        System.out.println("Smart tv turned off ");
    }

    public void changeChannel(int ch){


        if (isOn){
            this.currentChannel=ch;
            System.out.println("Channel Changed ");

        }
        else{
            System.out.println("Tv is turnOff ");
        }
    }

    public void adjustVolume(int vol){


        if (isOn){
            this.currentVolume=vol;
            System.out.println("Volume is Adjusted  ");
35

        }
        else{
            System.out.println("Tv is turnOff ");
        }
    }
    public void connectWifi(String network_name,String password){
        if (isOn){
            this.currentWifi=network_name;
            System.out.println("Wiffi is connected   "+currentWifi);

        }
        else{
            System.out.println("Tv is turnOff ");
        }

    }
     public void browsWeb(String url){
        if (isOn){
           
            System.out.println("Cuurent browsing web is :   "+ url);

        }
        else{
            System.out.println("Tv is turnOff ");
        }
     }
    public void sendEmail(String recipient,String subject ,String message){
        if (isOn){
           
            System.out.println("Sending an email :\n recipient :
"+recipient+" Subject : "+subject+ " Message : "+message);

        }
        else{
            System.out.println("Tv is turnOff ");
        }
    }
 
}

public class q16 {


   public static void main(String args[]){
     SmartTv st1= new SmartTv();
     st1.turnOn();
     st1.changeChannel(45);
     st1.adjustVolume(45);
     st1.turnOff();
36

     st1.browsWeb("https://www.abc.com/");

     st1.turnOn();
     st1.connectWifi("XYZ","abcd1234");
     st1.sendEmail("efg.gmail.com","Java Lab  ","sldfrhnfdljdiofjdlkf");
     st1.turnOff();
   
    }
}

Output:
37

18.WAP to implement exception handling. The program should accept


two numbers from the user &  divide the first no. by the second. It
should throw a Arithmetic Exception if an attempt is made to 
divide the no. by zero. Use try, catch & finally .Implement multi-
catch statements also . 

Code:
import java.util.Scanner;

public class q17 {


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int num1 = sc.nextInt();
        System.out.print("Enter the second number: ");
        int num2 = sc.nextInt();
        try {
            int result = num1 / num2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("Program execution completed.");
        }
    }
}

Output:
38

19. Create a user defined exception named “NoMatchException” that is


fired when the number entered by the user is not 10.Use the throws &
throw keyword.

Code: import java.util.Scanner;

class NoMatchException extends Exception {


    public NoMatchException(String message) {
        super(message);
    }
}

class NumberChecker {
    public static void checkNumber(int number) throws NoMatchException {
        if (number != 10) {
            throw new NoMatchException("Number does not match!");
        } else {
            System.out.println("Number is a match!");
        }
    }
}

public class q18 {


    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int userInput ;
        System.out.print("Enter Number : ");
        userInput=sc.nextInt();

        try {
            NumberChecker.checkNumber(userInput);
        } catch (NoMatchException e) {
            System.out.println(e.getMessage());
        }
    }
}
Output:
39

20. WAP that creates three threads which print no.s from 1 to 5, 6 to 10
and 11 to 15 respectively .Set the name & priority of the threads.

Code: public class q19 {

    public static void main(String[] args) {


        // Create Thread objects
        Thread thread1 = new Thread(new PrintNumbers(1, 5), "Thread 1");
        Thread thread2 = new Thread(new PrintNumbers(6, 10), "Thread 2");
        Thread thread3 = new Thread(new PrintNumbers(11, 15), "Thread 3");

        // Set priorities of the threads


        thread1.setPriority(Thread.MIN_PRIORITY);
        thread2.setPriority(Thread.NORM_PRIORITY);
        thread3.setPriority(Thread.MAX_PRIORITY);

        // Start the threads


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

class PrintNumbers implements Runnable {


    private int start;
    private int end;

    public PrintNumbers(int start, int end) {


        this.start = start;
        this.end = end;
    }

    @Override
    public void run() {
        for (int i = start; i <= end; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
}
40

Output:
41

21. WAP to print even & odd numbers using threads.

Code: class PrintNumbers implements Runnable {

    private final int limit;


    private final boolean isEvenNumber;
   
    public PrintNumbers(int limit, boolean isEvenNumber) {
        this.limit = limit;
        this.isEvenNumber = isEvenNumber;
    }
   
    @Override
    public void run() {
        int number = isEvenNumber ? 2 : 1;
        while (number <= limit) {
            if ((isEvenNumber && number % 2 == 0) || (!isEvenNumber && number
% 2 != 0)) {
                System.out.println(Thread.currentThread().getName() + ": " +
number);
            }
            number += 2; // Increment by 2 to get the next even/odd number
        }
    }
}
public class q20 {
    public static void main(String[] args) {
        int limit = 10;
   
        // Create two threads, one for even numbers and one for odd numbers
        Thread evenThread = new Thread(new PrintNumbers(limit, true),
"EvenThread");
        Thread oddThread = new Thread(new PrintNumbers(limit, false),
"OddThread");
       
        // Start the threads
        evenThread.start();
        oddThread.start();
    }
}
42

Output:

22. WAP that implements the concept of synchronization in threads using


both syncronized method and synchronized block.
Code:

public class q21 {


    private int sum;

    public synchronized int getSum() {


        return sum;
    }

    public synchronized void setSum(int sum) {


        this.sum = sum;
    }

    public void calculateSumSyncMethod(int num1, int num2) {


        synchronized (this) {
            setSum(num1 + num2);
            System.out.println("Sum calculated using synchronized method: " +
getSum());
        }
    }

    public void calculateSumSyncBlock(int num1, int num2) {


        synchronized (this) {
            setSum(num1 + num2);
            System.out.println("Sum calculated using synchronized block: " +
getSum());
        }
43

    }

    public static void main(String[] args) {


        q21 example = new q21();
        int num1 = 10;
        int num2 = 20;

        // Create two threads to calculate the sum using synchronized method


and synchronized block
        Thread thread1 = new Thread(() -> example.calculateSumSyncMethod(num1,
num2));
        Thread thread2 = new Thread(() -> example.calculateSumSyncBlock(num1,
num2));

        // Start the threads


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

        try {
            // Wait for the threads to finish
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output:
44

23. WAP that demonstrates the use of sleep and join methods in thread.
Use minimum three threads.
Code:

class TableThread extends Thread {


    private int tableNumber;
   
    public TableThread(int number) {
        this.tableNumber = number;
    }
   
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println(tableNumber + " x " + i + " = " + (tableNumber
* i));
           
            try {
                Thread.sleep(500); // Delay of 500 milliseconds
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class q22 {


    public static void main(String[] args) {
        // Create three table threads
        TableThread thread12 = new TableThread(12);
        TableThread thread13 = new TableThread(13);
        TableThread thread14 = new TableThread(14);
       
        // Start the threads
        thread12.start();
        thread13.start();
        thread14.start();
       

        try {
            // Wait for all three threads to complete using join()
            thread12.join();
            thread13.join();
45

            thread14.join();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       
        System.out.println("All threads completed.");
    }
}

Output:
46

24. WAP to demonstrate the use of equals(), trim() ,length() , substring(),


compareTo() of String class.

Code:

public class q23 {


    public static void main(String[] args) {
        String str = "HarshitaKashyap";
        String otherStr = "harshitaKashyap";

        // equals() - compares two strings for equality


        boolean isEqual = str.equals(otherStr);
        System.out.println("Using equals(): " + isEqual);

        // trim() - removes leading and trailing whitespaces


        String trimmedStr = str.trim();
        System.out.println("Using trim(): " + trimmedStr);

        // length() - returns the length of the string


        int length = str.length();
        System.out.println("Using length(): " + length);

        // substring() - extracts a portion of the string


        String substring = str.substring(4, 9);
        System.out.println("Using substring(): " + substring);

        // compareTo() - compares two strings lexicographically


        int comparisonResult = str.compareTo(otherStr);
        System.out.println("Using compareTo(): " + comparisonResult);
    }
}

Output:
47

25. WAP to implement file handling . The program should copy the content
from one file to another.

Code:

import java.io.*;

public class q24 {


    public static void main(String[] args) {
        String sourceFilePath = "source.txt";
        String destinationFilePath = "destination.txt";

        try {
            File sourceFile = new File(sourceFilePath);
            File destinationFile = new File(destinationFilePath);

            // Create input and output streams


            FileReader fileReader = new FileReader(sourceFile);
            FileWriter fileWriter = new FileWriter(destinationFile);

            // Read and write content


            int character;
            while ((character = fileReader.read()) != -1) {
                fileWriter.write(character);
            }

            // Close streams
            fileReader.close();
            fileWriter.close();

            System.out.println("File copied successfully!");


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:
48

26. WAP to implement all mouse events and mouse motion events. Change the
background color, text and foreground color at each mouse event.
Code:

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

public class q25 extends JFrame implements MouseListener, MouseMotionListener


{

    private JLabel label;

    public q25() {
        setTitle("Mouse Events Demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        label = new JLabel("Move the mouse or click any button");


        label.setHorizontalAlignment(SwingConstants.CENTER);
        add(label, BorderLayout.CENTER);

        addMouseListener(this);
        addMouseMotionListener(this);

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

    public static void main(String[] args) {


        SwingUtilities.invokeLater(q25::new);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        label.setText("Mouse Clicked");
        getContentPane().setBackground(Color.YELLOW);
        label.setForeground(Color.RED);
    }

    @Override
    public void mousePressed(MouseEvent e) {
        label.setText("Mouse Pressed");
        getContentPane().setBackground(Color.BLUE);
        label.setForeground(Color.WHITE);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
49

        label.setText("Mouse Released");
        getContentPane().setBackground(Color.GREEN);
        label.setForeground(Color.BLACK);
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        label.setText("Mouse Entered");
        getContentPane().setBackground(Color.CYAN);
        label.setForeground(Color.MAGENTA);
    }

    @Override
    public void mouseExited(MouseEvent e) {
        label.setText("Mouse Exited");
        getContentPane().setBackground(Color.PINK);
        label.setForeground(Color.ORANGE);
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        label.setText("Mouse Dragged: (" + e.getX() + ", " + e.getY() + ")");
        getContentPane().setBackground(Color.LIGHT_GRAY);
        label.setForeground(Color.DARK_GRAY);
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        label.setText("Mouse Moved: (" + e.getX() + ", " + e.getY() + ")");
        getContentPane().setBackground(Color.WHITE);
        label.setForeground(Color.BLACK);
    }
}

Output:
50

27. WAP to implement keyboard events.


Code:

import java.awt.*;
import java.awt.event.*;

public class q26  {


    public static void main(String[] args) {
        Frame frame = new Frame("Keyboard Events Example");
        TextField textField = new TextField(20);
       
        textField.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                System.out.println("Key pressed: " + e.getKeyChar());
            }
           
            public void keyReleased(KeyEvent e) {
                System.out.println("Key released: " + e.getKeyChar());
            }
           
            public void keyTyped(KeyEvent e) {
                System.out.println("Key typed: " + e.getKeyChar());
            }
        });
       
        frame.add(textField);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}
Output:
51

28. WAP that creates a button in Swings. On clicking the button, the content of
the button should be displayed on a label.

Code:

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

public class q27 {


    public static void main(String[] args) {
        JFrame frame = new JFrame("Button Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);

        JPanel panel = new JPanel();


        frame.add(panel);

        JButton button = new JButton("East and West I am the Best");


        panel.add(button);

        JLabel label = new JLabel();


        panel.add(label);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                label.setText(button.getText());
            }
        });

        frame.setVisible(true);
    }
}

Output:
52

29. Write a Java program that simulates a traffic light. The program lets the user
select one of three lights: red, yellow, or green. When a button is selected,
the light is turned on, and only one light can be on at a time No light is on
when the program starts.

Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class q28 extends JFrame implements ActionListener {


    private JButton redButton, yellowButton, greenButton;
    private JPanel trafficLightPanel;

    public q28() {
        setTitle("Traffic Light Simulator");
        setSize(400, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        redButton = new JButton("Red");


        yellowButton = new JButton("Yellow");
        greenButton = new JButton("Green");

        redButton.addActionListener(this);
        yellowButton.addActionListener(this);
        greenButton.addActionListener(this);

        trafficLightPanel = new JPanel();


        trafficLightPanel.setBackground(Color.BLACK);

        setLayout(new BorderLayout());

        JPanel buttonPanel = new JPanel();


        buttonPanel.add(redButton);
        buttonPanel.add(yellowButton);
        buttonPanel.add(greenButton);

        add(trafficLightPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
53

        switch (command) {
            case "Red":
                turnOnRedLight();
                break;
            case "Yellow":
                turnOnYellowLight();
                break;
            case "Green":
                turnOnGreenLight();
                break;
        }
    }

    private void turnOnRedLight() {


        trafficLightPanel.removeAll();
        JPanel redLight = new JPanel();
        redLight.setBackground(Color.RED);
        trafficLightPanel.add(redLight);
        validate();
        repaint();
    }

    private void turnOnYellowLight() {


        trafficLightPanel.removeAll();
        JPanel yellowLight = new JPanel();
        yellowLight.setBackground(Color.YELLOW);
        trafficLightPanel.add(yellowLight);
        validate();
        repaint();
    }

    private void turnOnGreenLight() {


        trafficLightPanel.removeAll();
        JPanel greenLight = new JPanel();
        greenLight.setBackground(Color.GREEN);
        trafficLightPanel.add(greenLight);
        validate();
        repaint();
    }
54

    public static void main(String[] args) {


        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new q28().setVisible(true);
            }
        });
    }
}

Output:
55

30. WAP using AWT to create a simple calculator. Integer.parseInt(String val)


Code:
import java.awt.*;
import java.awt.event.*;

public class CalculatorGUI extends Frame {


    private TextField firstInput;
    private TextField secondInput;
    private TextField resultField;
    private Button addButton;
    private Button subtractButton;
    private Button multiplyButton;
    private Button divideButton;
    private Button cancelButton;

    public CalculatorGUI() {
        // Set up the frame
        setTitle("Simple Calculator");
        setSize(300, 200);
        setLayout(new GridLayout(5, 2));

        // Create components
        firstInput = new TextField();
        secondInput = new TextField();
        resultField = new TextField();
        addButton = new Button("Add");
        subtractButton = new Button("Subtract");
        multiplyButton = new Button("Multiply");
        divideButton = new Button("Divide");
        cancelButton = new Button("Cancel");

        // Add components to the frame


        add(new Label("First Input:"));
        add(firstInput);
        add(new Label("Second Input:"));
        add(secondInput);
        add(new Label("Result:"));
        add(resultField);
        add(addButton);
        add(subtractButton);
        add(multiplyButton);
        add(divideButton);
        add(cancelButton);

        // Add event listeners


        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
56

                calculateResult('+');
            }
        });

        subtractButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                calculateResult('-');
            }
        });

        multiplyButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                calculateResult('*');
            }
        });

        divideButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                calculateResult('/');
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                clearFields();
            }
        });

        // Display the frame


        setVisible(true);
    }

    private void calculateResult(char operator) {


        try {
            int firstNumber = Integer.parseInt(firstInput.getText());
            int secondNumber = Integer.parseInt(secondInput.getText());
            int result = 0;

            switch (operator) {
                case '+':
                    result = firstNumber + secondNumber;
                    break;
                case '-':
                    result = firstNumber - secondNumber;
                    break;
                case '*':
                    result = firstNumber * secondNumber;
                    break;
57

                case '/':
                    result = firstNumber / secondNumber;
                    break;
            }

            resultField.setText(String.valueOf(result));
        } catch (NumberFormatException ex) {
            resultField.setText("Invalid input");
        }
    }

    private void clearFields() {


        firstInput.setText("");
        secondInput.setText("");
        resultField.setText("");
    }

    public static void main(String[] args) {


        CalculatorGUI calculator = new CalculatorGUI();
    }
}

Output:
58

31. Write an Jframe that contains three choices and 30 * 30 pixel canvas. The
three check boxes should be labeled “red” ,”Green” and “Blue” .The
selections of the choice should determine the color of the background.

Code:

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

public class q30 extends JFrame {


    private JPanel canvas;
    private JCheckBox redCheckBox, greenCheckBox, blueCheckBox;

    public q30() {
        setTitle("Color Chooser");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);
       
        canvas = new JPanel();
        canvas.setPreferredSize(new Dimension(30, 30));
        add(canvas, BorderLayout.CENTER);
       
        redCheckBox = new JCheckBox("Red");
        greenCheckBox = new JCheckBox("Green");
        blueCheckBox = new JCheckBox("Blue");
       
        redCheckBox.addItemListener(new ColorChangeListener());
        greenCheckBox.addItemListener(new ColorChangeListener());
        blueCheckBox.addItemListener(new ColorChangeListener());
       
        JPanel checkBoxPanel = new JPanel();
        checkBoxPanel.add(redCheckBox);
        checkBoxPanel.add(greenCheckBox);
        checkBoxPanel.add(blueCheckBox);
       
        add(checkBoxPanel, BorderLayout.SOUTH);
    }

    private class ColorChangeListener implements ItemListener {


        public void itemStateChanged(ItemEvent event) {
            int red = redCheckBox.isSelected() ? 255 : 0;
            int green = greenCheckBox.isSelected() ? 255 : 0;
59

            int blue = blueCheckBox.isSelected() ? 255 : 0;


            Color color = new Color(red, green, blue);
            canvas.setBackground(color);
        }
    }

    public static void main(String[] args) {


        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new q30().setVisible(true);
            }
        });
    }
}

Output:
60

32. Create a login form using AWT controls like labels, buttons, textboxes,
checkboxes, list, radio button. The selected checkbox item names should be
displayed.

Code:
import java.awt.*;
import java.awt.event.*;

public class LoginFrame extends Frame implements ActionListener {


    private Label lblUsername;
    private Label lblPassword;
    private TextField txtUsername;
    private TextField txtPassword;
    private Button btnLogin;
    private Checkbox cbRememberMe;
    private List selectedItems;

    public LoginFrame() {
        setTitle("Login Form");
        setSize(300, 200);
        setLayout(new FlowLayout());

        lblUsername = new Label("Username:");


        add(lblUsername);

        txtUsername = new TextField(20);


        add(txtUsername);

        lblPassword = new Label("Password:");


        add(lblPassword);

        txtPassword = new TextField(20);


        txtPassword.setEchoChar('*');
        add(txtPassword);

        cbRememberMe = new Checkbox("Remember Me");


        add(cbRememberMe);

        selectedItems = new List(3, true);


        selectedItems.add("Checkbox 1");
        selectedItems.add("Checkbox 2");
        selectedItems.add("Checkbox 3");
        add(selectedItems);

        btnLogin = new Button("Login");


        add(btnLogin);
        btnLogin.addActionListener(this);
61

        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {


        if (e.getSource() == btnLogin) {
            String username = txtUsername.getText();
            String password = txtPassword.getText();
            boolean rememberMe = cbRememberMe.getState();
            String[] selectedCheckboxItems = selectedItems.getSelectedItems();

            System.out.println("Username: " + username);


            System.out.println("Password: " + password);
            System.out.println("Remember Me: " + rememberMe);
            System.out.println("Selected Checkbox Items:");
            for (String item : selectedCheckboxItems) {
                System.out.println(item);
            }
        }
    }

    public static void main(String[] args) {


        new LoginFrame();
    }
}

Output:
62

33. Create an program using Combobox and textfield as per the below figure:

Code:
import java.awt.*;
import java.awt.event.*;

public class CalculatorGUI extends Frame {


    private TextField firstInput;
    private TextField secondInput;
    private TextField resultField;
    private Button addButton;
    private Button subtractButton;
    private Button multiplyButton;
    private Button divideButton;
    private Button cancelButton;

    public CalculatorGUI() {
        // Set up the frame
        setTitle("Simple Calculator");
        setSize(300, 200);
        setLayout(new GridLayout(5, 2));

        // Create components
        firstInput = new TextField();
        secondInput = new TextField();
        resultField = new TextField();
        addButton = new Button("Add");
        subtractButton = new Button("Subtract");
        multiplyButton = new Button("Multiply");
        divideButton = new Button("Divide");
        cancelButton = new Button("Cancel");

        // Add components to the frame


        add(new Label("First Input:"));
        add(firstInput);
        add(new Label("Second Input:"));
        add(secondInput);
        add(new Label("Result:"));
        add(resultField);
        add(addButton);
        add(subtractButton);
        add(multiplyButton);
        add(divideButton);
        add(cancelButton);
63

        // Add event listeners


        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                calculateResult('+');
            }
        });

        subtractButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                calculateResult('-');
            }
        });

        multiplyButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                calculateResult('*');
            }
        });

        divideButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                calculateResult('/');
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                clearFields();
            }
        });

        // Display the frame


        setVisible(true);
    }

    private void calculateResult(char operator) {


        try {
            int firstNumber = Integer.parseInt(firstInput.getText());
            int secondNumber = Integer.parseInt(secondInput.getText());
            int result = 0;

            switch (operator) {
                case '+':
                    result = firstNumber + secondNumber;
                    break;
                case '-':
                    result = firstNumber - secondNumber;
64

                    break;
                case '*':
                    result = firstNumber * secondNumber;
                    break;
                case '/':
                    result = firstNumber / secondNumber;
                    break;
            }

            resultField.setText(String.valueOf(result));
        } catch (NumberFormatException ex) {
            resultField.setText("Invalid input");
        }
    }

    private void clearFields() {


        firstInput.setText("");
        secondInput.setText("");
        resultField.setText("");
    }

    public static void main(String[] args) {


        CalculatorGUI calculator = new CalculatorGUI();
    }
}
65

34. WAP to show all Layout managers. (4 Layout managers).

Code:

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

public class LayoutManagerDemo {


    public static void main(String[] args) {
        JFrame frame = new JFrame("Layout Manager Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Creating panels
        JPanel borderLayoutPanel = new JPanel(new BorderLayout());
        JPanel flowLayoutPanel = new JPanel(new FlowLayout());
        JPanel gridLayoutPanel = new JPanel(new GridLayout(3, 3));
        JPanel boxLayoutPanel = new JPanel();
        boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel,
BoxLayout.Y_AXIS));

        // Adding components to the panels


        // BorderLayout
        borderLayoutPanel.add(new JButton("North"), BorderLayout.NORTH);
        borderLayoutPanel.add(new JButton("South"), BorderLayout.SOUTH);
        borderLayoutPanel.add(new JButton("West"), BorderLayout.WEST);
        borderLayoutPanel.add(new JButton("East"), BorderLayout.EAST);
        borderLayoutPanel.add(new JButton("Center"), BorderLayout.CENTER);

        // FlowLayout
        flowLayoutPanel.add(new JButton("Button 1"));
        flowLayoutPanel.add(new JButton("Button 2"));
        flowLayoutPanel.add(new JButton("Button 3"));

        // GridLayout
        for (int i = 1; i <= 9; i++) {
            gridLayoutPanel.add(new JButton("Button " + i));
        }

        // BoxLayout
        boxLayoutPanel.add(new JButton("Button 1"));
        boxLayoutPanel.add(Box.createVerticalStrut(10));
        boxLayoutPanel.add(new JButton("Button 2"));
        boxLayoutPanel.add(Box.createVerticalStrut(10));
        boxLayoutPanel.add(new JButton("Button 3"));

        // Adding panels to the frame


66

        frame.setLayout(new GridLayout(2, 2));


        frame.add(borderLayoutPanel);
        frame.add(flowLayoutPanel);
        frame.add(gridLayoutPanel);
        frame.add(boxLayoutPanel);

        frame.pack();
        frame.setVisible(true);
    }
}

Output:
67

35. Create a simple JDBC program that displays & updates(insert or delete) the
content of a table named employee having fields (id,name,deptt).

Code:

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

public class EmployeeManagementGUI extends JFrame {


    private static final String DB_URL =
"jdbc:mysql://localhost:3306/your_database_name";
    private static final String USERNAME = "your_username";
    private static final String PASSWORD = "your_password";

    private JTextField idField, nameField, deptField;


    private JTextArea outputArea;

    public EmployeeManagementGUI() {
        super("Employee Management");

        // Create GUI components


        JLabel idLabel = new JLabel("ID:");
        JLabel nameLabel = new JLabel("Name:");
        JLabel deptLabel = new JLabel("Department:");

        idField = new JTextField(10);


        nameField = new JTextField(20);
        deptField = new JTextField(20);

        JButton displayButton = new JButton("Display");


        JButton insertButton = new JButton("Insert");
        JButton deleteButton = new JButton("Delete");

        outputArea = new JTextArea(10, 30);


        outputArea.setEditable(false);

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

        // Add components to the frame


        add(idLabel);
        add(idField);
        add(nameLabel);
        add(nameField);
        add(deptLabel);
68

        add(deptField);
        add(displayButton);
        add(insertButton);
        add(deleteButton);
        add(new JScrollPane(outputArea));

        // Add event listeners


        displayButton.addActionListener(new DisplayButtonListener());
        insertButton.addActionListener(new InsertButtonListener());
        deleteButton.addActionListener(new DeleteButtonListener());
    }

    private class DisplayButtonListener implements ActionListener {


        public void actionPerformed(ActionEvent e) {
            outputArea.setText(""); // Clear the output area

            try (Connection conn = DriverManager.getConnection(DB_URL,


USERNAME, PASSWORD);
                 Statement stmt = conn.createStatement()) {

                // Execute the SELECT query


                String sql = "SELECT * FROM employee";
                ResultSet rs = stmt.executeQuery(sql);

                // Process the result set


                while (rs.next()) {
                    int id = rs.getInt("id");
                    String name = rs.getString("name");
                    String dept = rs.getString("deptt");

                    outputArea.append("ID: " + id + "\n");


                    outputArea.append("Name: " + name + "\n");
                    outputArea.append("Department: " + dept + "\n\n");
                }

                rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private class InsertButtonListener implements ActionListener {


        public void actionPerformed(ActionEvent e) {
            String id = idField.getText();
            String name = nameField.getText();
            String dept = deptField.getText();
69

            try (Connection conn = DriverManager.getConnection(DB_URL,


USERNAME, PASSWORD);
                 Statement stmt = conn.createStatement()) {

                // Execute the INSERT query


                String sql = "INSERT INTO employee (id, name, deptt) VALUES
('" + id + "', '" + name + "', '" + dept + "')";
                stmt.executeUpdate(sql);

                JOptionPane.showMessageDialog(null, "Record inserted


successfully!");

                // Clear the input fields


                idField.setText("");
                nameField.setText("");
                deptField.setText("");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private class DeleteButtonListener implements ActionListener {


        public void actionPerformed(ActionEvent e) {
            String id = idField.getText();

            try (Connection conn = DriverManager.getConnection(DB_URL,


USERNAME, PASSWORD);
                 Statement stmt = conn.createStatement()) {

                  // Execute the DELETE query


                String sql = "DELETE FROM employee WHERE id = '" + id + "'";
                int rowsAffected = stmt.executeUpdate(sql);

                if (rowsAffected > 0) {
                    JOptionPane.showMessageDialog(null, "Record deleted
successfully!");
                } else {
                    JOptionPane.showMessageDialog(null, "No record found with
ID: " + id);
                }

                // Clear the input field


                idField.setText("");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
70

    }

    public static void main(String[] args) {


        EmployeeManagementGUI empGUI = new EmployeeManagementGUI();
        empGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        empGUI.setSize(400, 400);
        empGUI.setVisible(true);
    }
}
             

Output:

You might also like