[go: up one dir, main page]

0% found this document useful (0 votes)
27 views65 pages

JAVA LAB MANNUAL- M

Uploaded by

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

JAVA LAB MANNUAL- M

Uploaded by

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

II B.Tech.

I SEM Regulation: R23

Laboratory Manual

For the course of


Object Oriented Programming Through Java Lab

Branch: CSE /CSM/CAI/CSD/AIML

DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING

OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB MANUAL

For B.Tech CSE/CSM/CAI/CSD/AIML

II Year I Semester(R-23)
II Year – I Semester L T P C
0 0 3 2

OBJECT ORIENTED THROUGH JAVA LAB


Exercise - 1
a). Write a JAVA program to display default value of all primitive data type of JAVA
b). Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate
the discriminate D and basing on value of D, describe the nature of root.

Exercise - 2
a). Write a JAVA program to search for an element in a given list of elements using binary
search mechanism.
b). Write a JAVA program to sort for an element in a given list of elements using bubble sort
c). Write a JAVA program using String Buffer to delete, remove character.

Exercise - 3
a). Write a JAVA program to implement class mechanism. – Create a class, methods and
invoke them inside main method.
b). Write a JAVA program implement method overloading.
c).Write a JAVA program to implement constructor.
d). Write a JAVA program to implement constructor overloading.

Exercise - 4
a). Write a JAVA program to implement Single Inheritance
b). Write a JAVA program to implement multi level Inheritance
c). Write a java program for abstract class to find areas of different shapes

Exercise - 5
a). Write a JAVA program give example for “super” keyword.
b). Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?
c). Write a JAVA program that implements Runtime polymorphism

Exercise - 6
a).Write a JAVA program that describes exception handling mechanism
b).Write a JAVA program Illustrating Multiple catch clauses
c). Write a JAVA program for creation of Java Built-in Exceptions
d).Write a JAVA program for creation of User Defined Exception

Exercise – 7
a). Write a JAVA program that creates threads by extending Thread class .First thread display
“Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the
third display “Welcome” every 3 seconds ,(Repeat the same by implementing Runnable)
b). Write a program illustrating isAlive and join ()
c). Write a Program illustrating Daemon Threads.
d).Write a JAVA program Producer Consumer Problem

Exercise – 8
(a). Write a JAVA program that import and use the user defined packages.
b). Without writing any code , build a GUI that display text in label and image in an
ImageView (use JavaFX)
c). Build a Tip Calculator app using several JavaFX components and learn how to
respond to user interactions with the GUI
Exercise – 9
a. Write a java program that connects to a database using JDBC
b. Write a java program to connect to a database using JDBC and insert values into it.
c. Write a java program to connect to a database using JDBC and delete values form it.
Exercise - 1

a). Write a JAVA program to display default value of all primitive data type of JAVA

Program:
class defaultdemo
{
static byte b;
static short s;
static int i; static
long l; static
float f; static
double d;static
char c;
static boolean bl;
public static void main(String[] args)
{
System.out.println("The default values of primitive data types are:");
System.out.println("Byte :"+b);
System.out.println("Short :"+s);
System.out.println("Int :"+i);
System.out.println("Long :"+l);
System.out.println("Float :"+f);
System.out.println("Double :"+d);
System.out.println("Char :"+c);
System.out.println("Boolean :"+bl);
}
}
Output:
The default values of primitive data types are:
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0
Char : Boolean
:false
1 b) Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculatethe
discriminate D and basing on value of D, describe the nature of root.

Aim: To write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate thediscriminate
D and basing on value of D, describe the nature of root.

Program:
import java.util.*;
class quadraticdemo
{
public static void main(String[] args)
{
int a, b, c; double
r1, r2, D;
Scanner s = new Scanner(System.in); System.out.println("Given
quadratic equation:ax^2 + bx + c");System.out.print("Enter a:");
a = s.nextInt();
System.out.print("Enter b:");b
= s.nextInt();
System.out.print("Enter c:");c
= s.nextInt();
D = b * b - 4 * a * c;
if(D > 0)
{
System.out.println("Roots are real and unequal");r1 = (
- b + Math.sqrt(D))/(2*a);
r2 = (-b - Math.sqrt(D))/(2*a);
System.out.println("First root is:"+r1);
System.out.println("Second root is:"+r2);
}
else if(D == 0)
{
System.out.println("Roots are real and equal");r1 =
(-b+Math.sqrt(D))/(2*a);
System.out.println("Root:"+r1);
}
else
{
System.out.println("Roots are imaginary");
}
}
}
Output:
Given quadratic equation:ax^2 + bx + c
Enter a:2
Enter b:3
Enter c:1
Roots are real and unequal
First root is:-0.5
Second root is:-1.0
Exercise - 2
a) Write a JAVA program to search for an element in a given list of elements using binarysearch mechanism
Aim: To write a JAVA program to search for an element in a given list of elements using binarysearch
mechanism

Program:
import java.util.Scanner;
class binarysearchdemo
{
public static void main(String args[])
{
int n, i, num,first, last, middle;
int a[ ]=new int[20];
Scanner s = new Scanner(System.in);
System.out.println("Enter total number of elements:");n =
s.nextInt();
System.out.println("Enter elements in sorted order:");for (i
= 0; i < n; i++)
a[i] = s.nextInt();
System.out.println("Enter the search value:");
num = s.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( a[middle] < num )
first = middle + 1;
else if ( a[middle] == num )
{
System.out.println("number found");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println( " Number is not found");
}
}

Output:
Enter total number of elements:5
Enter elements:
24689
Enter the search value:8
number found
2 b) Write a JAVA program to sort for an element in a given list of elements using bubble sort
Aim: To write a JAVA program to sort for an element in a given list of elements using bubble sort

Program:
import java.util.Scanner;
class bubbledemo
{
public static void main(String args[])
{
int n, i,j, temp;
int a[ ]=new int[20];
Scanner s = new Scanner(System.in);
System.out.println("Enter total number of elements:");n =
s.nextInt();
System.out.println("Enter elements:");for
(i = 0; i < n; i++)
a[i] = s.nextInt();
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("The sorted elements are:");
for(i=0;i<n;i++)
System.out.print("\t"+a[i]);
}
}

Output:
Enter total number of elements:
10
Enter elements:
3257689140
The sorted elements are:
0 1 2 3 4 5 6 7 8 9
2 c) Write a JAVA program using String Buffer to delete, remove character.
Aim: To write a JAVA program using StringBuffer to delete, remove character

Program:
class stringbufferdemo
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello World");
sb1.delete(0,6);
System.out.println(sb1);
StringBuffer sb2 = new StringBuffer("Some Content");
System.out.println(sb2);
sb2.delete(0, sb2.length());
System.out.println(sb2);
StringBuffer sb3 = new StringBuffer("Hello World");
sb3.deleteCharAt(0);
System.out.println(sb3);
}
}

Output:
World
Some Content

ello World
Exercise - 3
a). Write a JAVA program to implement class mechanism. – Create a class, methods and
invoke them inside main method.
Aim: To write a JAVA program to implement class mechanism. – Create a class, methods and invokethem
inside main method
Programs:
1. no return type and without parameter-list:
class A
{
int l=10,b=20;
void display()
{
System.out.println(l);
System.out.println(b);
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display();
}
}
Output:
10
20
2. no return type and with parameter-list:
class A
{
void display(int l,int b)
{
System.out.println(l);
System.out.println(b);
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display(10,20);
}
}
Output:
10
20

3. return type and without parameter-list


class A
{
int l=10,b=20;
int area()
{
return l*b;
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();int
r=a1.area();
System.out.println("The area is: "+r);
}
}
Output:
The area is:200
4. return type and with parameter-list:
class A
{
int area(int l,int b)
{
return l*b;
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
int r=a1.area(10,20);
System.out.println(“The area is:”+r);
}
}
Output:
The area is:200
3 b)Write a JAVA program implement method overloading.

Aim: To write a JAVA program implement method overloading

Program:

class A
{
int l=10,b=20;
int area()
{
return l*b;
}
int area(int l,int b)
{
return l*b;
}
}
class overmethoddemo
{
public static void main(String args[])
{
A a1=new A();
int r1=a1.area();
System.out.println("The area is: "+r1);int
r2=a1.area(5,20);
System.out.println("The area is: "+r2);
}
}

Output:
The area is: 200
The area is: 100
3 c).Write a JAVA program to implement constructor.
Aim: To write a JAVA program to implement constructor
Programs:
(i) A constructor with no parameters:
class A
{
int l,b;
A()
{
l=10;
b=20;
}
int area()
{
return l*b;
}
}
class constructordemo
{
public static void main(String args[])
{
A a1=new A();
int r=a1.area();
System.out.println("The area is: "+r);

}
}
Output:
The area is:200
(ii) A constructor with parameters
class A
{
int l,b;
A(int u,int v)
{
l=u;
b=v;
}
int area()
{
return l*b;
}
}
class constructordemo
{
public static void main(String args[])
{
A a1=new A(10,20);
int r=a1.area(); System.out.println("The
area is: "+r);
}
}
Output:
The area is:200
3 d). Write a JAVA program to implement constructor overloading.
Aim: To write a JAVA program to implement constructor overloading

Program:

class A
{
int l,b;
A()
{
l=10;
b=20;
}
A(int u,int v)
{
l=u;
b=v;
}
int area()
{
return l*b;
}
}
class overconstructdemo
{
public static void main(String args[])
{
A a1=new A();
int r1=a1.area();
System.out.println("The area is: "+r1);A
a2=new A(30,40);
int r2=a2.area(); System.out.println("The
area is: "+r2);
}
}

Output:
The area is: 200
The area is: 1200
Exercise - 4
a) Write a JAVA program to implement Single Inheritance

Aim: To write a JAVA program to implement Single Inheritance

Program:

class A
{
A(
)
{ System.out.println("Inside A's Constructor");

}
}
class B extends A
{
B()
{
System.out.println("Inside B's Constructor");
}
}
class singledemo
{
public static void main(String args[])
{
B b1=new B();
}
}

Output:
Inside A's Constructor
Inside B's Constructor
4 b) Write a JAVA program to implement multi level Inheritance
Aim: To write a JAVA program to implement multi level Inheritance

Program:

class A
{
A()
{
System.out.println("Inside A's Constructor");
}
}
class B extends A
{
B()
{
System.out.println("Inside B's Constructor");
}
}
class C extends B
{
C()
{
System.out.println("Inside C's Constructor");
}
}
class multidemo
{
public static void main(String args[])
{
C c1=new C();

}
}

Output:
Inside A's Constructor
Inside B's Constructor
Inside C's Constructor
4 C)Write a java program for abstract class to find areas of different shapes

Aim: To write a java program for abstract class to find areas of different shapes

Program:

abstract class shape


{
abstract double area();
}
class rectangle extends shape
{
double l=12.5,b=2.5;
double area()
{
return l*b;
}
}
class triangle extends shape
{
double b=4.2,h=6.5;
double area()
{
return 0.5*b*h;
}
}
class square extends shape
{
double s=6.5;
double area()
{
return 4*s;
}
}
class shapedemo
{
public static void main(String[] args)
{
rectangle r1=new rectangle();
triangle t1=new triangle();
square s1=new square();
System.out.println("The area of rectangle is: "+r1.area());
System.out.println("The area of triangle is: "+t1.area());
System.out.println("The area of square is: "+s1.area());
}
}

Output:
The area of rectangle is: 31.25
The area of triangle is: 13.65 The
area of square is: 26.0
Exercise - 5
a). Write a JAVA program give example for “super” keyword.

Aim: Write a JAVA program give example for “super” keyword

Programs:
(i) Using super to call super class constructor (Without parameters)

class A
{
int l,b;
A()
{
l=10;
b=20;
}
}
class B extends A
{
int h;
B()
{
super();
h=30;
}
int volume()
{
return l*b*h;
}
}
class superdemo
{
public static void main(String args[])
{
B b1=new B();
int r=b1.volume();
System.out.println("The vol. is: "+r);
}
}

Output:
The vol. is:6000
(ii) Using super to call super class constructor (With parameters)
class A
{
int l,b;
A(int u,int v)
{
l=u;
b=v;
}
}
class B extends A
{
int h;
B(int u,int v,int w)
{
super(u,v);
h=w;
}
int volume()
{
return l*b*h;
}
}
class superdemo
{
public static void main(String args[])
{
B b1=new B(30,20,30);
int r=b1.volume();
System.out.println("The vol. is: "+r);
}
}

Output:
The vol. is:18000
5 B) Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?
Aim: To write a JAVA program to implement Interface.
Programs:
(i) First form of interface implementation
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("B's method");
}
}
class C extends B
{
public void callme()
{
System.out.println("C's method");
}
}
class interfacedemo
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.callme();
}
}

Output:
B's method
C's method

(ii) Second form of interface implementation


interface D
{
void display();
}
interface E extends D
{
void show();
}
class A
{
void callme()
{
System.out.println("This is in callme method");
}
}
class B extends A implements E
{
public void display()
{
System.out.println("This is in display method");
}
public void show()
{
System.out.println("This is in show method");
}
}
class C extends B
{
void call()
{
System.out.println("This is in call method");
}
}
class interfacedemo
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.show();
c1.callme();
c1.call();
}
}
Output:
This is in display method
This is in show method
This is in callme method
This is in call method
(iii) Third form of interface implementation
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("This is in B's method");
}
}
class C implements A
{
public void display()
{
System.out.println("This is C's method");
}
}
class interfacedemo
{
public static void main(String args[])
{
B b1=new B();
C c1=new C();
b1.display();
c1.display();
}
}
Output:
This is in B's method
This is C's method
(iv) Fourth form of interface implementation
interface A
{
void display();
}
interface B
{
void callme();
}
interface C extends A,B
{
void call();
}
class D implements C
{
public void display()
{
System.out.println("interface A");
}
public void callme()
{
System.out.println("interface B");
}
public void call()
{
System.out.println("interface C");
}
}
class interfacedemo
{
public static void main(String args[])
{
D d1=new D();
d1.display();
d1.callme();
d1.call();
}
}
Output:
interface A
interface B
interface C
5 C) Write a JAVA program that implements Runtime polymorphism

Program:

Aim: To write a JAVA program that implements Runtime polymorphism

class A
{
void display()
{
System.out.println("Inside A class");
}
}
class B extends A
{
void display()
{
System.out.println("Inside B class");
}
}
class C extends A
{
void display()
{
System.out.println("Inside C class");
}
}
class runtimedemo
{
public static void main(String args[])
{
A a1=new
A(); B b1=new
B(); C c1=new
C();A ref;
ref=c1;
ref.display()
;ref=b1;
ref.display()
;ref=a1;
ref.display()
;
}
}

Output:

Inside C class
Inside B class
Inside A class
Exercise - 6
a) Write a JAVA program that describes exception handling mechanism
Aim: To write a JAVA program that describes exception handling mechanism

Program:
Usage of Exception Handling:

class trydemo
{
public static void main(String args[])
{
try
{
int a=10,b=0;
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("After the catch statement");
}
}

Output:
java.lang.ArithmeticException: / by zero
After the catch statement
6 b).Write a JAVA program Illustrating Multiple catch clauses

Program:

Aim: To write a JAVA program Illustrating Multiple catch clausesclass

multitrydemo
{
public static void main(String args[])
{
try
{
int a=10,b=5;
int c=a/b;
int d[]={0,1};
System.out.println(d[10]);
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("After the catch statement");
}
}

Output:
java.lang.ArrayIndexOutOfBoundsException: 10
After the catch statement
6 c). Write a JAVA program for creation of Java Built-in Exceptions
Aim: To write a JAVA program for creation of Java Built-in Exceptions Programs:

(i) Arithmetic exception


class arithmeticdemo
{
public static void main(String args[])
{
try
{
int a = 10, b = 0;
int c = a/b;
System.out.println (c);
}
catch(ArithmeticException e)
{
System.out.println (e);
}
}
}

Output:
java.lang.ArithmeticException: / by zero

(ii) NullPointer Exception


class nullpointerdemo
{
public static void main(String args[])
{
try
{
String a = null;
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
}
Output:
java.lang.NullPointerException

(iii) StringIndexOutOfBound Exception


class stringbounddemo
{
public static void main(String args[])
{
try
{
String a = "This is like chipping ";
char c = a.charAt(24);
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}

Output:
java.lang.StringIndexOutOfBoundsException: String index out of range: 24

(iv) FileNotFound Exception


import java.io.*;
class filenotfounddemo
{
public static void main(String args[])
{
try
{
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
}
Output:
java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified)

(v) NumberFormat Exception

class numberformatdemo
{
public static void main(String args[])
{
try
{
int num = Integer.parseInt ("akki") ;
System.out.println(num);
}
catch(NumberFormatException e)
{
System.out.println(e);
}
}
}

Output:
java.lang.NumberFormatException: For input string: "akki"
(vi) ArrayIndexOutOfBounds Exception

class arraybounddemo
{
public static void main(String args[])
{
try
{

int a[] = new int[5];


a[6] = 9;
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println (e);
}
}
}

Output:

java.lang.ArrayIndexOutOfBoundsException: 6
a)creation of illustrating throw

Program:

Aim: To write a JAVA program for creation of Illustrating throw

class throwdemo
{
public static void main(String args[])
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
}

Output:

java.lang.NullPointerException: demo
b) creation of illustrating finally
Aim: To write a JAVA program for creation of Illustrating finally
Program(i):
class finallydemo
{
public static void main(String args[])
{
try
{
int a=10,b=0;
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finall
y
{ System.out.println("This is inside finally block");

}
}
}

Output:
java.lang.ArithmeticException: / by zero
This is inside finally block
Program(ii):
class finallydemo
{
public static void main(String args[])
{
try
{
int a=10,b=5;
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finall
y
{ System.out.println("This is inside finally block");

}
}
}
Output:
2
This is inside finally block
6 D) Write a JAVA program for creation of User Defined Exception
Aim: To write a JAVA program for creation of User Defined Exception Program:

class A extends Exception


{
A(String s1)
{
super(s1);
}
}
class owndemo
{
public static void main(String args[])
{
try
{
throw new A("demo ");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:

A: demo
Exercise – 7 a) Write a JAVA program that creates threads by extending Thread class .First
thread display“Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds
and the third display “Welcome” every 3 seconds ,(Repeat the same by implementing Runnable)

Aim: To write a JAVA program that creates threads by extending Thread class .First thread display “Good
Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third display“Welcome”
every 3 seconds ,(Repeat the same by implementing Runnable)

Programs:
(i) Creating multiple threads using Thread class
class A extends Thread
{
public void run()
{
try
{

for(int i=1;i<=10;i++)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

class B extends Thread


{
public void run()
{ try
{

for(int j=1;j<=10;j++)
{
sleep(2000); System.out.println("hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class C extends Thread
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class threaddemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
a1.start();
b1.start();
c1.start();
}
}
Output:
good morning
hello
good morning
good morning
welcome hello
good morning
good morning
hello
good morning
welcome good
morninghello
good morning
good morning
welcome hello
good morning
hello welcome
hello welcome
hello
hello
welcome
hello
welcome
(ii) Creating multiple threads using Runnable interface
class A implements Runnable
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
Thread.sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B implements Runnable
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
Thread.sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class C implements Runnable
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
Thread.sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class runnabledemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
Thread t1=new Thread(a1);
Thread t2=new Thread(b1);
Thread t3=new Thread(c1);
t1.start();
t2.start();
t3.start();
}
}

Output:
good morning
good morning
hello
good morning
welcome good
morninghello
good morning
good morning
welcome hello
good morning
good morning
hello
good morning
welcome good
morninghello
welcome hello
hello
welcome
hello
welcome
hello
hello
welcome
welcome
welcome
welcome
7 B) Write a program illustrating isAlive and join ()

Aim: To write a program illustrating isAlive and join ()

Program:

class A extends Thread


{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
sleep(1000); System.out.println("good
morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class C extends Thread
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class isalivedemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
a1.start();
b1.start();
c1.start();
System.out.println(a1.isAlive());
System.out.println(b1.isAlive());
System.out.println(c1.isAlive());
try
{
a1.join();
b1.join();
c1.join();
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(a1.isAlive());
System.out.println(b1.isAlive());
System.out.println(c1.isAlive());
}
}
Output:
true true good morning
true hello welcome
good morning hello
good morning hello
hello welcome
good morning hello
welcome good welcome
morninghello hello
good morning hello
good morning welcome
welcome hello welcome
good morning welcome
good morning welcome
hello false
good morning false
welcome false
c)Implementation of Daemon Threads
7 C) Write a Program illustrating Daemon Threads.

Aim: To write a Program illustrating Daemon Threads

Program:

class A extends Thread


{
public void run()
{
if(Thread.currentThread().isDaemon())
System.out.println("daemon thread work");
else
System.out.println("user thread work");
}
}
class daemondemo
{
public static void main(String[] args)
{
A a1=new A();
A a2=new A();
A a3=new A();
a1.setDaemon(true);
a1.start();
a2.start();
a3.start();
}
}

Output:
daemon thread work
user thread work user
thread work
7 d).Write a JAVA program Producer Consumer Problem
Aim: Write a JAVA program Producer Consumer Problem
Program:
class A
{
int n;
boolean b=false;
synchronized int get()
{
if(!b
)try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Got:"+n);
b=false;
notify();
return n;
}
synchronized void put(int n)
{
if(b)try
{

wait();

}
catch(Exception e)
{
System.out.println(e);
}
this.n=n;
b=true;
System.out.println("Put:"+n);
notify();
}
}
class producer implements Runnable
{
A a1;
Thread t1;
producer(A a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int i=1;i<=10;i++)
{
a1.put(i);
}
}
}

class consumer implements Runnable


{
A a1;
Thread t1; consumer(A
a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int j=1;j<=10;j++)
{
a1.get();
}
}
}
class interdemo
{
public static void main(String args[])
{
A a1=new A();
producer p1=new producer(a1);
consumer c1=new consumer(a1);
}
}
Output:
Put:1
Got:1
Put:2
Got:2
Put:3
Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
Put:7
Got:7
Put:8
Got:8
Put:9
Got:9
Put:10
Got:10
Exercise – 8:
(A) AIM: To write a JAVA program, illustrate class path
import java.io.File;

public class App {


public static void main(String[] args) {
// Get the class path
String classPath = System.getProperty("java.class.path");

// Split the class path into individual entries


String[] classPathEntries = classPath.split(File.pathSeparator);

// Print a header
System.out.println("Class Path Entries:");

// Iterate through the class path entries and print each one
for (String entry : classPathEntries) {
System.out.println(entry);
}

// Print the module path if we're using Java 9+


String modulePath = System.getProperty("jdk.module.path");
if (modulePath != null && !modulePath.isEmpty()) {
System.out.println("\nModule Path Entries:");
String[] modulePathEntries = modulePath.split(File.pathSeparator);
for (String entry : modulePathEntries) {
System.out.println(entry);
}
}
}
}
OUT-PUT:
Class Path Entries:
%CLASSPATH%
%JUNIT_HOME%\junit5-main
.
C:\Program Files\junit5-main\JUnit\junit5-main
.
C:\Program Files\junit5-main\JUnit\junit5-main

b) A case study on including in class path in os environment


AIM: To write a case study on including in class path in your os environment of your package.
The differences between path and classpath are given by.
1. The PATH is an environment variable used to locate "java" or "javac" command, to run java
SOURCE-CODE and compile java source file. The CLASSPATH is an environment variable used to
set path for java classes.
2.In order to set PATH in Java, we need to include bin directory in PATH environment while in order
to set CLASSPATH we need to include all directories where we have put either our .class file or JAR
file, which
is required by our Java application.
3.PATH environment variable is used by operating system while CLASSPATH is used by Java
ClassLoaders to load class files.
4.Path refers to the system while classpath refers to the Developing Environment.
→By default the java run time system uses the current working directory.
→Normally to execute a java SOURCE-CODE in any directory we have to set the path by as follows:
set path=c:\SOURCE-CODE Files\java\jdk1.5.0_10\bin;
Setting environmental variable in windows xp:
Step-1:
→Select My computer on the desktop and right click the mouse and then select properties
→It displays the following "System Properties" dialog. System Properties

Step-2:
→In System Properties, click Advanced and then click Environment Variables.
→It displays the following “Environment Variables” dialog.

Step-3:
→In Environment Variables click New in System variables.
→It displays the following “New System Variable” dialog box.

Step-4:
→Now type variable name as a path and then variable value as c:\SOURCE-CODE
Files\java\jdk1.5.0_10\bin;

Step-5:
→ Click OK.

(C). Write a JAVA program that import and use the user defined packages.

Aim: To write a JAVA program that import and use the defined your package in the previous
Problem

(i) Creating a package:


Steps:
1. First declare the name of the package using package keyword
Example: package mypack;
2. Type the following program under this package statement. In package : class ,data, methodsall
are public
package
mypack;
public class
box
{
public int
l=10,b=20;
public void
display()
{
System.out.printl
n(l);
System.out.printl
n(b);
}
}
3. Create sub directory with a name same that of package name under the current working
directory by as follows. d:\>md mypack
4. Under this subdirectory store the above program with a file name “box.java”.
(ii) importing a package:
Steps:
1. packages can be accessed by using the import statement
General form: import
pack1[.pack2].(classname/*); Example: import
java.io.*;
Here pack1 is name of top level package and pack2 is name of sub package
2. Type the following program under the current working directory and save the program with a
file name “example.java”.
import
mypack.box;
class
packagedemo
{
public static void main(String args[])
{
box b1=new
box();
b1.display();
}
}
3. Now compile the above program in the current working directory
d:\javac packagedemo.java
4. Execute the above program in current working
directoryjava packagedemo

Output:
10
20

Exercise -9 (Applet)
a) Paint like Paint Brush in Applet
AIM:To write a JAVA program to paint like paint brush in applet.
SOURCE-CODE:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
//<applet code="paintdemo" width="800" height="500"></applet>
public class paintdemo extends Applet implements MouseMotionListener {
int w, h;
Image i;
Graphics g1;
public void init() {
w = getSize().width;
h = getSize().height;
i = createImage( w, h );
g1 = i.getGraphics();
g1.setColor( Color.white );
g1.fillRect( 0, 0, w, h );
g1.setColor( Color.red );
i = createImage( w, h );
g1 = i.getGraphics();
g1.setColor( Color.white );
g1.fillRect( 0, 0, w, h );
g1.setColor( Color.blue );
addMouseMotionListener( this );
}
public void mouseMoved( MouseEvent e ) { }
public void mouseDragged( MouseEvent me ) {
int x = me.getX();
int y = me.getY();
g1.fillOval(x-10,y-10,20,20);
repaint();
me.consume();
}
public void update( Graphics g ) {
g.drawImage( i, 0, 0, this );
}
public void paint( Graphics g ) {
update(g);
}
}

// After Java11 versions, Applet is deprecated, so, we have to move to either JFrames or Swings
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class PaintApp extends JFrame implements MouseMotionListener {


private int w, h;
private Image i;
private Graphics g1;

public PaintApp() {
setTitle("Paint App");
setSize(800, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
initializeGraphics();
}

@Override
public void componentResized(ComponentEvent e) {
initializeGraphics();
}
});

addMouseMotionListener(this);
}

private void initializeGraphics() {


w = getWidth();
h = getHeight();
i = createImage(w, h);
if (i != null) {
g1 = i.getGraphics();
g1.setColor(Color.white);
g1.fillRect(0, 0, w, h);
g1.setColor(Color.blue);
}
}

public void mouseMoved(MouseEvent e) { }

public void mouseDragged(MouseEvent me) {


if (g1 != null) {
int x = me.getX();
int y = me.getY();
g1.fillOval(x-10, y-10, 20, 20);
repaint();
}
}

@Override
public void paint(Graphics g) {
super.paint(g);
if (i != null) {
g.drawImage(i, 0, 0, this);
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
PaintApp demo = new PaintApp();
demo.setVisible(true);
});
}
}

OUT-PUT:

9b. Aim: Write a JAVA program to display analog clock using Applet.

Source Code:

MyClock.java
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;

public class MyClock extends Applet implements Runnable {

int width, height;


Thread t = null;
boolean threadSuspended;
int hours=0, minutes=0, seconds=0;
String timeString = "";

public void init() {


width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}

public void start() {


if ( t == null ) {
t = new Thread( this );
t.setPriority( Thread.MIN_PRIORITY );
threadSuspended = false;
t.start();
}
else {
if ( threadSuspended ) {
threadSuspended = false;
synchronized( this ) {
notify();
}
}
}
}

public void stop() {


threadSuspended = true;
}

public void run() {


try {
while (true) {

Calendar cal = Calendar.getInstance();


hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );

SimpleDateFormat formatter
= new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
Date date = cal.getTime();
timeString = formatter.format( date );

// Now the thread checks to see if it should suspend itself


if ( threadSuspended ) {
synchronized( this ) {
while ( threadSuspended ) {
wait();
}
}
}
repaint();
t.sleep( 1000 ); // interval specified in milliseconds
}
}
catch (Exception e) { }
}

void drawHand( double angle, int radius, Graphics g ) {


angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
g.drawLine( width/2, height/2, width/2 + x, height/2 + y );
}

void drawWedge( double angle, int radius, Graphics g ) {


angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
angle += 2*Math.PI/3;
int x2 = (int)( 5*Math.cos(angle) );
int y2 = (int)( 5*Math.sin(angle) );
angle += 2*Math.PI/3;
int x3 = (int)( 5*Math.cos(angle) );
int y3 = (int)( 5*Math.sin(angle) );
g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
}

public void paint( Graphics g ) {


g.setColor( Color.gray );
drawWedge( 2*Math.PI * hours / 12, width/5, g );
drawWedge( 2*Math.PI * minutes / 60, width/3, g );
drawHand( 2*Math.PI * seconds / 60, width/2, g );
g.setColor( Color.white );
g.drawString( timeString, 10, height-10 );
}
}

AnalogClock.html

<html>
<body>
<applet code="MyClock.class" width="300" height="300">
</applet>
</body>
</html>

//The latest versions of JDK, applets are deprecated.(After JDK 17)


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

public class MyClock1 extends JPanel implements Runnable {

int width, height;


Thread t = null;
boolean threadSuspended;
int hours = 0, minutes = 0, seconds = 0;
String timeString = "";
public MyClock1() {
setBackground(Color.black);
t = new Thread(this);
t.setPriority(Thread.MIN_PRIORITY);
threadSuspended = false;
t.start();
}

public void run() {


try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get(Calendar.HOUR_OF_DAY);
if (hours > 12) hours -= 12;
minutes = cal.get(Calendar.MINUTE);
seconds = cal.get(Calendar.SECOND);

SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss", Locale.getDefault());


Date date = cal.getTime();
timeString = formatter.format(date);

if (threadSuspended) {
synchronized (this) {
while (threadSuspended) {
wait();
}
}
}
repaint();
Thread.sleep(1000); // interval specified in milliseconds
}
} catch (Exception e) {
e.printStackTrace();
}
}

void drawHand(double angle, int radius, Graphics g) {


angle -= 0.5 * Math.PI;
int x = (int) (radius * Math.cos(angle));
int y = (int) (radius * Math.sin(angle));
g.drawLine(width / 2, height / 2, width / 2 + x, height / 2 + y);
}

void drawWedge(double angle, int radius, Graphics g) {


angle -= 0.5 * Math.PI;
int x = (int) (radius * Math.cos(angle));
int y = (int) (radius * Math.sin(angle));
angle += 2 * Math.PI / 3;
int x2 = (int) (5 * Math.cos(angle));
int y2 = (int) (5 * Math.sin(angle));
angle += 2 * Math.PI / 3;
int x3 = (int) (5 * Math.cos(angle));
int y3 = (int) (5 * Math.sin(angle));
g.drawLine(width / 2 + x2, height / 2 + y2, width / 2 + x, height / 2 + y);
g.drawLine(width / 2 + x3, height / 2 + y3, width / 2 + x, height / 2 + y);
g.drawLine(width / 2 + x2, height / 2 + y2, width / 2 + x3, height / 2 + y3);
}

public void paintComponent(Graphics g) {


super.paintComponent(g);
width = getSize().width;
height = getSize().height;
g.setColor(Color.gray);
drawWedge(2 * Math.PI * hours / 12, width / 5, g);
drawWedge(2 * Math.PI * minutes / 60, width / 3, g);
drawHand(2 * Math.PI * seconds / 60, width / 2, g);
g.setColor(Color.white);
g.drawString(timeString, 10, height - 10);
}

public static void main(String[] args) {


JFrame frame = new JFrame("Clock");
MyClock1 clock = new MyClock1();
frame.getContentPane().add(clock);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Output:

9. C. Write a JAVA program to create different shapes and fill colors using Applet.

Source Code:
import java.applet.*;
import java.awt.*;
public class Shapes extends Applet
{
//Function to initialize the applet
public void init()
{
setBackground(Color.white);
}
//Function to draw and fill shapes
public void paint(Graphics g)
{
//Draw a square
g.setColor(Color.black);
g.drawString("Square",75,200);
int x[]={50,150,150,50};
int y[]={50,50,150,150};
g.drawPolygon(x,y,4);
g.setColor(Color.yellow);
g.fillPolygon(x,y,4);
//Draw a pentagon
g.setColor(Color.black);
g.drawString("Pentagon",225,200);
x=new int[]{200,250,300,300,250,200};
y=new int[]{100,50,100,150,150,100};
g.drawPolygon(x,y,6);
g.setColor(Color.yellow);
g.fillPolygon(x,y,6);
//Draw a circle
g.setColor(Color.black);
g.drawString("Circle",400,200);
g.drawOval(350,50,125,125);
g.setColor(Color.yellow);
g.fillOval(350,50,125,125);
//Draw an oval
g.setColor(Color.black);
g.drawString("Oval",100,380);
g.drawOval(50,250,150,100);
g.setColor(Color.yellow);
g.fillOval(50,250,150,100);
//Draw a rectangle
g.setColor(Color.black);
g.drawString("Rectangle",300,380);
x=new int[]{250,450,450,250};
y=new int[]{250,250,350,350};
g.drawPolygon(x,y,4);
g.setColor(Color.yellow);
g.fillPolygon(x,y,4);
//Draw a triangle
g.setColor(Color.black);
g.drawString("Traingle",100,525);
x=new int[]{50,50,200};
y=new int[]{500,400,500};
g.drawPolygon(x,y,3);
g.setColor(Color.yellow);
g.fillPolygon(x,y,3);
}
}
/*
<applet code = Shapes.class width=600 height=600>
</applet>
*/

//For latest versions like JDK17, applet is deprecated, so, the code will be
import javax.swing.*;
import java.awt.*;
public class Shapes1 extends JPanel {

// Function to initialize the panel


public Shapes1() {
setBackground(Color.white); // Set background color of the panel
}

// Function to draw and fill shapes


public void paintComponent(Graphics g) {
super.paintComponent(g);

// Draw a square
g.setColor(Color.black);
g.drawString("Square", 75, 200);
int x[] = {50, 150, 150, 50};
int y[] = {50, 50, 150, 150};
g.drawPolygon(x, y, 4);
g.setColor(Color.yellow);
g.fillPolygon(x, y, 4);

// Draw a pentagon
g.setColor(Color.black);
g.drawString("Pentagon", 225, 200);
x = new int[]{200, 250, 300, 300, 250, 200};
y = new int[]{100, 50, 100, 150, 150, 100};
g.drawPolygon(x, y, 6);
g.setColor(Color.blue);
g.fillPolygon(x, y, 6);

// Draw a circle
g.setColor(Color.black);
g.drawString("Circle", 400, 200);
g.drawOval(350, 50, 125, 125);
g.setColor(Color.red);
g.fillOval(350, 50, 125, 125);

// Draw an oval
g.setColor(Color.black);
g.drawString("Oval", 100, 380);
g.drawOval(50, 250, 150, 100);
g.setColor(Color.green);
g.fillOval(50, 250, 150, 100);

// Draw a rectangle
g.setColor(Color.black);
g.drawString("Rectangle", 300, 380);
x = new int[]{250, 450, 450, 250};
y = new int[]{250, 250, 350, 350};
g.drawPolygon(x, y, 4);
g.setColor(Color.pink);
g.fillPolygon(x, y, 4);

// Draw a triangle
g.setColor(Color.black);
g.drawString("Triangle", 100, 525);
x = new int[]{50, 50, 200};
y = new int[]{500, 400, 500};
g.drawPolygon(x, y, 3);
g.setColor(Color.cyan);
g.fillPolygon(x, y, 3);
}

// Main function to create the JFrame window and add the Shapes panel
public static void main(String[] args) {
JFrame frame = new JFrame("Shapes");
Shapes1 shapes = new Shapes1();
frame.add(shapes); // Add the Shapes panel to the frame
frame.setSize(600, 600); // Set the size of the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close the application on exit
frame.setVisible(true); // Make the window visible
}
}

Output:

Exercise 10:
10. a. Write a JAVA program that display the x and y position of the cursor movement using Mouse.
Source Coee:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

public class MousePositionTracker extends JFrame implements MouseMotionListener {

private JLabel label;

public MousePositionTracker() {
// Set the frame properties
setTitle("Mouse Position Tracker");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Create a label to display the mouse coordinates


label = new JLabel("Move the mouse to see coordinates");
add(label);

// Add the MouseMotionListener to the frame


addMouseMotionListener(this);
}

// Method called when the mouse is moved


@Override
public void mouseMoved(MouseEvent e) {
// Update label with current mouse coordinates
label.setText("Mouse moved to X: " + e.getX() + ", Y: " + e.getY());
}

// Method called when the mouse is dragged (required by the interface)


@Override
public void mouseDragged(MouseEvent e) {
// Optional: handle mouse dragged event
}

public static void main(String[] args) {


// Create an instance of the frame and make it visible
MousePositionTracker frame = new MousePositionTracker();
frame.setVisible(true);
}
}
Output:

10.b. Write a JAVA program that identifies Key-up, key-down event user entering text in a Applet.
Source Code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/*
<applet code="KeyEventApplet" width=400 height=200>
</applet>
*/

public class KeyEventApplet extends Applet implements KeyListener {

String message = "";


String keyState = "";

// Initialize the applet and add the KeyListener


public void init() {
addKeyListener(this);
requestFocus(); // Set focus to the applet for key events
setBackground(Color.lightGray);
}

// Called when a key is pressed down


@Override
public void keyPressed(KeyEvent e) {
keyState = "Key Down: ";
message = KeyEvent.getKeyText(e.getKeyCode());
repaint(); // Repaint the applet to update the display
}

// Called when a key is released


@Override
public void keyReleased(KeyEvent e) {
keyState = "Key Up: ";
message = KeyEvent.getKeyText(e.getKeyCode());
repaint();
}

// Called when a key is typed (useful for character input)


@Override
public void keyTyped(KeyEvent e) {
// Optional: Handle key typed events if needed
}

// Method to paint the current state on the applet


public void paint(Graphics g) {
g.drawString(keyState + message, 20, 100); // Display key state and key name
}
}
Applet Code:
<html>
<body>
<applet code="KeyEventApplet.class" width="400" height="200"></applet>
</body>
</html>

//After JDK 17 versions, the code using JFrames will be..


import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyEventApp extends JFrame implements KeyListener {

private JLabel label;

public KeyEventApp() {
// Set up the JFrame
setTitle("Key Event Example");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Create a label to display key event details


label = new JLabel("Press any key to see Key Up or Key Down events");
add(label);

// Add the KeyListener to the frame


addKeyListener(this);
setFocusable(true); // Ensure the frame can capture key events
}

// Called when a key is pressed down


@Override
public void keyPressed(KeyEvent e) {
label.setText("Key Down: " + KeyEvent.getKeyText(e.getKeyCode()));
}

// Called when a key is released


@Override
public void keyReleased(KeyEvent e) {
label.setText("Key Up: " + KeyEvent.getKeyText(e.getKeyCode()));
}

// Called when a key is typed (optional, but can be used for character input)
@Override
public void keyTyped(KeyEvent e) {
// You can capture character inputs here if needed
}

public static void main(String[] args) {


// Create an instance of the application window
KeyEventApp app = new KeyEventApp();
app.setVisible(true);
}
}
Output:
Exercise – 11(Swings):
11. a. Aim: Write a JAVA program to build a Calculator in Swings.
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {

// Declare components
private JTextField display;
private JButton[] numberButtons;
private JButton[] functionButtons;
private JButton addButton, subButton, mulButton, divButton;
private JButton decButton, equButton, delButton, clrButton;
private JPanel panel;

// Variables to hold values for calculations


private double num1 = 0, num2 = 0, result = 0;
private char operator;

public Calculator() {
// Set up JFrame
setTitle("Calculator");
setSize(420, 550);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);

// Set up display (text field)


display = new JTextField();
display.setBounds(50, 25, 300, 50);
display.setFont(new Font("Arial", Font.PLAIN, 36));
display.setEditable(false);
add(display);

// Create buttons
numberButtons = new JButton[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].setFont(new Font("Arial", Font.PLAIN, 24));
numberButtons[i].addActionListener(this);
}

// Create function buttons


addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
decButton = new JButton(".");
equButton = new JButton("=");
delButton = new JButton("Del");
clrButton = new JButton("Clr");
functionButtons = new JButton[] {
addButton, subButton, mulButton, divButton, decButton, equButton, delButton, clrButton
};

// Add action listeners for function buttons


for (JButton btn : functionButtons) {
btn.setFont(new Font("Arial", Font.PLAIN, 24));
btn.addActionListener(this);
}

// Create a panel for number and function buttons


panel = new JPanel();
panel.setBounds(50, 100, 300, 400);
panel.setLayout(new GridLayout(5, 4, 10, 10));

// Add buttons to the panel


panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(addButton);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(subButton);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(mulButton);
panel.add(decButton);
panel.add(numberButtons[0]);
panel.add(equButton);
panel.add(divButton);
panel.add(delButton);
panel.add(clrButton);

add(panel);

setVisible(true);
}

// Handle button clicks


@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 10; i++) {
if (e.getSource() == numberButtons[i]) {
display.setText(display.getText().concat(String.valueOf(i)));
}
}

if (e.getSource() == decButton) {
display.setText(display.getText().concat("."));
}

if (e.getSource() == addButton) {
num1 = Double.parseDouble(display.getText());
operator = '+';
display.setText("");
}

if (e.getSource() == subButton) {
num1 = Double.parseDouble(display.getText());
operator = '-';
display.setText("");
}

if (e.getSource() == mulButton) {
num1 = Double.parseDouble(display.getText());
operator = '*';
display.setText("");
}

if (e.getSource() == divButton) {
num1 = Double.parseDouble(display.getText());
operator = '/';
display.setText("");
}

if (e.getSource() == equButton) {
num2 = Double.parseDouble(display.getText());

switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
display.setText(String.valueOf(result));
num1 = result;
}

if (e.getSource() == clrButton) {
display.setText("");
}

if (e.getSource() == delButton) {
String text = display.getText();
display.setText("");
for (int i = 0; i < text.length() - 1; i++) {
display.setText(display.getText() + text.charAt(i));
}
}
}

public static void main(String[] args) {


new Calculator();
}
}
Output:

11.b. Write a JAVA program to display the digital watch in Swing tutorial.
Source Code:
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DigitalClock extends JFrame {

private JLabel timeLabel;


private SimpleDateFormat timeFormat;
private String time;

public DigitalClock() {
// Set up the frame
setTitle("Digital Clock");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Initialize the time label with formatting


timeFormat = new SimpleDateFormat("hh:mm:ss a"); // 12-hour format with AM/PM
timeLabel = new JLabel();
timeLabel.setFont(new Font("Arial", Font.PLAIN, 50));
timeLabel.setForeground(Color.BLUE);

// Add the label to the frame


add(timeLabel);
setVisible(true);

// Create a timer to update the time every second


Timer timer = new Timer(1000, e -> {
updateTime();
});
timer.start();
}

// Method to update time


public void updateTime() {
time = timeFormat.format(Calendar.getInstance().getTime());
timeLabel.setText(time);
}

public static void main(String[] args) {


new DigitalClock();
}
}
Output:

Exercise – 12(Swings):
12. a. Write a JAVA program that to create a single ball bouncing inside a JPanel.
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class BouncingBall extends JPanel implements ActionListener {

// Ball properties
private int ballX = 50; // Initial x-coordinate of the ball
private int ballY = 50; // Initial y-coordinate of the ball
private int ballDiameter = 30; // Diameter of the ball
private int ballXSpeed = 2; // Speed of the ball in the x direction
private int ballYSpeed = 2; // Speed of the ball in the y direction

private Timer timer;

public BouncingBall() {
// Timer calls actionPerformed every 10 milliseconds (controls speed of the animation)
timer = new Timer(10, this);
timer.start(); // Start the timer
}

// Paint the ball and update its position


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

// Set background color


setBackground(Color.WHITE);

// Set color for the ball and draw it


g.setColor(Color.RED);
g.fillOval(ballX, ballY, ballDiameter, ballDiameter);
}

// Method to update the position of the ball


@Override
public void actionPerformed(ActionEvent e) {
// Move the ball
ballX += ballXSpeed;
ballY += ballYSpeed;

// Check for collision with the edges of the JPanel and reverse direction
if (ballX <= 0 || ballX >= getWidth() - ballDiameter) {
ballXSpeed = -ballXSpeed;
}
if (ballY <= 0 || ballY >= getHeight() - ballDiameter) {
ballYSpeed = -ballYSpeed;
}

// Repaint the panel to update the ball's position


repaint();
}

// Main method to create the JFrame and add the BouncingBall panel
public static void main(String[] args) {
JFrame frame = new JFrame("Bouncing Ball");
BouncingBall ballPanel = new BouncingBall();

// Set frame properties


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.add(ballPanel);
frame.setVisible(true);
}
}
Output:

12.b. Write a JAVA program JTree as displaying a real tree upside down.
Source Code:
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
public class UpsideDownTreeExample extends JFrame {
public UpsideDownTreeExample() {
// Create the root of the tree
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Roots");
DefaultMutableTreeNode branch1 = new DefaultMutableTreeNode("Branch 1");
DefaultMutableTreeNode branch2 = new DefaultMutableTreeNode("Branch 2");
DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");
DefaultMutableTreeNode leaf3 = new DefaultMutableTreeNode("Leaf 3");
DefaultMutableTreeNode leaf4 = new DefaultMutableTreeNode("Leaf 4");
// Build the tree structure
branch1.add(leaf1);
branch1.add(leaf2);
branch2.add(leaf3);
branch2.add(leaf4);
root.add(branch1);
root.add(branch2);
// Create the JTree
JTree tree = new JTree(root);
// Invert the tree visually by rotating the panel
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;

// Rotate the component by 180 degrees


g2d.rotate(Math.PI, getWidth() / 2, getHeight() / 2);
super.paintComponent(g2d); // Render the panel's contents
}
};
// Add the tree to the panel
panel.setLayout(new BorderLayout());
panel.add(new JScrollPane(tree));
// Set up the frame
add(panel);
setTitle("Upside Down JTree Example");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
// Run the application
SwingUtilities.invokeLater(UpsideDownTreeExample::new);
}
}
Output:

You might also like