You are on page 1of 59

VIVEKANANDA INSTITUTE OF PROFESSIONAL STUDIES

VIVEKANANDA INSTITUTE OF INFORMATION TECHNOLOGY

BACHELOR OF COMPUTER APPLICATIONS


Java Programming
BCA 272

SUBMITTED TO: SUBMITTED BY:


Senior Assistant Professor MAYANK TEWARI
Dr. Sakshi Khullar 10017702021
VSIT, VIPS BCA 4 – B

10017702021 Mayank Tewari BCA 4B


INDEX
Sno. Particulars Sign.
1. Write a program to find out factorial of a number through recursion.
2. Write a program to print Fibonacci Series.
3. Write a program to accept Command Line Arguments and print them.
4. Write a program to obtain number by user and check if it’s prime or not.
5. Write a program 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.
6. Write a program to implement constructor overloading.
7. Write a program to count number of objects created in a program.
8. Write a program to show :
a) Call by Value
b) Call by Reference
9. Write a program to implement :
a) Method Overriding
b) Method Overloading
10. Write a program that demonstrates all usage of ‘super’ keyword.
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.
12. Write a program that implements Multilevel Inheritance.
13. 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
14. Write a program to implement Run Time Polymorphism.
15. Write a program to implement interface. Create an interface named Shape having
area() & perimeter() as its methods. Create three classes circle, rectangle & square
that implement this interface.
16. Write a program to show multiple inheritance.
17. Write a program 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 .
18. 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.

19. 1. 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.
20 2. WAP to print even & odd numbers using threads.

10017702021 Mayank Tewari BCA 4B


21. 3. WAP that implements the concept of synchronization in threads using both
syncronized method and synchronized block.
22. 4. WAP that demonstrates the use of sleep and join methods in thread. Use minimum
three threads.
23. WAP to demonstrate the use of equals(), trim() ,length() , substring(), compareTo() of
String class.
24. WAP to implement file handling . The program should copy the content from one file
to another.
25. WAP to implement all mouse events and mouse motion events. Change the
background color, text and foreground color at each mouse event.
26. WAP to implement keyboard events.
27. WAP that creates a button in Swings. On clicking the button, the content of the button
should be displayed on a label.
28. 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.
29. WAP using AWT to create a simple calculator. Integer.parseInt(String val)
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. Create a login form using AWT controls like labels, buttons, textboxes, checkboxes,
list, radio button. The selected checkbox item names should be displayed.
32. Create an program using Combobox and textfield as per the below figure:
33. WAP to show all Layout managers. (4 Layout managers).
34. Create a simple JDBC program that displays & updates(insert or delete) the content of
a table named employee having fields (id,name,deptt).

10017702021 Mayank Tewari BCA 4B


Program – 1
Write a program to find out factorial of a number through recursion.
CODE
import java.util.*;
class Q1
{
public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
OUTPUT

Program – 2
Write a program to print Fibonacci Series.
CODE
import java.util.*;
class Q2{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);
for(i=2;i<count;++i)
{ n3=n1+n2;
System.out.print(" "+n3);
n1=n2;

10017702021 Mayank Tewari BCA 4B


n2=n3; }
}
}
OUTPUT

Program – 3
Write a program to accept Command Line Arguments and print them.
CODE
class Q3{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
} }
OUTPUT

Program – 4
Write a program to obtain number by user and check if it’s prime or not.
CODE
import java.util.Scanner;
public class Q4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
boolean isPrime = true;
if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(number); i++) {
10017702021 Mayank Tewari BCA 4B
if (number % i == 0) {
isPrime = false;
break;
}}}
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}}}

OUTPUT

Program – 5
Write a program 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.*;
class accounts{
int acc_no;
String name;
String acc_name;
double balance;

accounts(int acc_no, String name, String acc_name, double balance){


this.acc_no = acc_no;
this.name = name;
this.acc_name = acc_name;
this.balance = balance;

10017702021 Mayank Tewari BCA 4B


}

public void withdrawal(double amount){


if(amount <= balance){
balance -= amount;
System.out.println("Amount Withdrawn : "+amount);}
else{
System.out.println("Insufficient balance!");}
}

public void deposit(double amount){


balance += amount;
System.out.println("Amount Deposited: "+amount);}

public void display(){


System.out.println("Account number: "+acc_no);
System.out.println("Name: "+name);
System.out.println("Account Name: "+acc_name);
System.out.println("Balance: "+balance+"\n");
}
}

class bank{
public static void main(String[] args){
accounts a = new accounts(34792, "Mayank Tewari", "SBI", 9800);
a.display();
a.deposit(1000);
a.display();
a.withdrawal(500);
a.display();
}
}

10017702021 Mayank Tewari BCA 4B


OUTPUT

Program – 6
Write a program to implement constructor overloading.
CODE
import java.util.*;
class box{
double width;
double height;
double depth;
box()
{
width=height=depth=1;
}
box(double len)
{
width=height=depth=len;
}
10017702021 Mayank Tewari BCA 4B
box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
void volume()
{
System.out.println("Volume is "+width*height*depth);
}
}
class q6
{
public static void main(String[] args)
{
box mb1 = new box(10,30,17);
box mb2 = new box();
box mb3 = new box(20);
mb1.volume();
mb2.volume();
mb3.volume();
}
}

OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 7
Write a program to count number of objects created in a program.
CODE
import java.util.*;
public class Q7 {
private static int objectCount = 0;
public Q7() {
objectCount++;
}
public static int getObjectCount() {
return objectCount;
}
public static void main(String[] args) {
Q7 obj1 = new Q7();
Q7 obj2 = new Q7();
System.out.println("Number of objects created: " + Q7.getObjectCount());
}
}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 8
Write a program to show :
c) Call by Value
CODE
import java.util.*;
class CallByValue {
CallByValue(){
Scanner input = new Scanner(System.in);
int a = 6;
int b = 23;
System.out.println("The values of a and b before swapping: " + a + " " + b);
swapValues(a, b);
System.out.println("The values of a and b after swapping: " + a + " " + b);
}
void swapValues(int x, int y) {
int temp = x;
x = y;
y = temp;
System.out.println("The values of x and y inside the method: " + x + " " + y);}
}
class Q8a{
public static void main(String[] args){
CallByValue c = new CallByValue();
c.swapValues(6, 23);}}
OUTPUT

10017702021 Mayank Tewari BCA 4B


d) Call By Reference
CODE
import java.util.*;
class Test{
int a,b;
Test(int i, int j){
a=i;
b=j;
}
void meth(Test o){
o.a*=2;
o.b/=2;
}}
class Q8b{
public static void main(String[] args){
Test ob = new Test(6,26);
System.out.println("Values are: "+ob.a+" "+ob.b);
ob.meth(ob);
System.out.println("Now values are: "+ob.a+" "+ob.b);
}}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 9
Write a program to implement :
a) Method Overriding
CODE
import java.util.*;
class A{
int i, j;
A(int a, int b){
i = a;
j = b;}
void show(){
System.out.println("i and j: "+i+" "+j);}
}
class B extends A{
int k;
B(int a, int b, int c){
super(a,b);
k = c;
}
void show(){
System.out.println("k: "+k);}
}
class Q9a{
public static void main(String[] args){
B ob = new B(1, 2, 3);
ob.show();
}
}
OUTPUT

10017702021 Mayank Tewari BCA 4B


b) Method Overloading
CODE
import java.util.*;
class methodload{
void test(){
System.out.println("No hello.");}
void test(int a){
System.out.println("a: "+a);
}
void test(int a, int b){
System.out.println("a and b: "+a+" "+b);
}
double test(double a){
System.out.println("double a: "+a);
return a*a;}
}
class q9b{
public static void main(String[] args){
methodload m = new methodload();
double r;
m.test();
m.test(10);
m.test(10,15);
r = m.test(20.25);
System.out.println("Result of this is: "+r);
}}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 10
Write a program that demonstrates all usage of ‘super’ keyword.
CODE
import java.util.*;
class A{
A(){
System.out.println("A printing...");}
}
class B extends A{
B(){
super();
System.out.println("B printing...");}
}
class C extends B{
C(){
super();
System.out.println("C printing...");}
}
class q10a{
public static void main(String[] args){
C cobj = new C();
}
}
OUTPUT

10017702021 Mayank Tewari BCA 4B


b)
import java.util.*;
class vehicle{
int maxspd = 10;
}

class car extends vehicle{


int maxspd = 20;

void display(){
System.out.println("Max speed: "+super.maxspd);
}
}

class q10b{
public static void main(String[] args){
car cob = new car();
cob.display();
}
}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 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.*;
class box{
double height;
double width;
double depth;
box(){
width=height=depth=20;}
box(double len){
width=height=depth=len;}
double volume(){
double v = width*height*depth;
System.out.println("Volume is: "+v);
return v;}}
class box_new extends box{
double weight = 768.7;
void display(){
System.out.println("The Volume is: "+super.volume());
System.out.println("The Weight is: "+weight);}}
class q11{
public static void main(String[] args){
box_new b = new box_new();
b.display();}}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 12
Write a program that implements Multilevel Inheritance.
CODE
import java.util.*;
class A{
public void displayA(){
System.out.println("Displaying A");}
}
class B extends A{
public void displayB(){
System.out.println("Displaying B");}
}
class C extends B{
public void displayC(){
System.out.println("Displaying C");
}
}
class q12{
public static void main(String[] args){
C oc = new C();
oc.displayA();
oc.displayB();
oc.displayC();}
}

OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 13
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.*;
class student{
String name;
int rollno;
student(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter name: ");
name = sc.next();
System.out.println("Enter roll no.: ");
rollno = sc.nextInt();
}
}

class exam extends student{


int java, sw, total_marks;
exam(){
super();
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks of java: ");
java = sc.nextInt();
System.out.println("Enter marks of sw: ");
sw = sc.nextInt();
total_marks = java + sw;
System.out.println("Total marks is: "+total_marks);
}
}

10017702021 Mayank Tewari BCA 4B


interface sports{
int grace_marks();
}

class results extends exam implements sports{


public int grace_marks(){
int gm = 20;
return gm;
}
int calculate(){
int grace = grace_marks();
int finalresult = grace + total_marks;
return finalresult;
}
}

class q13{
public static void main(String[] args){
results r = new results();
int result = r.calculate();
System.out.println("Final result is: " + result);
}
}OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 14
Write a program to implement Run Time Polymorphism
CODE
class A{
void show(){
System.out.println("Inside A's show");}
}
class B extends A{
void show(){
System.out.println("Inside B's show");}}
class C extends B{
void show(){
System.out.println("Inside C's show");}}
class q14{
public static void main(String[] args){
A a = new A();
B b = new B();
C c = new C();
A r;
r = a;
r.show();
r = b;
r.show();
r = c;
r.show();}}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 15
Write a program 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.*;
interface Shape{
void calc_area();
void calc_peri();
}

class Circle implements Shape{


double r = 5;
double area, p;
public void calc_area(){
area = 3.14*r*r;
}
public void calc_peri(){
p = 2*3.14*r;
}
public void display(){
System.out.println("Area of circle is: "+area);
System.out.println("Perimeter of circle is: "+p);
}
}

class Rectangle implements Shape{


double l = 3.5, b = 5.6;
double r_area, r_peri;
public void calc_area(){
r_area = l*b;
}

10017702021 Mayank Tewari BCA 4B


public void calc_peri(){
r_peri = 2*(l+b);
}
public void display(){
System.out.println("Area of rectangle is: "+r_area);
System.out.println("Perimeter of rectangle is: "+r_peri);
}
}

class Square implements Shape{


int a = 5;
int s_area, s_peri;
public void calc_area(){
s_area = a*a;
}
public void calc_peri(){
s_peri = 4*a;
}
public void display(){
System.out.println("Area of square is: "+s_area);
System.out.println("Perimeter of square is: "+s_peri);
}
}

class Q15{
public static void main(String[] args){
Square sob = new Square();
sob.calc_area();
sob.calc_peri();
sob.display();
Rectangle rob = new Rectangle();
rob.calc_area();

10017702021 Mayank Tewari BCA 4B


rob.calc_peri();
rob.display();
Circle cob = new Circle();
cob.calc_area();
cob.calc_peri();
cob.display();
}
}

OUTPUT

Program – 16
Write a program to show multiple inheritance.
CODE
import java.util.*;
interface adder{
void add();
void sub();
}
interface multiplier{
void mul();
void div();
}
class Mycalc implements adder, multiplier{
int a,b;
Mycalc(int x, int y){
a = x;
10017702021 Mayank Tewari BCA 4B
b = y;
}
public void add(){
System.out.println("Sum is :"+(a+b));
}
public void sub(){
System.out.println("Sub is :"+(a-b));
}
public void mul(){
System.out.println("Multiplier is :"+(a*b));
}
public void div(){
System.out.println("Division is :"+(a/b));
}
}
class Q16{
public static void main(String[] args){
Mycalc c = new Mycalc(8,2);
c.add();
c.sub();
c.mul();
c.div();
}
}

OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 17
Write a program 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.*;
public class Q17 {
public static void main(String[] args) {
int a, b;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Two numbers: ");
a = sc.nextInt();
b = sc.nextInt();
try{
int d = a/b;
System.out.println("Answer is: "+d);
}
catch(ArithmeticException e){
System.out.println("Exception Caught: Division by zero.");
}
catch(Exception e){
System.out.println("Exception caught: "+e);
}
finally{
System.out.println("Finally block will executed.");}}}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 18
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);
}
}
public class Q18 {
public static void main(String[] args) throws NoMatchException {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (num != 10) {
throw new NoMatchException("Number entered is not 10!");
} else {
System.out.println("Number entered is 10.");
}
}
}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 19
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
class NumberPrinter implements Runnable {
private int start;
private int end;

public NumberPrinter(int start, int end) {


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

public void run() {


System.out.println("Thread " + Thread.currentThread().getName() + " started:");
for (int i = start; i <= end; i++) {
System.out.println(i);
}
System.out.println("Exit from " + Thread.currentThread().getName());
}
}

class ThreadNumber {
public static void main(String[] args) {
NumberPrinter printer1 = new NumberPrinter(1, 4);
NumberPrinter printer2 = new NumberPrinter(5, 9);
NumberPrinter printer3 = new NumberPrinter(10, 15);

Thread thread1 = new Thread(printer1, "Thread 1");


Thread thread2 = new Thread(printer2, "Thread 2");
Thread thread3 = new Thread(printer3, "Thread 3");

thread1.setPriority(Thread.MIN_PRIORITY);

10017702021 Mayank Tewari BCA 4B


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

System.out.println("Started " + thread1.getName());


thread1.start();

System.out.println("Started " + thread2.getName());


thread2.start();

System.out.println("Started " + thread3.getName());


thread3.start();
}
}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 20
WAP to print even & odd numbers using threads.
import java.util.*;
class Even extends Thread{
public void run(){
for(int i=2; i<=20; i+=2){
System.out.println("from Thread Even: "+i);
}}
}
class Odd extends Thread{
public void run(){
for(int j=1; j<=19; j+=2){
System.out.println("from Thread Odd: "+j);
}}
}
class Q20{
public static void main(String[] args){
Even e = new Even();
Odd o = new Odd();
e.start();
o.start();
}}

OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 21
WAP that implements the concept of synchronization in threads using both syncronized method and
synchronized block.
CODE
import java.util.*;
class Buying implements Runnable{
int item_avail = 1;
synchronized public void run(){
System.out.println("Items available: "+item_avail);
if(item_avail!=0){
System.out.println("order placed successfully");
try{
Thread.sleep(1000);
item_avail = 0;
}
catch(InterruptedException e){}
}
else{
System.out.println("Sorry, out of stock..");}
}}
class Q21{
public static void main(String[] args){
Buying ob = new Buying();
Thread t1 = new Thread(ob);
Thread t2 = new Thread(ob);
t1.start();
t2.start();
}}

10017702021 Mayank Tewari BCA 4B


Program – 22
WAP that demonstrates the use of sleep and join methods in thread. Use minimum three threads.

CODE
class Table4 extends Thread{
public void run(){
for(int i=4;i<=40; i+=4){
try{
Thread.sleep(500);
System.out.println("Printing table of 4: "+i);
}
catch(InterruptedException e){
System.out.println(e); }
}
}
}
class Table11 extends Thread{
public void run(){
for(int i=11; i<=110; i+=11){
try{
Thread.sleep(5000);
System.out.println("Printing table of 11: "+i);
}
catch(InterruptedException e){
System.out.println(e); }
}
}
}
class Table5 extends Thread{
public void run(){
for(int i=5; i<=50; i+=5){
try{
Thread.sleep(10000);
System.out.println("Printing table of 5: "+i);
}
catch(InterruptedException e){
System.out.println(e); }
}
}
}
class TableThd{
public static void main(String[] args){
Table4 t = new Table4();
Table11 t1 = new Table11();
Table5 t2 = new Table5();
t.start();
t1.start();
t2.start();
}
}

10017702021 Mayank Tewari BCA 4B


OUTPUT

Program – 23
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 str1 = "Hello";
String str2 = "Hello";
String str3 = "World";
System.out.println("Using equals():");
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str3));

String trimmedStr = str1.trim();


10017702021 Mayank Tewari BCA 4B
System.out.println("\nUsing trim():");
System.out.println("Original String: '" + str1 + "'");
System.out.println("Trimmed String: '" + trimmedStr + "'");
System.out.println("\nUsing length():");
System.out.println("Length of str2: " + str2.length());
System.out.println("Length of str3: " + str3.length());

String str7 = "Hello, World!";


String sub1 = str7.substring(7);
String sub2 = str7.substring(0, 5);
System.out.println("\nUsing substring():");
System.out.println("Sub1: " + sub1); // "World!"
System.out.println("Sub2: " + sub2); // "Hello"

String str8 = "Apple";


String str9 = "Banana";
System.out.println("\nUsing compareTo():");
System.out.println(str8.compareTo(str9)); // negative value (-1)
System.out.println(str9.compareTo(str8)); // positive value (1)
System.out.println(str8.compareTo(str8)); // 0
}}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 24
CODE
import java.io.*;
class FileCopy {
public static void main(String[] args) {
try {
File sourceFile = new File("source.txt");
File destinationFile = new File("destination.txt");
BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(destinationFile));
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}}}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 25
Write a Program 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.*;
import java.awt.Font;

class Abc extends JFrame implements MouseMotionListener, MouseListener{


JLabel l1;
Abc(){
l1 = new JLabel("Print over here");
addMouseMotionListener(this);
addMouseListener(this);
add(l1);
setVisible(true);
setSize(500, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void mouseClicked(MouseEvent ae){
l1.setText("Mouse is Clicked");
getContentPane().setBackground(Color.YELLOW);
l1.setForeground(Color.RED);
}
public void mouseReleased(MouseEvent ae){
l1.setText("Mouse is Released");
getContentPane().setBackground(Color.GREEN);
l1.setForeground(Color.YELLOW);
}
public void mousePressed(MouseEvent ae){
l1.setText("Mouse is Pressed");
getContentPane().setBackground(Color.WHITE);
10017702021 Mayank Tewari BCA 4B
l1.setForeground(Color.BLACK);
}
public void mouseExited(MouseEvent ae){
l1.setText("Mouse is Exited");
getContentPane().setBackground(Color.CYAN);
l1.setForeground(Color.MAGENTA);
}
public void mouseEntered(MouseEvent ae){
l1.setText("Mouse is Entered");
getContentPane().setBackground(Color.ORANGE);
l1.setForeground(Color.BLACK);
}
public void mouseDragged(MouseEvent ae){
getContentPane().setBackground(Color.RED);
l1.setText("Mouse id Dragged");
}
public void mouseMoved(MouseEvent ae){
getContentPane().setBackground(Color.GREEN);
l1.setText("Mouse is Moved");
}
}

class Mouse_Swings2{
public static void main(String[] args){
Abc mobj = new Abc();
}
}

10017702021 Mayank Tewari BCA 4B


OUTPUT

Commented [Ma1]:

Program – 26
WAP to implement keyboard events.
CODE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Font;

class Key_Test extends JFrame implements KeyListener{


JLabel l1;
Key_Test(){
l1 = new JLabel(" ");
l1.setFont(new Font("Verdana", Font.PLAIN, 30));
addKeyListener(this);
add(l1);
10017702021 Mayank Tewari BCA 4B
setVisible(true);
setSize(300, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void keyTyped(KeyEvent ke){
l1.setText("You have Typed "+ke.getKeyChar());
}
public void keyPressed(KeyEvent ke){
l1.setText("You have Pressed");
}
public void keyReleased(KeyEvent ke){
l1.setText("You have Released");
}
}

class Key_Swings{
public static void main(String[] args){
Key_Test kobj = new Key_Test();
}
}
OUTPUT

Program – 27
WAP that creates a button in Swings. On clicking the button, the content of the button should be
displayed on a label.
CODE
import java.awt.*;
10017702021 Mayank Tewari BCA 4B
import java.awt.event.*;
import javax.swing.*;

class ButtonTest implements ActionListener{


JFrame frame;
JButton button1, button2, button3;
JLabel l1;
ButtonTest(){
frame = new JFrame("Button Test");
button1 = new JButton("X");
button2 = new JButton("Y");
button3 = new JButton("Z");
l1 = new JLabel("Print Here", SwingConstants.LEFT);
frame.setLayout(new FlowLayout());
frame.add(l1);
frame.add(button1);
frame.add(button2);
frame.add(button3);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
frame.setVisible(true);
frame.setSize(300, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == button1) {
System.out.println("X Button Clicked!");
l1.setText("You clicked 'X'");
frame.getContentPane().setBackground(Color.RED);
}
else if (ae.getSource() == button2) {

10017702021 Mayank Tewari BCA 4B


System.out.println("Y Button Clicked!");
l1.setText("You clicked 'Y'");
frame.getContentPane().setBackground(Color.BLUE);
}
else if (ae.getSource() == button3) {
System.out.println("Z Button Clicked!");
l1.setText("You clicked 'Z'");
frame.getContentPane().setBackground(Color.GREEN);
}}}

class Button_Test{
public static void main(String[] args){
ButtonTest b = new ButtonTest();
}
}
OUTPUT

Program – 28
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 java.awt.*;

10017702021 Mayank Tewari BCA 4B


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

class ButtonTest implements ActionListener{


JFrame frame;
JButton button1, button2, button3;
JLabel l1;
ButtonTest(){
frame = new JFrame("Button Test");
button1 = new JButton("Red");
button2 = new JButton("Yellow");
button3 = new JButton("Green");
l1 = new JLabel("Current Status", SwingConstants.LEFT);
frame.setLayout(new FlowLayout());
frame.add(l1);
frame.add(button1);
frame.add(button2);
frame.add(button3);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
frame.setVisible(true);
frame.setSize(300, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == button1) {
System.out.println("X Button Clicked!");
l1.setText("Signal is RED, Stop!!");
frame.getContentPane().setBackground(Color.RED);
}
else if (ae.getSource() == button2) {

10017702021 Mayank Tewari BCA 4B


System.out.println("Y Button Clicked!");
l1.setText("Signal is YELLOW, Wait..");
frame.getContentPane().setBackground(Color.YELLOW);
}
else if (ae.getSource() == button3) {
System.out.println("Z Button Clicked!");
l1.setText("Signal is GREEN, Go>>");
frame.getContentPane().setBackground(Color.GREEN);
}
}
}

class Button_Test2{
public static void main(String[] args){
ButtonTest b = new ButtonTest();
}
}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 29
WAP using AWT to create a simple calculator. Integer.parseInt(String val)
CODE
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

class Calculator2 implements ActionListener {


JFrame frame;
JTextField textField;
JButton[] numberButtons;
JButton buttonPlus, buttonMinus, buttonMultiply, buttonDivide, buttonEquals, buttonClear;

Calculator2() {
frame = new JFrame("Calculator");
frame.setLayout(new FlowLayout());

textField = new JTextField(20);


textField.setEditable(false);

numberButtons = new JButton[10];


for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].addActionListener(this);
}

buttonPlus = new JButton("+");


buttonMinus = new JButton("-");
buttonMultiply = new JButton("*");
buttonDivide = new JButton("/");
buttonEquals = new JButton("=");
buttonClear = new JButton("C");

10017702021 Mayank Tewari BCA 4B


buttonPlus.addActionListener(this);
buttonMinus.addActionListener(this);
buttonMultiply.addActionListener(this);
buttonDivide.addActionListener(this);
buttonEquals.addActionListener(this);
buttonClear.addActionListener(this);

frame.add(textField);
for (int i = 1; i < 10; i++) {
frame.add(numberButtons[i]);
}
frame.add(buttonPlus);
frame.add(buttonMinus);
frame.add(buttonMultiply);
frame.add(buttonDivide);
frame.add(numberButtons[0]);
frame.add(buttonEquals);
frame.add(buttonClear);

frame.setSize(200, 250);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String command = e.getActionCommand();

switch (command) {
case "0":
case "1":
case "2":
case "3":

10017702021 Mayank Tewari BCA 4B


case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
textField.setText(textField.getText() + command);
break;
case "+":
case "-":
case "*":
case "/":
textField.setText(textField.getText() + " " + command + " ");
break;
case "=":
String expression = textField.getText();
String[] parts = expression.split(" ");

if (parts.length == 3) {
int num1 = Integer.parseInt(parts[0]);
int num2 = Integer.parseInt(parts[2]);
int result = 0;

switch (parts[1]) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;

10017702021 Mayank Tewari BCA 4B


break;
case "/":
result = num1 / num2;
break;
}

textField.setText(expression + " = " + result);


} else {
textField.setText("Invalid expression");
}
break;
case "C":
textField.setText("");
break;
}
}

public static void main(String[] args) {


Calculator2 calculator = new Calculator2();
}}
OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 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.

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

class ColorForm implements ActionListener {


JFrame frame;
JLabel namel, passwordl;
JTextField nametf, passwordtf;
JButton button1;
JCheckBox redCheckBox, greenCheckBox, blueCheckBox;
JPanel canvas;

ColorForm() {
frame = new JFrame("Login Form");
frame.setLayout(new FlowLayout());
namel = new JLabel("Name");
passwordl = new JLabel("Password");
nametf = new JTextField(20);
passwordtf = new JTextField(20);
button1 = new JButton("Login");
button1.addActionListener(this);

redCheckBox = new JCheckBox("Red");


greenCheckBox = new JCheckBox("Green");
blueCheckBox = new JCheckBox("Blue");

canvas = new JPanel();


canvas.setPreferredSize(new Dimension(30, 30));

frame.add(namel);
frame.add(nametf);
frame.add(passwordl);
frame.add(passwordtf);
frame.add(redCheckBox);
frame.add(greenCheckBox);
frame.add(blueCheckBox);
frame.add(canvas);
frame.add(button1);
frame.setSize(300, 400);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == button1) {
String name = nametf.getText();
String password = passwordtf.getText();
System.out.println("Name: " + name);
10017702021 Mayank Tewari BCA 4B
System.out.println("Password: " + password);
}

Color backgroundColor = Color.WHITE; // Default background color

if (redCheckBox.isSelected()) {
backgroundColor = Color.RED;
}
if (greenCheckBox.isSelected()) {
backgroundColor = Color.GREEN;
}
if (blueCheckBox.isSelected()) {
backgroundColor = Color.BLUE;
}

canvas.setBackground(backgroundColor);
}

public static void main(String[] args) {


ColorForm cf = new ColorForm();
}
}

OUTPUT

Program – 31
10017702021 Mayank Tewari BCA 4B
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 javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class LoginForm1 implements ActionListener, ItemListener {
JFrame frame;
JLabel namel, passwordl;
JTextField nametf, passwordtf, checkboxtf;
JButton button1;
JCheckBox ch1, ch2, ch3;
JList<String> sl;
JRadioButton b1, b2;
LoginForm1() {
frame = new JFrame("Login Form");
frame.setLayout(new FlowLayout());
namel = new JLabel("Name");
passwordl = new JLabel("Password");
nametf = new JTextField(20);
passwordtf = new JTextField(20);
checkboxtf = new JTextField(20);
checkboxtf.setEditable(false);
button1 = new JButton("Login");
button1.addActionListener(this);

ch1 = new JCheckBox("C++", false);


ch1.addItemListener(this);
ch2 = new JCheckBox("Java", true);
ch2.addItemListener(this);
ch3 = new JCheckBox("Python", false);
ch3.addItemListener(this);
b1 = new JRadioButton("Male");
b1.addActionListener(this);
b2 = new JRadioButton("Female");
10017702021 Mayank Tewari BCA 4B
b2.addActionListener(this);
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
DefaultListModel<String> l6 = new DefaultListModel<>();
l6.addElement("Item1");
l6.addElement("Item2");
sl = new JList<>(l6);
frame.add(namel);
frame.add(nametf);
frame.add(passwordl);
frame.add(passwordtf);
frame.add(ch1);
frame.add(ch2);
frame.add(ch3);
frame.add(b1);
frame.add(b2);
frame.add(sl);
frame.add(checkboxtf);
frame.add(button1);
frame.setSize(300, 400);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
System.out.println("Male selected");
} else if (e.getSource() == b2) {
System.out.println("Female selected");
} else if (e.getSource() == button1) {
String name = nametf.getText();
String password = passwordtf.getText();
System.out.println("Name: " + name);
System.out.println("Password: " + password);
}

10017702021 Mayank Tewari BCA 4B


}
public void itemStateChanged(ItemEvent e) {
JCheckBox checkbox = (JCheckBox) e.getSource();
if (checkbox.isSelected()) {
checkboxtf.setText(checkboxtf.getText() + checkbox.getText() + " ");
} else {
String text = checkboxtf.getText().replace(checkbox.getText() + " ", "");
checkboxtf.setText(text);
}
}
public static void main(String[] args) {
LoginForm1 lf = new LoginForm1();
}
}

OUTPUT

10017702021 Mayank Tewari BCA 4B


Program – 32
Create a program using Combobox and TextField as per the below figure:

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

class ComboBox1 implements ActionListener {


JFrame frame;
JComboBox<String> comboBox;
JTextField textField;

ComboBox1() {
frame = new JFrame("ComboBox Example");
frame.setLayout(new FlowLayout());

String[] items = {"Option 1", "Option 2", "Option 3", "Option 4", "Option 5"};

comboBox = new JComboBox<>(items);


comboBox.addActionListener(this);

textField = new JTextField(15);

frame.add(comboBox);
frame.add(textField);
frame.setSize(300, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {


String selectedItem = (String) comboBox.getSelectedItem();
textField.setText(selectedItem);
}

public static void main(String[] args) {


ComboBox1 example = new ComboBox1();
}
}

OUTPUT

Program – 33
10017702021 Mayank Tewari BCA 4B
WAP to show all Layout managers. (4 Layout managers).

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

class LayoutManager implements ActionListener{


JFrame f;
JButton b1, b2, b3, b4;
JLabel l1;
LayoutManager(){
f = new JFrame("Layout Manager");
l1 = new JLabel("Status");
f.add(l1);
f.setLayout(new BorderLayout());
b1 = new JButton("North");
f.add(b1, BorderLayout.NORTH);
f.add(b1);
b2 = new JButton("South");
f.add(b2, BorderLayout.SOUTH);
f.add(b2);
b2.addActionListener(this);
b3 = new JButton("East");
f.add(b3, BorderLayout.EAST);
f.add(b3);
b3.addActionListener(this);
b4 = new JButton("West");
f.add(b4, BorderLayout.WEST);
f.add(b4);
b4.addActionListener(this);
f.setLayout(new FlowLayout(FlowLayout.CENTER));
f.setLayout(new GridLayout(4, 5, 10, 10));
for(int i = 1; i <=20; i++){
JButton btn = new JButton("Button "+ Integer.toString(i));
f.add(btn);
}
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(650, 650);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == b1){
System.out.println("Button 1 pressed");}
else if(ae.getSource() == b2){
System.out.println("Button 2 pressed");}
else if(ae.getSource() == b3){
System.out.println("Button 3 pressed");}
else if(ae.getSource() == b4){
System.out.println("Button 4 pressed");
}
}
}

class Layout{
public static void main(String[] args){
LayoutManager lm = new LayoutManager();
}

10017702021 Mayank Tewari BCA 4B


}

OUTPUT

Program – 34
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

10017702021 Mayank Tewari BCA 4B


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

10017702021 Mayank Tewari BCA 4B


}

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

10017702021 Mayank Tewari BCA 4B


String name = nameField.getText();
String dept = deptField.getText();

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) {
10017702021 Mayank Tewari BCA 4B
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();
}
}
}

public static void main(String[] args) {


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

OUTPUT

10017702021 Mayank Tewari BCA 4B

You might also like