Java Lab Manual
Java Lab Manual
EXERCISE-1
1-a) Write a JAVA program to display default value of all primitive data types of JAVA
class DefaultValues
{
byte b;
short s;
int i;
long l;
float f;
double d;
char c;
boolean bl;
String s;
public static void main(String[] args)
{
DefaultValues df=new
DefaultValues();
System.out.println("Byte :"+df.b);
System.out.println("Short :"+df.s);
System.out.println("Int :"+df.i);
System.out.println("Long :"+df.l);
System.out.println("Float :"+df.f);
System.out.println("Double :"+df.d);
System.out.println("Char :"+df.c);
System.out.println("Boolean :"+df.bl
);
System.out.println("String :"+df.s);
}
}
output:
javac DefaultValues.java
java DefaultValues
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0
Char :
Boolean :false
String: null
M.HANUMANTHARAO ,KITS, GUNTUR Page 1
JAVA PROGRAMMING LAB MANUAL
1-b) Write a JAVA program that display the roots of quadratic equation ax2+bx+c=0.
import java.util.Scanner;
public class Quadratic_Equation
{
public static void main(String[] args)
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
double sq = Math.sqrt(b * b - 4 * a * c);
double root1 = (-b+sq)/(2*a); double
root2 = (-b-sq)/(2*a);
System.out.println("First root
is:"+root1); System.out.println("Second
root is:"+root2);
}
}
output:
javac Quadratic_Equation.java
java Quadratic_Equation 1 6 9
First root is:-3.0
Second root is:-3.0
1-c). Five Bikers Compete in a race such that they drive at a constant speed which may
or may not be the same as the other. To qualify the race, the speed of a racer must be
more than the average speed of all 5 racers. Take as input the speed of each racer and
print back the speed of qualifying racers.
import java.io.*;
import java.util.*;
class BikeRacers
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int speed[]=new int[5];
for(int i=0;i<5;i++)
{
System.out.print("\nEnter the speed of
Racer-"+i+": "); speed[i]=sc.nextInt();
}
int sum=0;
for(int i=0;i<5;i++)
sum+=speed[i];
double avg=sum/5;
M.HANUMANTHARAO ,KITS, GUNTUR Page 2
JAVA PROGRAMMING LAB MANUAL
1-d) Write a case study on public static void main (250 words)
Ans:
public : is an Access Modifier, which defines who can access this Method. Public
means that this Method will be accessible by any Class (If other Classes are able to
access this Class.).
static methods are the methods, which can be called and executed without creating
the objects. Since we want to call main() method without using an object, we should
declare main () method as static.
void : is used to define the Return Type of the Method. It defines what the method can
return. Void means the Method will not return any value.
main: is the name of the Method. This Method name is searched by JVM as a starting
point for an application with a particular signature only.
String args[ ] : is the parameter to the main Method.
EXERCISE - 2
2-a). Write a JAVA program to search for an element in a given list of elements using
binary search mechanism.
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search,
array[]; boolean status=false;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of elements");
n = sc.nextInt();
array = new int[n];
System.out.print("\nEnter " + n + " integers");
System.out.print("\nEnter value to
find"); search = sc.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
status=true;
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (status=true)
System.out.println(search + " found at
location " + (middle + 1) + ".");
else
System.out.println(search + " is not present
in the list.\n");
M.HANUMANTHARAO, KITS, GUNTUR Page 4
JAVA PROGRAMMING LAB MANUAL
}
}
output
:
java BinarySearch
Enter number of elements 5
Enter 5 integers 12 14 15 18 20
Enter value to find 15
15 found at location 3
2-b). Write a JAVA program to sort for an element in a given list of elements
using bubble sort
import java.util.Scanner;
class BubbleSort{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter No. of Elements: ");
int n=sc.nextInt();
int a[]=new int[n];
System.out.print("Enter "+n+" Elements:
"); for(int i=0;i<n;i++)
a[i]=sc.nextInt();
for(int i=0;i<n;i++)
{
for(int j=1;j<n-i;j++)
{
if(a[j]<a[j-1])
{
int t=a[j];
a[j]=a[j-1];
a[j-1]=t;
}
}
}
System.out.print("Array After Bubble Sort
is: "); for(int i=0;i<n;i++)
System.out.print(" "+a[i]);
}
}
Output
:
javac BubbleSort.java
java BubbleSort
Enter No. of Elements: 5
Enter 5 Elements: 9 8 7 6 5 4
Array After Bubble Sort is: 5 6 7 8 9
M.HANUMANTHARAO ,KITS, GUNTUR Page 5
JAVA PROGRAMMING LAB MANUAL
2-c). Write a JAVA program to sort for an element in a given list of elements
using merge sort.
import java.util.Scanner;
class MergeSort
{
void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
/ recursively
sort sort(a, low,
mid); sort(a, mid,
high);
/ merge two sorted
subarrays int[] temp = new
int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j+
+];
else if (j == high)
temp[k] = a[i+
+];
else if (a[j]<a[i])
temp[k] = a[j+
+];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k+
+) a[low + k] =
temp[k];
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter No. of Elements: ");
int n=sc.nextInt();
int a[]=new int[n];
System.out.print("Enter "+n+" Elements:
"); for(int i=0;i<n;i++)
a[i]=sc.nextInt();
MergeSort ms=new MergeSort();
ms.sort(a,0,n);
System.out.print("Array After Merge Sort
is: "); for(int i=0;i<n;i++)
M.HANUMANTHARAO ,KITS, GUNTUR Page 6
JAVA PROGRAMMING LAB MANUAL
System.out.print(" "+a[i]);
}
}
Output
:
javac MergeSort.java
java MergeSort
Enter No. of Elements: 10
Enter 10 Elements: 9 8 7 6 5 4 3 2 1 0
Array After Merge Sort is: 0 1 2 3 4 5 6 7 8 9
class StringBufferExample
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello World");
sb1.delete(0,6);
System.out.println(sb1);
sb1.delete(1,2);
System.out.println(sb1);
}
}
Output:
javac StringBufferExample.java
java StringBufferExample
World
orld
EXERCISE - 3
3-a). Write a JAVA program to implement class mechanism. – Create a class, methods and
invoke them inside main method.
class Person
{
String name;
int age;
void talk()
{
System.out.println("Hello my name is
"+name); System.out.println("and my age is
"+age);
}
}
class Demo
{
public static void main(String args[])
{
Person p = new Person();
p.name="Raju";
p.age=22;
p.talk();
}
}
Output:
Hello my name is Raju
And my age is 22
class Person
{
String name;
int age;
Person()
{
name="Raju";
age=22;
}
Person(String s, int i)
{
name=s;
age=i;
}
void talk()
{
System.out.println("My Name is
"+name); System.out.println("My Age
is "+age);
}
}
class Demo
{
public static void main(String args[])
{
Person p1 = new Person();
System.out.println("p1 hashcode
"+p1.hashCode()); p1.talk();
Person p2 = new Person("Sita",23);
System.out.println(p2.hashCode());
p2.talk();
}
}
Output:
p1 hashcode 705927765
My Name is Raju
My Age is 22
p2 hashcode 705934457
My Name is Sita
My Age is 23
EXERCISE - 4
4-a). Write a JAVA program to implement constructor overloading.
class Box
{
double width, height, depth;
Box()
{
width = height = depth = 0;
}
Box(double len)
{
width = height = depth = len;
}
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
double volume()
{
return width * height * depth;
}
}
public class Test
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mybox3 = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " +
vol); vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " +
vol); vol = mybox3.volume();
System.out.println(" Volume of mybox3 is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mybox3 is 343.0
class MethodOverloading
{
void add(int a,int b)
{
int c = a+b;
System.out.println("The Sum is "+c);
}
void add(int a,int b,int c)
{
int d = a+b+c;
System.out.println("The Sum is "+d);
}
public static void main(String[] args)
{
MethodOverloading m = new MethodOverloading();
m.add(22,31);
m.add(5,27,35);
}
}
Output:
The Sum is 53
The Sum is 67
EXERCISE – 5
class SuperClass
{
void add(int a,int b)
{
int c=a+b;
System.out.println("Addition is "+c);
}
}
class SubClass extends SuperClass
{
void sub(int a,int b)
{
int c=a-b;
System.out.println("Subtraction is "+c);
}
}
class Demo{
public static void main( String args[] )
{
SuperClass s1=new SuperClass();
s1.add(5,6);
SubClass s2=new SubClass();
s2.sub(15,10);
s2.add(15,27);
}
}
Output:
Addition is 11
Subtraction is 5
Addition is 42
b). Write a JAVA program to implement multi level Inheritance
class A
{
void showA()
{
System.out.println("Method A");
}
}
class B extends A
{
void showB()
{
System.out.println("Method B");
}
}
M.HANUMANTHARAO ,KITS, GUNTUR Page 12
JAVA PROGRAMMING LAB MANUAL
class C extends B
{
void showC()
{
System.out.println("Method C");
}
}
class MultiLevel
{
public static void main(String[] args)
{
C c1=new C();
c1.showC();
c1.showB();
c1.showA();
}
}
Output:
Method C
Method B
Method A
c). Write a java program for abstract class to find areas of different shapes
}
class AreaShape extends Shape
{
void findCircle(double r)
{
double a=3.14*r*r;
System.out.println("Area of Circle = "+a);
}
Output:
Area of Circle = 58.0586
Area of Triangle = 13.725
Area of Rectangle = 39.6
EXERCISE – 6
class One
{
int i=10;
void show()
{
System.out.println("Super Class Method i: "+i);
}
}
class Two extends One
{
int i=20;
void show()
{
System.out.println("Sub Class Method i:
"+i); super.show();
System.out.println("Super Class Variable i:
"+super.i);
}
}
class Demo{
public static void main( String args[] )
{
Two t=new Two();
t.show();
}
}
Output:
Sub Class Method i: 20
Super Class Method i: 10
Super Class Variable i: 10
b). Write a JAVA program to implement Interface. What kind of Inheritance can
be achieved?
interface Father
{
double HT=6.2;
void height();
}
interface Mother
{
double HT=5.8;
void color();
}
Output:
Child's Height= 6.0
Child Color= brown
EXERCISE – 7
class Division
{
public static void main(String[] args)
{
try{
System.out.println("WELCOME");
int a=5;
int b=0;
int c=a/b;
System.out.println("The Division is "+c);
}
catch(ArithmeticException ae)
{
System.out.println("Division with zero
is not possible");
}
finally{
System.out.println("LOGOUT");
}
}
}
Output:
WELCOME
Division with zero is not possible
LOGOUT
import java.util.*;
class Division
{
public static void main(String[] args)
{
try{
System.out.println("WELCOME");
Scanner sc=new Scanner(System.in);
System.out.print("Enter a value: ");
int a=sc.nextInt();
System.out.print("Enter b value: ");
int b=sc.nextInt();
int c=a/b;
System.out.println("The Division is "+c);
}
M.HANUMANTHARAO ,KITS, GUNTUR Page 17
JAVA PROGRAMMING LAB MANUAL
catch(InputMismatchException ae)
{
System.out.println("Wrong Input");
}
catch(ArithmeticException ae)
{
System.out.println("Division with zero
is not possible");
}
finally{
System.out.println("LOGOUT");
}
}
}
Output-1: Output-2:
WELCOME WELCOM
E
Enter a value: 5 Enter a value: 5
Enter b value: k Enter b value: k
Wrong Input Division with zero is not possible
LOGOUT LOGOU
T
EXERCISE – 8
class Bank
{
float interest()
{
return 0;
}
}
class SBI extends Bank
{
float interest()
{
return 8.4f;
}
}
class AXIS extends Bank
{
float interest()
{
return 7.3f;
}
}
class RuntimePoly
{
public static void main(String args[])
{
Bank b1=new SBI();
System.out.println("SBI Rate of Interest:
"+b1.interest());
Bank b2=new AXIS();
System.out.println("Axis Rate of Interest:
"+b2.interest());
}
}
In this previous example we have three classes Bank, SBI and AXIS. Bank is a parent
class and SBI and AXIS are child classes. The child classes are overriding the method
interest() of parent class. In this previous example we have child class object assigned
to the parent class reference so in order to determine which method would be called, the type
of the object would be determined at run-time. It is the type of object that determines which
version of the method would be called (not the type of reference).
EXERCISE – 9
Output:
WELCOME
java.lang.NullPointerException: Exception Data
try
{
int m1 = marks[3];
System.out.println("Marks are " + m1);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Size of array greater than
3");
}
}
}
Output:
Hello 1
Size of array greater than 3
System.out.println("Balance is withdrawn");
}
catch(MyException me)
{
System.out.println(me);
}
}
}
Output-1:
WELCOME
Enter amount to withdraw: 26000
MyException: Balance is very high
Output-2:
WELCOME
Enter amount to withdraw: 15000
Balance is withdrawn
Exercise-10
10-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)
Program:
class GoodMorning extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
try{
Thread.sleep(1000);
}
catch(Exception e){}
System.out.println("GoodMorning");
}
}
}
class Hello extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
try{
Thread.sleep(2000);
}
catch(Exception e){}
System.out.println("Hello");
}
}
}
class Welcome extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
try{
Thread.sleep(3000);
}
catch(Exception e){}
System.out.println("Welcome");
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{
Welcome
Hello
Hello
Welcome
Welcome
Welcome
Welcome
Program:
class MyThread extends Thread
{
public void run()
{
System.out.println("r1 ");
try {
Thread.sleep(500);
}
catch(InterruptedException ie) { }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}
Output:
true
r1
r1
true
r2
r2
t1.setDaemon(true);
t1.start();
t2.start();
t3.start();
}
}
Output:
daemon thread work
user thread work
user thread work
M.HANUMANTHARAO ,KITS, GUNTUR Page 27
JAVA PROGRAMMING LAB MANUAL
EXCERCISE-11
11-a).Write a JAVA program Producer Consumer Problem
import java.util.*;
class Producer extends Thread
{
StringBuffer sb=new StringBuffer();
public void run()
{
synchronized(sb)
{
for(int i=1;i<=10;i++)
{
sb.append(i+" : ");
System.out.println("Appending
"); try{
Thread.sleep(100);
}
catch(InterruptedException ie)
{ }
}
sb.notify();
}
}
}
class Consumer extends Thread
{
Producer prod;
Consumer(Producer prod)
{
this.prod=prod;
}
public void run()
{
synchronized(prod.sb)
{
try{
prod.sb.wait();
}
catch(Exception e)
{ }
11-b) Write a case study on thread Synchronization after solving the above
producer consumer problem
Synchronization:
When thread is already acting on an object, preventing any other thread from acting
on the same object is called Thread Synchronization or thread safe. Thread synchronization is
recommended when multiple threads are used on the same object.
In the above Producer-Consumer program we are synchronization on StringBuffer
Object. In the Producer Thread sb.notify()method is sending a notification to the
Consumer thread that the StringBuffer object sb is available, and it can be used now.
Meanwhile, what the Consumer thread is doing? It is waiting for the notification that
the StringBuffer object sb (of Producer class) is available. Here, there is no need of using
sleep() method to go into sleep for some time wait() method stops waiting as soon
as it receives the notification. So there is no time delay to receive the data from the Producer.
EXCERCISE-12
12-a) Write a case study on including in class path in your os environment
of your package.
Setting CLASSPATH:
The CLASSPATH is an environment variable that tells the Java compiler where to
look for class files to import. CLASSPATH is generally set to a directory or a JAR (Java
Archive) file.
To see what is there in currently in CLASSPATH variable in your system. You can type the
command in windows.
echo %CLASSPATH%
Suppose, preceding command has disp1ayed class path as:
C:\rnr;.
This means the current class path is set to rnr directory in C: \ and also to the current
directory represented by dot (.). Our package pack does not exist in either rnr or current
directory. Our package exists in D:\sub, as:
set CLASSPATH=D:\sub;.;%CLASSPATH%
12-b) Write a JAVA program that import and use the defined your package in
the previous Problem
package pack;
public class Addition
{
public void add(int a,int b)
{
int c=a+b;
System.out.println("The sum is "+c);
}
}
To compile the program by using following command,
javac -d . Addition.java
EXCERCISE-13
a).Write a JAVA program to paint like paint brush in applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Painting extends Applet implements
MouseMotionListener {
public void init()
{
addMouseMotionListener(this);
setBackground(Color.white);
}
public void mouseDragged(MouseEvent me)
{
Graphics g=getGraphics();
g.setColor(Color.red);
g.fillOval(me.getX(),me.getY(),5,5
);
}
public void mouseMoved(MouseEvent me){}
}
javac Painting.java
<html>
<applet code="Painting.class" width=700 height=500 >
</applet>
</html>
appletviewer Painting.html
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 );
if ( threadSuspended ) {
synchronized( this ) {
while ( threadSuspended ) {
wait();
}
}
}
repaint();
t.sleep( 1000 );
}
}
catch (Exception e) { }
}
c). Write a JAVA program to create different shapes and fill colors using Applet.
import java.awt.*;
import java.applet.*;
public class DrawShapes extends
Applet {
public void paint(Graphics g)
{
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.setColor(Color.blue);
g.fillRect(60,10,30,80);
g.setColor(Color.green);
g.drawLine(100,140,230,10);
g.drawOval(230,10,200,150);
g.setColor(Color.blue);
g.fillOval(245,25,100,100);
}
}
Output:
EXCERCISE-14
14-a)Write a JAVA program that display the x and y position of the cursor
movement using Mouse.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class DisplayXY extends Applet implements
MouseMotionListener {
int x,y;
String str="";
public void init()
{
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent me)
{
x = me.getX();
y = me.getY();
str = "Mouse Dragged "+x+" , "+y;
repaint();
}
public void mouseMoved(MouseEvent me)
{
x = me.getX();
y = me.getY();
str = "Mouse Moved "+x+" , "+y;
repaint();
}
public void paint(Graphics g)
{
g.drawString(str, x, y);
}
}
Output:
14-b)Write a JAVA program that identifies key-up key-down event user entering
text in a Applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Key extends Applet implements
KeyListener {
int X=20,Y=30;
String msg="";
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent k)
{
showStatus("Key Pressed");
msg="Key Pressed";
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
msg="Key Up";
repaint();
}
public void keyTyped(KeyEvent k)
{
showStatus("Key Typed");
msg="Key Typed";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Output:
EXCERCISE-15
15-a) Write a JAVA program to build a Calculator in Swings
import javax.swing.*;
import java.awt.event.*;
class Calc implements
ActionListener {
JFrame f;
JTextField t;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
JButton bdiv,bmul,bsub,badd,bdec,beq,bdel,bclr;
Calc()
{
f=new JFrame("Calculator");
t=new JTextField();
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b0=new JButton("0");
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
bdec=new JButton(".");
beq=new JButton("=");
bdel=new JButton("\u21d0"); //
bclr=new JButton("C");
t.setBounds(30,40,280,30);
b7.setBounds(40,100,50,40);
b8.setBounds(110,100,50,40);
b9.setBounds(180,100,50,40);
bdiv.setBounds(250,100,50,40);
b4.setBounds(40,170,50,40);
b5.setBounds(110,170,50,40);
b6.setBounds(180,170,50,40);
bmul.setBounds(250,170,50,40);
b1.setBounds(40,240,50,40);
b2.setBounds(110,240,50,40);
M.HANUMANTHARAO ,KITS, GUNTUR Page 37
JAVA PROGRAMMING LAB MANUAL
b3.setBounds(180,240,50,40);
bsub.setBounds(250,240,50,40);
bdec.setBounds(40,310,50,40);
b0.setBounds(110,310,50,40);
beq.setBounds(180,310,50,40);
badd.setBounds(250,310,50,40);
bdel.setBounds(60,380,80,40);
bclr.setBounds(180,380,50,40);
f.add(t);
f.add(b7);
f.add(b8);
f.add(b9);
f.add(bdiv);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(bmul);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(bsub);
f.add(bdec);
f.add(b0);
f.add(beq);
f.add(badd);
f.add(bdel);
f.add(bclr);
f.setLayout(null);
f.setVisible(true);
f.setSize(350,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
badd.addActionListener(this);
bdiv.addActionListener(this);
bmul.addActionListener(this);
bsub.addActionListener(this);
bdec.addActionListener(this);
beq.addActionListener(this);
bdel.addActionListener(this);
bclr.addActionListener(this);
}
{
a=Double.parseDouble(t.getText());
operator=4;
t.setText("");
}
if(e.getSource()==beq)
{
b=Double.parseDouble(t.getText());
switch(operator)
{
case 1: result=a+b; break;
case 2: result=a-b; break;
case 3: result=a*b; break;
case 4: result=a/b; break;
default: result=0;
}
t.setText(""+result);
}
if(e.getSource()==bclr)
t.setText("");
if(e.getSource()==bdel)
{
String s=t.getText();
t.setText("");
for(int i=0;i<s.length()-1;i++)
t.setText(t.getText()
+s.charAt(i));
}
}
public static void main(String...s)
{
new Calc();
}
}
Output:
15-b) Write a JAVA program to display the digital watch in swing tutorial.
import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.util.*;
public class DigitalWatch implements
Runnable {
JFrame f;
Thread t=null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
JButton b;
DigitalWatch()
{
f=new JFrame();
t = new Thread(this);
t.start();
b=new JButton();
b.setBounds(100,100,100,50);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(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 );
b.setText(timeString);
t.sleep( 1000 );
}
}
catch (Exception e) { }
}
public static void main(String[] args)
{
new DigitalWatch();
}
}
public BouncingBall()
{
Thread thread = new Thread() {
public void run() {
while (true) {
width = getWidth();
height = getHeight();
X = X + dx ;
Y = Y + dy;
if (X - radius < 0) {
dx = -dx;
X = radius;
} else if (X + radius > width) {
dx = -dx;
X = width - radius;
}
if (Y - radius < 0) {
dy = -dy;
Y = radius;
} else if (Y + radius > height) {
dy = -dy;
Y = height - radius;
}
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
}
}
M.HANUMANTHARAO ,KITS, GUNTUR Page 43
JAVA PROGRAMMING LAB MANUAL
}
};
thread.start();
}
16-b) Write a JAVA program JTree as displaying a real tree upside down
import javax.swing.*;
import javax.swing.tree.*;
Output: