Java Lab Manual r23 Updated
Java Lab Manual r23 Updated
2024–25
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA
KAKINADA–533003, AndhraPradesh, India
DEPARTMENTOFCOMPUTERSCIENCE& ENGINEERING
L T P C
II Year– II Semester
0 0 3 1.5
JAVA PROGRAMMINGLAB
Course Objectives:
The aim of this course is to
Practice object oriented programming in the Java programming language
Implement Classes, Objects, Methods, Inheritance, Exception, Runtime
Polymorphism, User defined Exception handling mechanism
Illustrate inheritance, Exception handling mechanism, JDBC connectivity
Construct Threads, Event Handling, implement packages, Java FX GUI
Experiments covering the Topics:
Object Oriented Programming fundamentals- data types, control structures
Classes, methods, objects, Inheritance, polymorphism,
Exception handling, Threads, Packages, Interfaces
Files, I/O streams, Java FX GUI
Sample Experiments:
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 ax 2+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
R-23SyllabusforCSE, JNTUKw.e.f.2024–25
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA
KAKINADA–533003, AndhraPradesh, India
DEPARTMENTOFCOMPUTERSCIENCE& ENGINEERING
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 is Alive 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.
Exercise-1 (Basics)
a) Displayingdefaultvalueofallprimitivedatatypes
Aim: To writeaJAVAprogramtodisplaydefaultvalueofallprimitivedatatypeofJAVA
Program:
classdefaultdemo
{
static byte
b;static short
s;static int
i;static long
l;static float
f;static
double
d;staticcharc
;
staticbooleanbl;
publicstaticvoidmain(String[]args)
{
System.out.println("The default values of primitive data
typesare:");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("Bool
ean:"+bl);
}
}
Output:
Thedefaultvaluesofprimitivedatatypesare:
Byte:0
Short:0
Int:0
Long:0
Float:0.0
Double :0.0
Char :Boole
an:false
Page1
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
b) Rootsofa quadraticequation
Aim: To write a java program that display the roots of a quadratic equation
ax2+bx=0. Calculatethediscriminate Dandbasingon valueofD,describe the
natureofroot.
Program:
import
java.util.*;classqu
adraticdemo
{
publicstaticvoidmain(String[]args)
{
int a, b,
c;doubler1,r2,
D;
Scanner s = new
Scanner(System.in);System.out.println("Givenquad
raticequation:ax^2+bx+c");System.out.print("Ente
ra:");a=s.nextInt();
System.out.print("Enter
b:");b =
s.nextInt();System.out.p
rint("Enter
c:");c=s.nextInt();
D=b*b-4*a
* c;if(D>0)
{
System.out.println("Rootsarerealandunequa
l");r1=(-b +Math.sqrt(D))/(2*a);
r2 = (-b -
Math.sqrt(D))/(2*a);System.out.pri
ntln("First root
is:"+r1);System.out.println("Secon
drootis:"+r2);
}
elseif(D==0)
{
System.out.println("Rootsarerealandequal
");r1 =
(-b+Math.sqrt(D))/(2*a);System.out.printl
} n("Root:"+r1);
els
e
{
System.out.println("Rootsareimaginary");
}
}
}
Output:
Givenquadratic
equation:ax^2+bx+cEntera:2
Page2
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
Enter
b:3Ente
rc:1
Rootsarerealandunequa
lFirstroot is:-0.5
Secondrootis:-1.0
Page2
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby: G.Mahesh CSE
c) BikeRace
Aim: Five Bikers Compete in a race such that they drive at a constant speed which
may or maynot be the same as the other. To qualify the race, the speed of a racer
must be more than
theaveragespeedofall5racers.Takeasinputthespeedofeachracerandprintbackthespeed
ofqualifying racers.
Program:
import
java.util.*;clas
sracedemo
{
publicstaticvoidmain(String[]args)
{
floats1,s2,s3,s4,s5,average;
Scanner s = new
Scanner(System.in);System.out.println("E
nterspeedoffirstracer:");s1 =s.nextFloat();
System.out.println("Enter speed of second
racer:");s2 =s.nextFloat();
System.out.println("Enterspeedofthirdrace
r:");s3 =s.nextFloat();
System.out.println("Enterspeedoffourthrac
er:");s4 =s.nextFloat();
System.out.println("Enterspeedoffifthrac
er:");s5 =
s.nextFloat();average=(s1+s2+s3+s4+s
5)/5;
if(s1>average)
System.out.println("First racer is qualify
racer:");else if(s2>average)
System.out.println("Second racer is
qualifyracer:"); else
if(s3>average)System.out.println("Third
racer is qualify racer:");else
if(s4>average)
System.out.println("Fourth racer is
qualifyracer:"); else
if(s5>average)System.out.println("Fifthrac
erisqualifyracer:");
}
}
Output:
Enter speed of first
racer:4.5
Enter speed of second
racer:6.7
Enter speed of third
racer:3.8
Enter speed of fourth
racer:5.3
Page3
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby: G.Mahesh CSE
Enterspeedoffifthracer
:4.9
Secondracerisqualifyracer:
Page3
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: S.Mariya Babu CSE
Aim:Acasestudyonpublicstaticvoidmain(250words)Ca
sestudy:
Theprogramstructureof asimplejavaprogramisgivenbelowwithdifferentsteps
Step-
1:Clickstart+runandthentypenotepadinrundialogboxandclickOK.ItdisplaysNotepad.St
ep-2:Inrundialogboxtype cmdand clickOK. Itdisplayscommand prompt.
Step-3: Type the following program in the Notepad and save the program as
“example.java” ina currentworkingdirectory.
classexample
{
publicstaticvoidmain(Stringargs[])
{
System.out.println(“Welcome”);
}
}
Step-4 (Compilation): To compile the program type the following in current
working directoryandthen clickenter.
c:\xxxx>javacexample.java
Step-
5(Execution):Toruntheprogramtypethefollowingincurrentworkingdirectoryandthe
nclickenter.
c:\xxxx>javaexample
Explanation:
Generallythefilename andclassname
shouldbesame.Ifitisnotsamethenthejavafilecanbecompiledbutitcannotbe
executed.Thatiswhenexecution itgivesthefollowingerror
Exceptioninthread"main"java.lang.NoClassDefFoundError:ex
In“publicstaticvoidmain(Stringargs[])”statement
ain()tobecalledwithoutcreatingobjectoftheclass.
We can send some input values (arguments) at run time to the String
args[] of themain method . These arguments are called command line
arguments. Thesecommandlinearguments arepassedat
thecommandprompt.
InSystem.out.println("Welcome");state
mentistheoutput stream.
println()methoddisplaytheoutputindifferentlines.Ifweuseprint()methoditdisplaytheou
tputin thesame line
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: S.Mariya Babu CSE
Page4
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
Exercise-2(Operations,Expressions,Control-flow,Strings)
a) ImplementationofBinarysearchmechanism
Aim: To write a JAVA program to search for an element in a given list of
elements usingbinarysearchmechanism
Program:
import
java.util.Scanner;clas
sbinarysearchdemo
{
publicstaticvoidmain(Stringargs[])
{
int n, i, num,first, last,
middle;int
a[]=newint[20];
Scanner s = new
Scanner(System.in);System.out.println("Entert
otalnumberofelements:"); n = s.nextInt();
System.out.println("Enterelementsin
sortedorder:");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;
elseif(a[middle]==num)
{
System.out.println("numberfou
nd");break;
}
els
e
{ last=middle -1;
}
middle=(first+last)/2;
}
if (first >last)
System.out.println("Numberisnotfound");
}
}
Output:
Page5
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
Enter total number of
elements:5
Enter
elements:246
89
Enterthesearchvalu
e:8
numberfound
Page6
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
b) Bubblesort
Aim:TowriteaJAVAprogramtosortforanelementinagivenlistofelementsusingbubblesort
Program:
import
java.util.Scanner;clas
sbubbledemo
{
publicstaticvoidmain(Stringargs[])
{
intn,i,j,temp;
inta[]=newint[20];
Scanner s = new
Scanner(System.in);System.out.pri
ntln("Entertotalnumberofelements:"
); n =
s.nextInt();System.out.println("Ente
relements:");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]=te
mp;
}
}
}
System.out.println("Thesortedelementsa
re:");for(i=0;i<n;i++)
System.out.print("\t"+a[i]);
}
}
Output:
Entertotalnumberofelements:
10
Enterelements:
3257689140
Thesortedelementsare:
0 1 2 3 4 5 6 7 8 9
Page7
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
c) Mergesort:
Aim:TowriteaJAVAprogramtosortforanelement inagivenlist ofelements usingmergesort
Program:
import
java.util.*;class
mergedemo
{
publicstaticvoidmain(Stringargs[])
{
intn1,n2,i,j,k;
int a[ ]=new
int[20];int
b[ ]=new
int[20];intc[]=ne
wint[20];
Scanner s = new
Scanner(System.in);System.out.println("Enternu
mberofelementsinfirstarray:");n1 =s.nextInt();
System.out.println("Entersortedelementso
ffirstarray:");for(i=0; i<n1; i++)
a[i]=s.nextInt();
System.out.println("Enternumberofelementsinsec
ondarray:");n2 =s.nextInt();
System.out.println("Entersortedelementsofsecon
darray:");for(j=0; j<n2; j++)
b[j] =
s.nextInt();i=0
;
j=0;
k=0;
while((i<n1)&& (j<n2))
{
if(a[i] >b[j])
c[k++]=b[j++];
else
c[k++]=a[i++];
}
while(i <
n1)c[k+
+]=a[i++];
while(j <
n2)c[k+
+]=b[j++];
System.out.println("After merging the elements
are:\n");for(i=0; i<(n1+n2);i++)
System.out.print("\t"+c[i]);
}
}
Output:
Enternumberofelementsinfirstarray:
6
Enterelementsoffirstarray:
8912131518
Page8
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
Enternumberofelementsinsecondarray:
5
Enterelementsof secondarray:
67101120
Aftermergingtheelementsare:
6 7 8 9 10 11 12 13 15 1820
Page9
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
d) ImplementingStringBuffer
Aim:TowriteaJAVAprogramusingStringBuffertodelete,removecharacter
Program:
classstringbufferdemo
{
publicstaticvoidmain(String[]args)
{
StringBuffer sb1 = new
StringBuffer("HelloWorld");
sb1.delete(0,6);System.out.println(sb
1);
StringBuffer sb2 = new StringBuffer("Some
Content");System.out.println(sb2);
sb2.delete(0,sb2.length
());System.out.println(s
b2);
StringBuffer sb3 = new StringBuffer("Hello
World");sb3.deleteCharAt(0);
System.out.println(sb3);
}
}
Output:
World
Some
Contentello
World
Page1
0
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
Exercise-3 (Class,Objects)
a) ImplementingClass&Objects
Aim: To write a JAVA program to implement class mechanism. – Create a class,
methods andinvoke theminsidemain method
Programs:
1. noreturntypeandwithoutparameter-list:
class A
{
int
l=10,b=20;
voiddisplay(
)
{
System.out.println
(l);System.out.prin
tln(b);
}
}
classmethoddemo
{
publicstaticvoidmain(Stringargs[])
{
Aa1=newA()
;a1.display()
} ;
}
Output:
10
20
2. noreturntypeandwithparameter-list:
class A
{
voiddisplay(intl,intb)
{
System.out.println
(l);System.out.prin
tln(b);
}
}
classmethoddemo
{
publicstaticvoidmain(Stringargs[])
{
A a1=new
A();a1.display(1
0,20);
}
}
Output:
10
20
Page1
1
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
Page1
2
IIB.TechIISemCSEJavaLabManual (R20)Preparedby:G.Mahesh CSEintarea()
int area()
{
returnl*b;
}
}
classmethoddemo
{
publicstaticvoidmain(Stringargs[])
{
A a1=new
A();intr=a1.a
rea();
System.out.println("Theareais:"+r);
}
}
Output:
Theareais:200
4. returntypeandwithparameter-list:
class A
{
intarea(intl,intb)
{
returnl*b;
}
}
classmethoddemo
{
publicstaticvoidmain(Stringargs[])
{
Aa1=newA();
int
r=a1.area(10,20);System.out.pr
intln(“Theareais:”+r);
}
}
Output:
Theareais:200
Page13
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
b) ImplementingConstructor
Aim:Towrite aJAVAprogram toimplementconstructor
Programs:
(i) Aconstructorwithnoparameters:
class A
{
int
l,b;A(
)
{ l=10
;b=2
0;
}
intarea()
{
returnl*b;
}
}
classconstructordemo
{
publicstaticvoidmain(Stringargs[])
{
A a1=new
A();intr=a1.a
rea();
System.out.println("Theareais:"+r);
}
}
Output:
Theareais:200
(ii) Aconstructorwithparameters
class A
{
intl,b;
A(intu,intv)
{
l=u
;b=
v;
}
intarea()
{
returnl*b;
}
}
classconstructordemo
{
publicstaticvoidmain(Stringargs[])
{
A a1=newA(10,20);
int
r=a1.area();System.out.println(
Page14
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
"Theareais:"+r);
}
}
Output:
Theareais:200
Page15
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
Exercise-4 (Methods)
a) ConstructorOverloading
Aim:TowriteaJAVAprogramtoimplementconstructoroverloading
Program:
class A
{
int
l,b;A(
)
{
l=10
;b=2
0;
}
A(intu,intv)
{
l=u
;b=
v;
}
intarea()
{
returnl*b;
}
}
classoverconstructdemo
{
publicstaticvoidmain(Stringargs[])
{
A a1=new
A();intr1=a1.a
rea();
System.out.println("The area is:
"+r1);A a2=newA(30,40);
int
r2=a2.area();System.out.println(
"Theareais:"+r2);
}
}
Output:
The area is:
200Theareais:1
200
Page16
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
b) Method
classA
{
int
l=10,b=20;i
nt area()
{
returnl*b;
}
intarea(intl,intb)
{
returnl*b;
}
}
classovermethoddemo
{
publicstaticvoidmain(Stringargs[])
{
A a1=new
A();intr1=a1.a
rea();
System.out.println("The area is:
"+r1);int
r2=a1.area(5,20);System.out.pri
ntln("Theareais:"+r2);
}
}
Output:
The area is:
200Theareais:
100
Page17
IIB.TechII SemCSEJava LabManual(R20) Preparedby: G.Mahesh CSE
Exercise - 5
(Inheritance)a)ImplementingSingl
eInheritance
Aim:TowriteaJAVAprogram toimplementSingleInheritance
Program:
class A
{
A()
{
System.out.println("InsideA'sConstructor");
}
}
classB extendsA
{
B()
{
System.out.println("InsideB'sConstructor");
}
}
classsingledemo
{
publicstaticvoidmain(Stringargs[])
{
Bb1=newB();
}
}
Output:
Inside A's
ConstructorInsideB'
sConstructor
Page18
IIB.TechII SemCSEJava LabManual(R20) Preparedby: G.Mahesh CSE
b) Multi level
class A
{
A()
{
System.out.println("InsideA'sConstructor");
}
}
classB extendsA
{
B()
{
System.out.println("InsideB'sConstructor");
}
}
classCextendsB
{
C()
{
System.out.println("InsideC'sConstructor");
}
}
classmultidemo
{
publicstaticvoidmain(Stringargs[])
{
Cc1=newC();
}
}
Output:
Inside A's
ConstructorInside
B's
ConstructorInsideC'
sConstructor
Page19
IIB.TechII SemCSEJava LabManual(R20) Preparedby: G.Mahesh CSE
c) AbstractClass
Aim:To writeajavaprogramforabstractclasstofindareasofdifferentshapes
Program:
abstractclassshape
{
abstractdoublearea();
}
classrectangleextendsshape
{
double
l=12.5,b=2.5;dou
blearea()
{
returnl*b;
}
}
classtriangleextendsshape
{
double
b=4.2,h=6.5;dou
blearea()
{
return0.5*b*h;
}
}
classsquareextendsshape
{
double
s=6.5;doubl
earea()
{
return4*s;
}
}
classshapedemo
{
publicstaticvoidmain(String[]args)
{
rectangler1=newrectangl
e();triangle t1=new
triangle();squares1=news
quare();
System.out.println("The area of rectangle is:
"+r1.area());System.out.println("The area of
triangle is:
"+t1.area());System.out.println("Theareaof
squareis:"+s1.area());
}
}
Page20
IIB.TechII SemCSEJava LabManual(R20) Preparedby: G.Mahesh CSE
Output:
The area of rectangle is:
31.25The area of triangle
is: 13.65Thearea
ofsquareis:26.0
Page21
IIB.TechII SemCSEJava LabManual(R20) Preparedby: G.Mahesh CSE
Exercise - 6 (Inheritance -
Continued)a)superkeywordimplem
entation
Aim: WriteaJAVAprogram giveexamplefor“super”keyword
Programs:
(i) Usingsupertocallsuperclassconstructor(Withoutparameters)
class A
{
int
l,b;A(
)
{
l=10
;b=2
0;
}
}
classB extendsA
{
int
h;B(
)
{
super(
);h=30
;
}
intvolume()
{
returnl*b*h;
}
}
classsuperdemo
{
publicstaticvoidmain(Stringargs[])
{
Bb1=newB();
int
r=b1.volume();System.out.prin
tln("Thevol.is:"+r);
}
}
Output:
Thevol.is:6000
(ii) Usingsupertocallsuperclassconstructor(Withparameters)
class A
{
intl,b;
Page22
IIB.TechII SemCSEJava LabManual(R20) Preparedby: G.Mahesh CSE
A(intu,intv)
{
l=u
;b=
v;
}
}
Page23
IIB.TechII SemCSEJava LabManual(R20) Preparedby: G.Mahesh CSE
classB extendsA
{
inth;
B(intu,intv,intw)
{
super(u,v
);h=w;
}
intvolume()
{
returnl*b*h;
}
}
classsuperdemo
{
publicstaticvoidmain(Stringargs[])
{
Bb1=newB(30,20,30);
int
r=b1.volume();System.out.prin
tln("Thevol.is:"+r);
}
}
Output:
Thevol.is:18000
Page24
IIB.TechII SemCSEJava LabManual(R20) Preparedby: G.Mahesh CSE
b)Implementinginterface
Aim:TowriteaJAVAprogram toimplementInterface.
Programs:
(i) Firstformof interfaceimplementation
interfaceA
{
voiddisplay();
}
classBimplementsA
{
publicvoiddisplay()
{
System.out.println("B'smethod");
}
}
classCextendsB
{
publicvoidcallme()
{
System.out.println("C'smethod");
}
}
classinterfacedemo
{
publicstaticvoidmain(Stringargs[])
{
Cc1=newC()
;c1.display()
;
c1.callme();
}
}
Output:
B's
methodC'
smethod
Page26
IIB.Tech IISemCSEJava Lab Manual(R20) Preparedby: G.Mahesh CSE
classBextendsAimplementsE
{
publicvoiddisplay()
{
System.out.println("Thisisindisplaymethod");
}
publicvoidshow()
{
System.out.println("Thisisinshowmethod");
}
}
classCextendsB
{
voidcall()
{
System.out.println("Thisisincallmethod");
}
}
classinterfacedemo
{
publicstaticvoidmain(Stringargs[])
{
C c1=new
C();c1.displa
y();
c1.show();
c1.callme();
c1.call();
}
}
Output:
Thisisindisplaymetho
dThis is in show
methodThis is in
callme methodThis is
in callmethod
(iii) Third form of
interfaceimplementationin
terfaceA
{
voiddisplay();
}
classBimplementsA
{
publicvoiddisplay()
{
System.out.println("ThisisinB'smethod");
}
}
classCimplementsA
{
publicvoiddisplay()
{
System.out.println("ThisisC'smethod");
}
}
IIB.Tech IISemCSEJava Lab Manual(R20) Preparedby: G.Mahesh CSE
classinterfacedemo
{
Page20
IIB.TechII SemCSEJava LabManual (R20)Preparedby:G.Mahesh CSE
publicstaticvoidmain(Stringargs[])
{
B b1=new
B();C
c1=new
C();b1.displa
y();
c1.display();
}
}
Output:
This is in B's
methodThisisC'sm
ethod
(iv) Fourthformofinterfaceimplementation
interfaceA
{
voiddisplay();
}
interfaceB
{
voidcallme();
}
interfaceCextendsA,B
{
voidcall();
}
classDimplementsC
{
publicvoiddisplay()
{
System.out.println("interfaceA");
}
publicvoidcallme()
{
System.out.println("interfaceB");
}
publicvoidcall()
{
System.out.println("interfaceC");
}
}
classinterfacedemo
{
publicstaticvoidmain(Stringargs[])
{
Dd1=newD()
;d1.display()
;
d1.callme();
d1.call();
}
}
Page21
IIB.TechII SemCSEJava LabManual (R20)Preparedby:G.Mahesh CSE
Output:int
erface
Ainterfac
e
Binterfac
eC
Page22
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
Exercise-7 (Exception)
a) Exceptionhandlingmechanism
Aim:TowriteaJAVAprogramthatdescribesexceptionhandlingmechanism
Program:
Usageof ExceptionHandling:
classtrydemo
{
publicstaticvoidmain(Stringargs[])
{
tr
y
{ int
a=10,b=0;i
nt c=a/b;
System.out.println(c);
}
catch(ArithmeticExceptione)
{
System.out.println(e);
}
System.out.println("Afterthecatchstatement");
}
}
Output:
java.lang.ArithmeticException:/
byzeroAfterthe catch statement
Page23
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
b) Illustratingmultiplecatchclasses
Program:
clausesclass multitrydemo
{
publicstaticvoidmain(Stringargs[])
{
tr
y
{ int
a=10,b=5;i
nt c=a/b;
int
d[]={0,1};System.out.println(d[
10]);System.out.println(c);
}
catch(ArithmeticExceptione)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsExceptione)
{
System.out.println(e);
}
System.out.println("Afterthecatchstatement");
}
}
Output:java.lang.ArrayIndexOutOfBoundsEx
ception:10Afterthe catch statement
Page24
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
Exercise–
8(RuntimePolymorphism)a)Ru
ntimePolymorphism
Program:
Aim:TowriteaJAVAprogramthatimplementsRuntimepolymorphism
classA
{
voiddisplay()
{
System.out.println("InsideAclass");
}
}
classB extendsA
{
voiddisplay()
{
System.out.println("InsideBclass");
}
}
classCextendsA
{
voiddisplay()
{
System.out.println("InsideCclass");
}
}
classruntimedemo
{
publicstaticvoidmain(Stringargs[])
{
A a1=new
A();B
b1=new
B();C
c1=new
C();Aref;
ref=c1;ref.
display();r
ef=b1;ref.
display();r
ef=a1;ref.
display();
}
}
Output:
Inside C
classInside
B
classInsideA
class
Page25
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
b) CasestudyonRuntimePolymorphism
Aim: To write a Case study on run time polymorphism, inheritance that implements in
above problemDynamicmethoddispatchisthemechanism
bywhichacalltoanoverriddenmethodisresolved
atruntime,ratherthancompiletime.
Whenanoverriddenmethodiscalledthroughasuperclassreference,Javadetermineswhic
hversion(superclass/subclasses)ofthatmethodistobeexecutedbaseduponthetypeofthe
objectbeingreferredtoatthetimethecalloccurs.Thus,thisdeterminationismadeatruntime.
Atrun-time,itdependsonthetypeoftheobjectbeingreferredto(notthetypeofthereference
variable)thatdetermineswhichversionofanoverriddenmethodwillbeexecuted
Asuperclassreferencevariablecanrefertoasubclassobject.Thisisalsoknowna
supcasting. Javausesthisfacttoresolvecallstooverriddenmethodsatruntime.
UpcastingSuperCl
assobj=newSubClass
SuperClas
s
extends
SubClass
Therefore,if
asuperclasscontainsamethodthatisoverriddenbyasubclass,thenwhendifferenttypes of
objects are referred to through a superclass reference variable, different versions of
themethodareexecuted.Hereisanexamplethat illustratesdynamicmethoddispatch:
Theexampleisgivenby
Consider a scenario, Bank is a class that provides method to get the rate of interest.
But, rate
ofinterestmaydifferaccordingtobanks.Forexample,SBI,ICICIandAXISbanksareproviding8.4
%,7.3%and9.7%rateofinterest
Bank
getRateOfInterest():float
extends
getRateOfInterest():float getRateOfInterest():float
getRateOfInterest():float
Page26
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
}
catch(NullPointerExceptione)
{
System.out.println(e);
}
}
}
Output:
java.lang.NullPointerException:demo
Page27
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
b) creation of illustrating
finallyAim: To write a JAVA program for creation of
Illustrating finallyProgram(i):
classfinallydemo
{
publicstaticvoidmain(Stringargs[])
{
tr
y
{ int
a=10,b=0;i
nt c=a/b;
System.out.println(c);
}
catch(ArithmeticExceptione)
{
System.out.println(e);
}
finall
y
{ System.out.println("Thisisinsidefinallyblock");
}
}
}
Output:
java.lang.ArithmeticException:/
byzeroThisisinsidefinallyblock
Program(ii):
classfinallydemo
{
publicstaticvoidmain(Stringargs[])
{
tr
y
{ int
a=10,b=5;i
nt c=a/b;
System.out.println(c);
}
catch(ArithmeticExceptione)
{
System.out.println(e);
}
finall
y
{ System.out.println("Thisisinsidefinallyblock");
}
}
}
Page28
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
Output:
2
Thisisinsidefinallyblock
Page29
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
(i) Arithmeticexception
classarithmeticdemo
{
publicstaticvoidmain(Stringargs[])
{
tr
y
{ int a = 10, b
= 0;int c
=a/b;
System.out.println(c);
}
catch(ArithmeticExceptione)
{
System.out.println(e);
}
}
}
Output:
java.lang.ArithmeticException:/byzero
(ii)NullPointerException
classnullpointerdemo
{
publicstaticvoidmain(Stringargs[])
{
tr
y
{ String a =
null;System.out.println(a.charAt(0));
}
catch(NullPointerExceptione)
{
System.out.println(e);
}
}
}
Output:
java.lang.NullPointerException
(iii)StringIndexOutOfBoundException
classstringbounddemo
{
publicstaticvoidmain(Stringargs[])
Page30
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
{
try
{
Page31
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
Stringa="Thisislikechipping
"; char c =
a.charAt(24);System.out.pri
ntln(c);
}
catch(StringIndexOutOfBoundsExceptione)
{
System.out.println(e);
}
}
}
Output:
java.lang.StringIndexOutOfBoundsException:Stringindexoutofrange:24
(iv)FileNotFoundException
importjava.io.*;
classfilenotfounddemo
{
publicstaticvoidmain(Stringargs[])
{
tr
y
{ File file = new
File("E://file.txt");FileReaderfr=newFi
leReader(file);
}
catch(FileNotFoundExceptione)
{
System.out.println(e);
}
}
}
Output:
java.io.FileNotFoundException:E:\file.txt(Thesystem cannotfindthefilespecified)
(v)NumberFormatException
classnumberformatdemo
{
publicstaticvoidmain(Stringargs[])
{
tr
y
{ int num = Integer.parseInt
("akki") ;System.out.println(nu
m);
}
catch(NumberFormatExceptione)
{
System.out.println(e);
}
}
}
Page32
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
Output:
java.lang.NumberFormatException:Forinputstring:"akki"
Page33
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
(vi)ArrayIndexOutOfBoundsException
classarraybounddemo
{
publicstaticvoidmain(Stringargs[])
{
tr
y
{ int a[] = new
int[5];a[6] =9;
}
catch(ArrayIndexOutOfBoundsExceptione)
{
System.out.println(e);
}
}
}
Output:
java.lang.ArrayIndexOutOfBoundsException:6
Page34
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
classAextendsException
{
A(Strings1)
{
super(s1);
}
}
classowndemo
{
publicstaticvoidmain(Stringargs[])
{
tr
y
{ thrownewA("demo");
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
Output:
A:demo
Page35
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
Exercise – 10
(Threads)a)ExtendingTh
readclass
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 thirddisplay“Welcome”every3 seconds,
(RepeatthesamebyimplementingRunnable)
Programs:
(i) CreatingmultiplethreadsusingThreadclass
classAextendsThread
{
publicvoidrun()
{
tr
y
{ for(inti=1;i<=10;i++)
{
sleep(1000);System.out.println
("goodmorning");
}
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
classBextendsThread
{
publicvoidrun()
{
tr
y
{ for(intj=1;j<=10;j++)
{
sleep(2000);System.out.prin
tln("hello");
}
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
classCextendsThread
{
publicvoidrun()
Page36
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
{
try
{
Page37
IIB.TechIISemCSE JavaLabManual(R20)Preparedby: G.Mahesh CSEfor(int
for(int k=1;k<=10;k++)
{
sleep(3000);System.out.pri
ntln("welcome");
}
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
classthreaddemo
{
publicstaticvoidmain(Stringargs[])
{
A a1=new
A();B
b1=new
B();C
c1=new
C();a1.start(
);
b1.start();
c1.start();
}
}
Output:
good
morninghell
o
good
morninggoo
d
morningwel
comehello
good
morninggoo
d
morninghell
o
good
morningwel
comegood
morninghell
o
good
morninggoo
d
morningwel
comehello
good
morninghell
owelcomeh
ellowelcom
ehello
IIB.TechIISemCSE JavaLabManual(R20)Preparedby: G.Mahesh CSEfor(int
hellowe
lcomeh
ellowelc
omewel
comew
elcome
welcom
e
Page33
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
(ii) CreatingmultiplethreadsusingRunnableinterface
classAimplementsRunnable
{
publicvoidrun()
{
try
{
for(inti=1;i<=10;i++)
{
Thread.sleep(1000);System.ou
t.println("goodmorning");
}
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
classBimplementsRunnable
{
publicvoidrun()
{
try
{
for(intj=1;j<=10;j++)
{
Thread.sleep(2000);System.out.printl
n("hello");
}
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
classCimplementsRunnable
{
publicvoidrun()
{
tr
y
{ for(intk=1;k<=10;k++)
{
Thread.sleep(3000);System.out.println("
welcome");
}
}
catch(Exceptione)
{
System.out.println(e);
}
Page34
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
}
}
classrunnabledemo
{
publicstaticvoidmain(Stringargs[])
{
A a1=new
A();B
b1=new
B();Cc1=ne
wC();
Thread t1=new
Thread(a1);Thread
t2=new
Thread(b1);Thread
t3=new
Thread(c1);t1.start();
t2.start();
t3.start();
}
}
Output:
good
morninggoo
d
morninghell
o
good
morningwel
comegood
morninghell
o
good
morninggoo
d
morningwel
comehello
good
morninggoo
d
morninghell
o
good
morningwel
comegood
morninghell
owelcomeh
ello
hellowe
lcomeh
ellowelc
omehell
ohellow
Page35
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
elcome
welcom
ewelco
mewelc
ome
Page36
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
(b)ImplementingisAlive()andjoin()
Aim:TowriteaprogramillustratingisAliveandjoin()
Program:
classAextendsThread
{
publicvoidrun()
{
try
{
for(inti=1;i<=10;i++)
{
sleep(1000);System.out.println
("goodmorning");
}
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
classBextendsThread
{
publicvoidrun()
{
try
{
for(intj=1;j<=10;j++)
{
sleep(2000);System.out.printl
n("hello");
}
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
classCextendsThread
{
publicvoidrun()
{
tr
y
{ for(intk=1;k<=10;k++)
{
sleep(3000);System.out.printl
n("welcome");
}
Page37
IIB.TechII SemCSE JavaLabManual (R20)Preparedby: G.Mahesh CSE
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
classisalivedemo
{
publicstaticvoidmain(Stringargs[])
{
A a1=new
A();B
b1=new
B();C
c1=new
C();a1.start(
);
b1.start();
c1.start();System.out.printl
n(a1.isAlive());System.out.p
rintln(b1.isAlive());System.o
ut.println(c1.isAlive());try
{
a1.join();
b1.join();
c1.join();
}
catch(InterruptedExceptione)
{
System.out.println(e);
}
System.out.println(a1.isAliv
e());System.out.println(b1.i
sAlive());System.out.println
(c1.isAlive());
}
}
Output: morningwelcomehello
truetr good morninggood morninghello
uetrue goodmorning
good welcome
morninggoo
d
morninghell
o
good
morningwel
comegood
morninghell
o
good
morninggoo
d
Page38
IIB.TechII SemCSE JavaLabManual (R20)Preparedby: G.Mahesh CSE
hellohel
g lowelco
o mewelc
o omewel
d comew
elcomef
m alsefals
o efalse
r
n
i
n
g
h
e
l
l
o
w
e
l
c
o
m
e
h
e
l
l
o
h
e
l
l
o
w
e
l
c
o
m
e
h
e
l
l
o
w
e
l
c
o
m
e
Page39
IIB.TechII SemCSE JavaLabManual (R20)Preparedby: G.Mahesh CSE
c) ImplementationofDaemonThreads
Aim:TowriteaProgramillustratingDaemonThreads
Program:
classAextendsThread
{
publicvoidrun()
{
if(Thread.currentThread().isDaemon(
))System.out.println("daemonthread
work");else
System.out.println("userthreadwork");
}
}
classdaemondemo
{
publicstaticvoidmain(String[]args)
{
A a1=new
A();A
a2=new
A();Aa3=ne
wA();
a1.setDaemon(tru
e);a1.start();
a2.start();
a3.start();
}
}
Output:
daemon thread
workuser thread
workuserthread
work
Page40
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
Exercise - 11 (Threads
continuity)a)Producer-
Consumerproblem
Aim: Write a JAVA program
ProducerConsumerProblemProgra
m:
class A
{
intn;
boolean
b=false;synchroniz
edintget()
{
if(!
b)tr
y
{ wait();
}
catch(Exceptione)
{
System.out.println(e);
}
System.out.println("Got:"
+n);b=false;
notify();
returnn;
}
synchronizedvoidput(intn)
{
if(b
)tr
y
{ wait();
}
catch(Exceptione)
{
System.out.println(e);
}
this.n=
n;b=tru
e;
System.out.println("Put:"+n);n
otify();
}
}
classproducerimplementsRunnable
{
A a1;
Threadt1;
producer(Aa
Page41
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby:G.Mahesh CSE
1)
{
this.a1=a1;
t1=newThread(thi
s);t1.start();
}
publicvoidrun()
{
Page42
IIB.TechIISemCSE JavaLabManual(R20)Preparedby:G.Mahesh CSE
for(inti=1;i<=10;i++)
{
a1.put(i);
}
}
}
classconsumerimplementsRunnable
{
A a1;
Threadt1;
consumer(Aa
1)
{
this.a1=a1;
t1=newThread(thi
s);t1.start();
}
publicvoidrun()
{
for(intj=1;j<=10;j++)
{
a1.get();
}
} }
classinterdemo
{
publicstaticvoidmain(Stringargs[])
{
Aa1=newA();
producer p1=new
producer(a1);consumerc1=n
ewconsumer(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:1
IIB.TechIISemCSE JavaLabManual(R20)Preparedby:G.Mahesh CSE
0Got:
10
Page40
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
b)Casestudyonthreadsynchronization
Acasestudyonthreadsynchronization aftersolvingproducerconsumerproblem:
Wecanusewait,notifyandnotifyAllmethodstocommunicatebetweenthreadsinJava.
Forexample,ifwehavetwothreadsrunninginyourprograme.g.ProducerandConsumerthen producerthreadcan
communicate totheconsumerthatitcanstartconsumingnowbecausethereare itemstoconsumeinthequeue.
Similarly,aconsumerthreadcantelltheproducerthatitcanalsostart putting items now because
there issomespace inthequeue,whichiscreatedasaresultof consumption.
Athreadcanusewait()methodtopauseanddonothingdependinguponsomecondition.
Forexample,intheproducer-consumerproblem,producer
threadshouldwaitifthequeueis fulland
consumerthreadshouldwait if the
queueisempty.
Ifsomethreadiswaitingforsomeconditiontobecometrue,wecan usenotifyandnotifyAllmethods to inform them
thatconditionisnowchanged andtheycanwake up.
Bothnotify()andnotifyAll()methodsendsanotificationbutnotifysendsthenotificationtoonlyoneof
thewaitingthread,no
guaranteewhichthreadwillreceivenotificationandnotifyAll()sendsthenotificationto
allthreads.
Thingstoremember:
Page41
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
Exercise–12 (Packages)
a) Illustrationofclasspath
Aim:TowriteaJAVAprogram illustrateclasspath
importjava.net.URL;
import
java.net.URLClassLoader;pub
licclassApp
{
publicstaticvoidmain(String[]args)
{
ClassLoader sysClassLoader =
ClassLoader.getSystemClassLoader();URL[]urls=((URLClassLo
ader)sysClassLoader).getURLs();
for(inti=0;i<urls.length;i++)
{
System.out.println(urls[i].getFile());
}
}
}
Output:
E:/java%20work/
Page42
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
Settingenvironmentalvariableinwindowsxp:
Step-1:
SelectMycomputeronthedesktopand rightclickthemouseandthenselectproperties.
Itdisplaysthefollowing“SystemProperties”dialog.
SystemProperties
Advanced
EnvironmentVariables
OK Cancel
InSystemPropertiesclickAdvancedandthenclickEnvironmentVariables.
Itdisplaysthefollowing “EnvironmentVariables”dialog.
EnvironmentVariables
SystemVariables
New
OK Cancel
InEnvironmentVariablesclickNewinSystemvariables.
Itdisplaysthefollowing“NewSystemVariable”dialogbox.
Page43
IIB.TechII SemCSE JavaLab Manual(R20)Preparedby:G.Mahesh CSE
NewSystemVariable
variablename:
variablevalue:
OK Cancel
Step-4:
Nowtypevariablenameasapathandthenvariable
valueasc:\ProgramFiles\java\jdk1.5.0_10\
bin;
NewSystemVariable
variable path
name:variabl c:\ProgramFiles\java\jdk1.5.0_10\bin;
evalue:
OK Cancel
Step-5:
ClickOK
Page44
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
c) Creatingandimportingapackage
Aim: To write a JAVA program that import and use the defined your
package in thepreviousProblem
(i) Creatingapackage:
Steps:
1. Firstdeclarethe name
ofthepackageusingpackagekeywordExa
mple:packagemypack;
2. Typethefollowingprogramunderthispackagestatement.Inpackage:class,data,meth
odsallare public
package
mypack;public
class box
{
publicintl=10,b=
20;publicvoiddisp
lay()
{
System.out.println(l);
System.out.println(b);
}
}
3. Createsubdirectorywithanamesamethatofpackagenameunderthecurrentworki
ngdirectorybyasfollows.d:\>mdmypack
4. Underthissubdirectorystoretheaboveprogramwithafilename“box.java”.
(ii) importingapackage:
Output:
10
20
Page45
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
Exercise-13 (Applet)
a) Paint like Paint Brush in
AppletAim: To write a JAVA program to paint like paint brush
in applet.Program:
import
java.applet.*;import
java.awt.*;importjav
a.awt.event.*;
//<appletcode="paintdemo"width="800"height="500"></
applet>publicclasspaintdemoextendsAppletimplementsMouse
MotionListener{
int w,
h;Image
i;Graphicsg
1;
publicvoidinit()
{
w=getSize().width;h=getSize().heig
ht;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)
{ }publicvoidmouseDragged(MouseEven
tme)
{
intx=me.getX();inty=me.getY(
);g1.fillOval(x-10,y-
10,20,20);repaint();
me.consume();
}
publicvoidupdate(Graphicsg)
{
g.drawImage(i,0,0,this);
}
publicvoidpaint(Graphicsg)
{
update(g);
}
}
Output:
Page46
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
b) DisplayAnalogClockusingApplet
Aim:TowriteaJAVAprogramtodisplayanalogclockusingApplet.
Program:
import
java.util.*;import
java.text.*;import
java.applet.*;imp
ortjava.awt.*;
//<applet code="clockdemo" width="550"
height="250"></appletpublicclassclockdemoextendsA
ppletimplementsRunnable
{
inth=0,m=0,s=0;
String str=""; int wt, ht; Thread thr=null;
boolean b;public void init()
{
wt=getSize().width;ht=getSize().height;
}
publicvoidstart()
{
if(thr==null)
{
thr=new
Thread(this);b=fal
se;
} thr.start();
els
e
{
if(b)
{
b=false;synchroni
zed(this)
{
notify();
}
}
}
}
publicvoidstop()
{
b=true;
}
publicvoidrun()
{
tr
y
{ while(true)
{
Calendar
clndr=Calendar.getInstance();h=cl
ndr.get(Calendar.HOUR_OF_DAY);if
(h>12)h-=12;
m=clndr.get(Calendar.MINUTE);s=clndr.get(Calendar.SECO
ND);SimpleDateFormatfrmatter=newSimpleDateFormat("hh:
mm:ss",
Page47
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
Locale.getDefault
());Dated=clndr.getTime();str=frmatter.format(
d);
if(b)
{
synchronized(this)
{
Page48
IIB.TechIISemCSEJavaLab Manual(R20)Preparedby:G.Mahesh CSE
while(b)
{
wait();
}
}
}
repaint();thr.slee
p(1000);
}
}
catch(Exceptione)
{
System.out.println(e);
}
}
voiddrawHand(doubleangle,intradius,Graphicsgrp)
{
angle-=0.5*Math.PI;
int a=(int)(radius*Math.cos(angle)); int b=(int)
(radius*Math.sin(angle));grp.drawLine(wt/2,ht/2,wt/2+a,ht/2+b);
}
voiddrawWedge(doubleangle,intradius,Graphicsgrp)
{
angle-=0.5*Math.PI;
int a=(int)(radius*Math.cos(angle)); intb=(int)
(radius*Math.sin(angle));
angle+=2*Math.PI/3;int a2=(int)
(5*Math.cos(angle)); intb2=(int)
(5*Math.sin(angle));angle+=2*Math.PI/3;
inta3=(int)(5*Math.cos(angle));intb3=(int)
(5*Math.sin(angle));grp.drawLine(wt/2+a2,
ht/2+b2,wt/2+a,ht/2+b);grp.drawLine(wt/2+a3,
ht/2+b3,wt/2+a,ht/2+b);grp.drawLine(wt/2+a2,ht/2+b2,wt
/2+a3,ht/2+b3);
}
publicvoidpaint(Graphicsgrp)
{
grp.setColor(Color.gray);
drawWedge(2*Math.PI*h/12,wt/5,grp);
drawWedge(2*Math.PI*m/60,wt/3,grp);drawHand(2*Math.PI*s/60,wt/2,grp);
}
}
Output:
Page48
IIB.TechIISemCSEJavaLabManual(R20)Preparedby:G.Mahesh CSE
c) DisplayAnalogClockusingApplet
Aim:TowriteaJAVAprogramtocreatedifferentshapesandfillcolorsusingApplet
Program:
import
java.awt.*;import
java.applet.*;
//
<appletcode="graphicsdemo"width="400"height="400">
</applet>publicclassgraphicsdemoextendsApplet{
publicvoidpaint(Graphicsg)
{
intx[]={10,220,220};
inty[]={400,400,520};
int
n=3;g.drawLine(10,30,20
0,30);
g.setColor(Color.blue);
g.drawRect(10,40,200,30);g.setColor(Color.red);
g.fillRect(10,80,200,30);g.setColor(Color.orange);g.drawRo
undRect(10,120,200,30,20,20);g.setColor(Color.green);g.fil
lRoundRect(10,160,200,30,20,20);
g.setColor(Color.blue);
g.drawOval(10,200,200,30);g.setColor(Color.black)
;g.fillOval(10,240,40,40);g.setColor(Color.yellow);g.
drawArc(10,290,200,30,0,180);g.setColor(Color.yel
low);
g.fillArc(10,330,200,30,0,180);g.setColor(Color.pin
k); g.fillPolygon(x,y,n);
}
}
Output:
Page49
IIB.TechII SemCSEJava LabManual(R20) Preparedby: G.Mahesh CSE
Exercise-14 (EventHandling)
a) Cursormovementusingmouse
Aim: To write a JAVA program that display the x and y position of the cursor
movementusingMouse.
Program:
import
java.awt.*;importjav
a.awt.event.*;import
java.applet.*;
//
<appletcode="mouseevent"width=450height=300><
/applet>publicclassmouseeventextendsApplet
implementsMouseListener,MouseMotionListener
{
String s1="
";intx,y;
publicvoidinit()
{
addMouseListener(this);addMou
seMotionListener(this);
}
publicvoidmouseClicked(MouseEventme)
{
x=10
0;y=1
00;
s1="Mouse
clicked";repaint();
}
publicvoidmouseEntered(MouseEventme)
{
x=10
0;y=2
00;
s1="Mouse
entered";repaint()
;
}
publicvoidmouseExited(MouseEventme)
{
x=10
0;y=3
00;
s1="Mouse
exited";repaint();
}
publicvoidmousePressed(MouseEventme)
{
x=me.getX();
y=me.getY();s1="
Mouse
Page50
IIB.TechII SemCSEJava LabManual(R20) Preparedby: G.Mahesh CSE
Pressed";repaint();
}
publicvoidmouseReleased(MouseEventme)
{
x=me.getX();
y=me.getY();s1="Mo
useRealeased";
Page51
IIB.TechII SemCSEJavaLabManual(R20)Prepared by:G.Mahesh CSE
repaint();
}
publicvoidmouseDragged(MouseEventme)
{
x=me.getX();
y=me.getY();s1="
Mouse
Dragged";repaint();
}
publicvoidmouseMoved(MouseEventme)
{
x=me.getX();
y=me.getY();s1=
"Mouse
Moved";repaint();
}
publicvoidpaint(Graphicsg)
{
g.drawString(s1,x,y);
}
}
Output:
Page51
IIB.Tech II SemCSE Java Lab Manual(R20) Preparedby: G.Mahesh CSE
b) Key-upandKey-downevent
Aim: To write a JAVA program that identifies key-up key-down event user
entering text ina Applet.
Program:
import
java.awt.*;importjav
a.awt.event.*;import
java.applet.*;
//
<appletcode="keyevent"width=450height=300></
applet>public class keyevent extends Applet
implementsKeyListener{
String s1="
";intx,y;
publicvoidinit()
{
addKeyListener(this);requestFo
cus();
}
publicvoidkeyPressed(KeyEventke)
{
x=10
0;y=2
00;
s1= "key
pressed
";repaint();
}
publicvoidkeyReleased(KeyEventke)
{
x=10
0;y=4
00;
s1= "key
Released
";repaint();
}
publicvoidkeyTyped(KeyEventke)
{
s1=s1+ke.getKeyChar();re
paint();
}
publicvoidpaint(Graphicsg)
{
g.drawString(s1,x,y);
}
}
Output:
Page52