JAVA LAB MANNUAL- M
JAVA LAB MANNUAL- M
Laboratory Manual
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
II Year I Semester(R-23)
II Year – I Semester L T P C
0 0 3 2
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
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
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:
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.
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
Program:
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:
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:
Output:
java.lang.ArithmeticException: / by zero
Output:
java.lang.StringIndexOutOfBoundsException: String index out of range: 24
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
{
Output:
java.lang.ArrayIndexOutOfBoundsException: 6
a)creation of illustrating throw
Program:
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:
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);
}
}
}
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 ()
Program:
Program:
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);
}
}
}
// 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);
}
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
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 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);
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (i != null) {
g.drawImage(i, 0, 0, this);
}
}
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.*;
SimpleDateFormat formatter
= new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );
Date date = cal.getTime();
timeString = formatter.format( date );
AnalogClock.html
<html>
<body>
<applet code="MyClock.class" width="300" height="300">
</applet>
</body>
</html>
if (threadSuspended) {
synchronized (this) {
while (threadSuspended) {
wait();
}
}
}
repaint();
Thread.sleep(1000); // interval specified in milliseconds
}
} catch (Exception e) {
e.printStackTrace();
}
}
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 {
// 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 MousePositionTracker() {
// Set the frame properties
setTitle("Mouse Position Tracker");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
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 KeyEventApp() {
// Set up the JFrame
setTitle("Key Event Example");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// 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
}
// 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;
public Calculator() {
// Set up JFrame
setTitle("Calculator");
setSize(420, 550);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
// 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);
}
add(panel);
setVisible(true);
}
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));
}
}
}
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 DigitalClock() {
// Set up the frame
setTitle("Digital Clock");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
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;
// 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
public BouncingBall() {
// Timer calls actionPerformed every 10 milliseconds (controls speed of the animation)
timer = new Timer(10, this);
timer.start(); // Start the timer
}
// 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;
}
// 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();
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;