0% found this document useful (0 votes)
30 views61 pages

Java Lab Manual JNTUK II-I

The document outlines the Java Programming Lab curriculum for II-B.Tech, CSE I - Semester at DNR College of Engineering & Technology for the academic year 2022-23. It includes course objectives, outcomes, and a series of programming exercises designed to teach various Java concepts such as data types, control flow, object-oriented programming, inheritance, exception handling, threading, and applet development. Each exercise provides specific programming tasks aimed at reinforcing the learning of Java programming skills.

Uploaded by

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

Java Lab Manual JNTUK II-I

The document outlines the Java Programming Lab curriculum for II-B.Tech, CSE I - Semester at DNR College of Engineering & Technology for the academic year 2022-23. It includes course objectives, outcomes, and a series of programming exercises designed to teach various Java concepts such as data types, control flow, object-oriented programming, inheritance, exception handling, threading, and applet development. Each exercise provides specific programming tasks aimed at reinforcing the learning of Java programming skills.

Uploaded by

238a1a4460
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

L T P C

JAVA Programming Lab

Java Programming Lab


[Link], CSE I - Semester
2022-23

Prepared by

Professor

DEPARTMENT OF COMPUTER SCIENCE &


ENGINEERING

DNR COLLEGE OF ENGINEERING &


TECHNOLOGY
BHIMAVARAM-534202
(Approved by AICTE, New Delhi & Affiliated to JNTUK, Kakinada)

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab
II Year – II Semester 0 0 3 1.5
JAVA PROGRAMMING LAB

Course Objectives:
The aim of this lab is to

 Practice programming in the Java


 Gain knowledge of object-oriented paradigm in the Java programming language
 Learn use of Java in a variety of technologies and on different platforms

Course Outcomes:
By the end of the course student will be able to write java program for

 Evaluate default value of all primitive data type, Operations, Expressions, Control-
flow, Strings
 Determine Class, Objects, Methods, Inheritance, Exception, Runtime Polymorphism,
User defined Exception handling mechanism
 Illustrating simple inheritance, multi-level inheritance, Exception handling
mechanism
 Construct Threads, Event Handling, implement packages, developing applets
Exercise - 1 (Basics)
a) Write a JAVA program to display default value of all primitive data type of JAVA
b) Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate the
discriminate D and basing on value of D, describe the nature of root.
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.
Exercise - 2 (Operations, Expressions, Control-flow, Strings)
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 to sort for an element in a given list of elements using merge sort.
d) Write a JAVA program using StringBuffer to delete, remove character.
Exercise - 3 (Class, Objects)
a) Write a JAVA program to implement class mechanism. Create a class, methods and
invoke them inside main method.
b) Write a JAVA program to implement constructor.
Exercise - 4 (Methods)
a) Write a JAVA program to implement constructor overloading.
b) Write a JAVA program implement method overloading.
Exercise - 5 (Inheritance)
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 - 6 (Inheritance - Continued)
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?
Exercise - 7 (Exception)
a) Write a JAVA program that describes exception handling mechanism
b) Write a JAVA program Illustrating Multiple catch clauses.
Exercise – 8 (Runtime Polymorphism)
a) Write a JAVA program that implements Runtime polymorphism
b) Write a Case study on run time polymorphism, inheritance that implements in above
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

problem
Exercise – 9 (User defined Exception)
a) Write a JAVA program for creation of Illustrating throw
b) Write a JAVA program for creation of Illustrating finally
c) Write a JAVA program for creation of Java Built-in Exceptions
d) d)Write a JAVA program for creation of User Defined Exception
Exercise – 10 (Threads)
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.
Exercise - 11 (Threads continuity)
a) Write a JAVA program Producer Consumer Problem
b) Write a case study on thread Synchronization after solving the above producer
consumer problem
Exercise – 12 (Packages)
a) Write a JAVA program illustrate class path
b) Write a case study on including in class path in your os environment of your package.
c) Write a JAVA program that import and use the defined your package in the previous
Problem
Exercise - 13 (Applet)
a) Write a JAVA program to paint like paint brush in applet.
b) Write a JAVA program to display analog clock using Applet.
c) Write a JAVA program to create different shapes and fill colors using Applet.
Exercise - 14 (Event Handling)
a) Write a JAVA program that display the x and y position of the cursor movement
using Mouse.
b) Write a JAVA program that identifies key-up key-down event user entering text in a
Applet.

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

LAB INTRODUCTION

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY KAKINADA


KAKINADA - 533 003, Andhra Pradesh, India
COMPUTER SCIENCE & ENGINEERING
(Applicable for batches admitted from 2021-2022)
II B. TECH I SEMESTER L T P C
0 0 3 1.5
Java Programming Lab

Exercise - 1 (Basics)
1 a) Write a JAVA program to display default value of all primitive data type of JAVA
Aim: A JAVA program to display default values of all primitive data types in JAVA.
Program:

class Exe1a
{
static boolean b;
static byte by;
static short s;
static int i;
static long li;
static char c;
static float f;
static double d;
static String str;
public static void main (String args[])
{
[Link]("Boolean="+b);
[Link]("Byte="+by);
[Link]("Short="+s);
[Link]("Int="+i);
[Link]("Long="+li);
[Link]("Char="+c);
[Link]("Float="+f);
[Link]("Double="+d);
[Link]("String="+str);
}
}

Output:
D:\DNRCET>javac [Link]
D:\DNRCET>java Exe1a
Boolean=false
Byte=0
Short=0
Int=0
Long=0

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

Char=
Float=0.0
Double=0.0
String=null

D:\DNRCET>

1 b) Write a java program that display the roots of a quadratic equation ax2+bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.

Aim: A java program that display the roots of a quadratic equation ax2+bx=0. Calculate the
discriminate D and basing on value of D, describe the nature of root.
Program:-
import [Link].*;
class Exe1b
{
public static void main(String args[]) throws IOException
{
int a,b,c,d;
double r1,r2;
DataInputStream dis=new DataInputStream([Link]);
[Link]("Enter a,b and c values");
a=[Link]([Link]());
b=[Link]([Link]());
c=[Link]([Link]());
d=b*b-4*a*c;
if(d==0)
{
r1=r2=(double)-b/(2*a);
[Link]("Root1 is "+r1+" Root2 is "+r2);
}
else if(d>0)
{
r1=(-b+[Link](d))/(2*a);
r2=(-[Link](d))/(2*a);
[Link]("Root1 is "+r1+" Root2 is "+r2);
}
else
{
[Link]("Roots are imaginary");
}
}
}
Output:
D:\DNRCET>javac [Link]
D:\DNRCET>java Exe1b
Enter a,b and c values
9
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

1
5
Roots are imaginary

D:\DNRCET>

1c) 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.

Aim: 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.
Program:-
import [Link].*;
class racedemo
{
public static void main(String[] args)
{
float s1,s2,s3,s4,s5,average;
Scanner s = new Scanner([Link]);
[Link]("Enter speed of first racer:");
s1 = [Link]();
[Link]("Enter speed of second racer:");
s2 = [Link]();
[Link]("Enter speed of third racer:");
s3 = [Link]();
[Link]("Enter speed of fourth racer:");
s4 = [Link]();
[Link]("Enter speed of fifth racer:");
s5 = [Link](); average=(s1+s2+s3+s4+s5)/
5;
if(s1>average)
[Link]("First racer is qualify racer:");
else if(s2>average)
[Link]("Second racer is qualify racer:");
else if(s3>average)
[Link]("Third racer is qualify
racer:"); else if(s4>average)
[Link]("Fourth racer is qualify racer:");
else if(s5>average)
[Link]("Fifth racer is qualify racer:");
}
}
Output:
Enter speed of first racer:
4.5
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

Enter speed of second racer:


6.7
Enter speed of third racer:
3.8
Enter speed of fourth racer:
5.3
Enter speed of fifth racer:
4.9
Second racer is qualify racer:

Exercise - 2 (Operations, Expressions, Control-flow, Strings)


2. a). Write a JAVA program to search for an element in a given list of elements using binary
Search mechanism.

Aim: a).A JAVA program to search for an element in a given list of elements using binary
Search mechanism.

Program:
import [Link];
class A
{
int binarysearch(int L[],int n,int k)
{
int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(L[mid]==k)
{
return mid;
}
else if(L[mid]>k)
{
high=mid-1;
}
else
{
low=mid+1;
}
}
return -1;
}
}
class Exe2a
{
public static void main(String args[])
{
int L[]=new int[20];
int n,k,pos,i;
A obj=new A();
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

Scanner s=new Scanner([Link]);


[Link]("Enter n value");
n=[Link]();
[Link]("Enter "+n+" elements");
for(i=0;i<n;i++)
{
L[i]=[Link]();
}
[Link]("Enter searching element");
k=[Link]();
pos=[Link](L,n,k);
if(pos==-1)
{
[Link]("Searching element not found in the list");
}
else
{
[Link]("Element found at "+(pos+1)+" location");
}
}
}
Output:

D:\DNRCET>javac [Link]

D:\DNRCET>java Exe2a
Enter n value
5
Enter 5 elements
1 2 3 4 5
Enter searching element
3
Element found at 3 location

D:\DNRCET>java Exe2a
Enter n value
4
Enter 4 elements
10 9 8 7
Enter searching element
5
Searching element not found in the list

D:\DNRCET>

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

2. b). Write a JAVA program to sort for an element in a given list of elements using bubble sort

Aim: b). A JAVA program to sort for an element in a given list of elements using bubble sort
Program:
import [Link];
class Exe2b

{
public static void main(String []args)
{
int n,t,i,j;
Scanner s = new Scanner([Link]);
[Link]("How many numbers are to be sorted:");

n = [Link]();
int a[] = new int[n];
[Link]("Enter " + n + " integers");
for (i = 0; i < n; i++)
a[i] = [Link]();
for (i = 0; i < ( n - 1 ); i++) {

for (j = 0; j < n - (i + 1); j++) {


if (a[j] > a[j+1]){
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}

[Link]("After after sorting: ");


for (i = 0; i < n; i++){
[Link]("\t"+a[i]);

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

}
}
}

Output:-
D:\DNRCET>javac [Link]
D:\DNRCET>java Exe2b
How many numbers are to be sorted:
6
Enter 6 integers

1 9 2 8 5 3
After after sorting:
1 2 3 5 8 9
D:\DNRCET>
2.c) Write a JAVA program to sort for an element in a given list of elements using merge sort.
Aim:- A JAVA program to sort for an element in a given list of elements using merge sort.
Program:-
import [Link].*;
class Exe2c
{
private int[] a;
private int[] tempar;
private int length;
public static void main(String args[])
{
int[] a = {6,1,3,4,2,5};
[Link]("array before sorting is ");
for(int i=0;i < [Link];i++)
[Link]("\t"+a[i]);
Exe2c obj = new Exe2c();
[Link](a);
[Link]("\n array after sorting is ");
for(int i=0;i < [Link];i++)
{
[Link]("\t"+a[i]);
}
}
void sort(int a[])
{
this.a = a;
[Link] = [Link];
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

[Link] = new int[length];


mergesort(0, length - 1);
}
void mergesort(int low, int high)
{
if (low < high)
{
int mid = (low + high) / 2;
mergesort(low, mid);
mergesort(mid + 1, high);
merge(low, mid, high);
}
}
void merge(int low, int mid, int high)
{
int i;
for (i = low; i <= high; i++)
{
tempar[i] = a[i];
}
i = low;
int j = mid + 1;
int k = low;
while (i <= mid && j <= high)
{
if (tempar[i] <= tempar[j])
{
a[k] = tempar[i];
i++;
}
else
{
a[k] = tempar[j];
j++;
}
k++;
}
while (i <= mid)
{
a[k] = tempar[i];
k++;
i++;
}

}
}
Output:-
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe2c
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

array before sorting is


6 1 3 4 2 5
array after sorting is
1 2 3 4 5 6
D:\DNRCET>

2.d) Write a JAVA program using StringBuffer to delete, remove character.

Aim:- A JAVA program using StringBuffer to delete, remove character.

Program:-

class Exe2d
{
public static void main(String arg[])
{
StringBuffer s = new StringBuffer("Kumar");
[Link](s);
[Link](1, 3);
[Link](s);
[Link](0);
[Link](s);
}
}
Output:-
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe2d
Kumar
Kar
ar

D:\DNRCET>

Exercise - 3 (Class, Objects)


3.a). Write a JAVA program to implement class mechanism. – Create a class, methods and invoke
them inside main method.

Aim:-A JAVA program to implement class mechanism. – Create a class, methods and invoke
them inside main method.
Program:
public class Exe3a

{
private static void call()
{

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

[Link]("World");
}
public static void main(String[] args)

{
[Link]("Hello");
call();
}

Output:
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe3a

HelloWorld

D:\DNRCET>

3.b). Write a JAVA program to implement constructor.


Aim:-A JAVA program to implement constructor.
Program:-
class Exe3b
{
Exe3b()
{
[Link]("Constructor called");
}
public static void main(String[] args)
{
Exe3b obj= new Exe3b();
}

}
Output:-
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe3b
Constructor called

D:\DNRCET>

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

Exercise - 4 (Methods)

4. a). Write a JAVA program to implement constructor overloading.

Aim: A JAVA program to implement constructor overloading.

Program:
class Employee
{
int age;
String name;
Employee()
{
age =20;
name="Harish";
}
Employee(int age,String name)
{
[Link] =age;
[Link]=name;
}
public void disp()
{
[Link]("Name:"+name+"\t"+ "Age:"+age);
}

}
class Exe4a
{
public static void main(String args[])
{
Employee e1 = new Employee();
Employee e2 = new Employee(15,"Sirish");
[Link]();
[Link]();
}
}
Output:-
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe4a
Name:Harish Age:20
Name:Sirish Age:15

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

D:\DNRCET>
4.b). Write a JAVA program implement method overloading.

Aim:-A JAVA program implement method overloading.

Program:
class Exe4b
{

int n1;
int n2;
Exe4b()
{
n1 = 10;
n2 = 20;

}
void square()
{
[Link]("The Square is " + n1 * n2);
}
void square(int p1)

{
n1 = p1;
[Link]("The Square is " + n1 * n2);
}
void square(int p1, int p2)
{
n1 = p1;

n2 = p2;
[Link]("The Square is " + n1 * n2);
}
public static void main(String args[])
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

{
Exe4b obj = new Exe4b();
[Link](); //call non parameterise method

[Link](4); //call method which has 1 argument


[Link](7,8); //call method which has 2 argument
}
}Output:

D:\DNRCET>java Exe4b
The Square is 200
The Square is 80
The Square is 56

D:\DNRCET>

Exercise - 5 (Inheritance)
5. a). Write a JAVA program to implement Single Inheritance

Aim: A JAVA program to implement Single Inheritance


Program:
class A
{
int a=10,b=5;
void add()
{

[Link]("Addition is= "+(a+b));


}
}
class B extends A
{
void sub()

{
[Link]("Subtraction is= " +(a-b));
}
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

}
class Exe5a
{

public static void main(String args[])


{
B obj=new B();
[Link]();
[Link]();
}

Output:
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe5a
Addition is= 15
Subtraction is= 5

D:\DNRCET>
5 b) Write a JAVA program to implement multi level Inheritance

Aim:-b). a JAVA program to implement multi level Inheritance


Program:
class A
{
int a=10,b=5;
void add()
{
[Link]("Addition is= "+(a+b));
}
}
class B extends A
{
void sub()
{
[Link]("Subtraction is= " +(a-b));
}
}
class C extends B
{
void mul()
{

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

[Link]("Multiplication is= "+(a*b));


}
}
class Exe5b
{
public static void main(String args[])
{
C obj = new C();
[Link]();
[Link]();
[Link]();
}
}
Output:
D:\DNRCET>java Exe5b
Addition is= 15
Subtraction is= 5
Multiplication is= 50
D:\DNRCET>

5. c). Write a java program for abstract class to find areas of different shapes

Aim:- a java program for abstract class to find areas of different shapes
Program:-
//Program for abstract class to find areas of different shapes
import [Link];
abstract class Calcarea
{
abstract void findTriangle(double b, double h);
abstract void findRectangle(double l, double b);
abstract void findSquare(double s);
abstract void findCircle(double r);
}

class findArea extends Calcarea


{
void findTriangle(double b, double h){
double area = (b*h)/2;
[Link]("Area of Triangle: "+area);
}

void findRectangle(double l, double b){


double area = l*b;
[Link]("Area of Rectangle: "+area);
}
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

void findSquare(double s){


double area = s*s;
[Link]("Area of Square: "+area);
}

void findCircle(double r){


double area = 3.14*r*r;
[Link]("Area of Circle: "+area);
}
}

class Exe5c
{
public static void main(String args[])
{
double l, b, h, r, s;
findArea area = new findArea();
Scanner obj = new Scanner([Link]);

[Link]("\nEnter Base & Vertical Height of Triangle: ");


b = [Link]();
h = [Link]();
[Link](b, h);

[Link]("\nEnter Length & Breadth of Rectangle: ");


l = [Link]();
b = [Link]();
[Link](l, b);

[Link]("\nEnter Side of a Square: ");


s = [Link]();
[Link](s);

[Link]("\nEnter Radius of Circle: ");


r = [Link]();
[Link](r);
}
}
Output:-

D:\DNRCET>javac [Link]

D:\DNRCET>java Exe5c

Enter Base & Vertical Height of Triangle: 5


3
Area of Triangle: 7.5

Enter Length & Breadth of Rectangle: 4


6
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

Area of Rectangle: 24.0

Enter Side of a Square: 1


Area of Square: 1.0

Enter Radius of Circle: 8


Area of Circle: 200.96

D:\DNRCET>

Exercise - 6 (Inheritance - Continued)


6 a). Write a JAVA program give example for “super” keyword.

Aim:- a). A JAVA program gives example for “super” keyword.

Program:
class A
{
int a=10;
A()
{
[Link]("This is default constructor of A");
}
A(int a)
{
[Link]("This is parameterised constructor of A "+a);
}
void display()
{
[Link]("This is display method in A");
}
}

class B extends A
{
int a=20;
B()
{
[Link]("This is default constructor of B");
}
B(int a)
{

super(6);
//this();
[Link]("This is parameterised constructor of B i.e addition
"+(a+this.a+super.a));

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

[Link]();
[Link]();
}
void display()
{
[Link]("This is display method in B");
}
}
class Exe6a
{
public static void main(String args[])
{
B obj=new B();
B obj2=new B(9);
}
}
Output:
D:\DNRCET>javac [Link]
D:\DNRCET>java Exe6a
This is default constructor of A
This is default constructor of B
This is parameterised constructor of A 6
This is parameterised constructor of B i.e addition 39
This is display method in A

This is display method in B

D:\DNRCET>

6 b). Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?

Aim:- A JAVA program to implement Interface. What kind of Inheritance can be achieved?
Program:
interface add{
int addition(int i,int j);
}
interface sub{
int substraction(int i,int j);
}

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

class Exe6b implements add,sub


{
public int addition(int i,int j){
return (i+j);
}
public int substraction(int i,int j){
return (i-j);
}
public static void main(String args[]){
Exe6b obj=new Exe6b();
int a=10,b=5;
[Link]("Addition is="+[Link](a,b));
[Link]("Substraction is="+[Link](a,b));
}
}
Output:
D:\DNRCET>javac [Link]
D:\DNRCET>java Exe6b
Addition is=15
Substraction is=5

D:\DNRCET>

Note:- Using interface mechanism we achieved multiple inheritance.


Exercise - 7 (Exception)
7 a).Write a JAVA program that describes exception handling mechanism

Aim:-A JAVA program that describes exception handling mechanism


Program:
class Exe7a
{
public static void main (String args[])throws Exception
{
int n=20,result;
try
{
result=n/0;
[Link]("The result is"+result);
}
catch(ArithmeticException ex)
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

{
[Link]("Arithmetic exception occoured: ");
}
finally
{
[Link]("This is finally block");
}
result=n*n;
[Link]("Square of given number is "+result);
}
}
Output:
D:\DNRCET>javac [Link]
D:\DNRCET>java Exe7a
Arithmetic exception occurred:

This is finally block


Square of given number is 400
D:\DNRCET>
7 b).Write a JAVA program Illustrating Multiple catch clauses
Aim- b).A JAVA program Illustrating Multiple catch clauses
Program:
class Exe7b
{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[5]=1/0;
//a[2]=a[20];
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception found");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array Index Out of Bounds");
}
catch(Exception e)
{
[Link]("Exception found");
}
[Link]("End of the Program");

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

}
}
Output:-
D:\DNRCET>javac [Link]
D:\DNRCET>java Exe7b
Arithmetic Exception found
End of the Program

D:\DNRCET>

Exercise – 8 (Runtime Polymorphism)


8. a). Write a JAVA program that implements Runtime polymorphism

Aim:- A JAVA program that implements Runtime polymorphism

Program:
class Human{
//Overridden method
public void eat()
{
[Link]("Human is eating");
}
}
class Exe8a extends Human
{
//Overriding method
public void eat()
{
[Link]("Boy is eating");
}
public static void main( String args[])
{
Exe8a obj = new Exe8a();
//This will call the child class version of eat()
[Link]();
}
}
Output:-
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe8a
Boy is eating

D:\DNRCET>

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

8. b). Write a Case study on run time polymorphism, inheritance that implements in above
problem

Aim:- A Case study on run time polymorphism, inheritance that implements in above problem

Exercise – 9 (User defined Exception)


9 a). Write a JAVA program for creation of Illustrating throw

Aim:- a JAVA program for creation of Illustrating throw

Program:

class VoteException extends Exception


{
VoteException(String s)
{
super(s);
}

class Exe9a
{
static void validate(int age) throws VoteException
{
if(age < 18)
throw new VoteException("Candidate is not eligible to vote");
else
[Link]("Welcome to Vote");
}
public static void main(String args[])
{
try
{
validate(13);
}
catch(Exception e)
{
[Link]("Exception occured: "+e);
}
[Link]("End of the program");
}
}
Output:-
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe9a
Exception occured: VoteException: Candidate is not eligible to vote
End of the program

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

D:\DNRCET>javac [Link] //if age=19 then output

D:\DNRCET>java Exe9a
Welcome to Vote
End of the program

D:\DNRCET>

9 b). Write a JAVA program for creation of Illustrating finally

Aim:- A JAVA program for creation of Illustrating finally

Program:-
class Exe9b
{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/0;
[Link](num);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBoundsException");
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception");
}
finally
{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}

Output:-
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe9b
First statement of try block
Arithmetic Exception
finally block
Out of try-catch-finally block

D:\DNRCET>

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

9 c). Write a JAVA program for creation of Java Built-in Exceptions

Aim:- A JAVA program for creation of Java Built-in Exceptions

Program:-
// Java program to demonstrate String Index Out Of Bounds Exception
class Exe9c
{
public static void main(String args[])
{
try
{
String a = "This is built-in exception"; // length is 26
char c = [Link](26); // accessing 27th element
[Link](c);
}
catch (StringIndexOutOfBoundsException e)
{
[Link]("String Index Out Of Bounds Exception");
}
}
}
Output:-

D:\DNRCET>javac [Link]

D:\DNRCET>java Exe9c
String Index Out Of Bounds Exception

D:\DNRCET>

9 d). Write a JAVA program for creation of User Defined Exception

Aim:- A JAVA program for creation of User Defined Exception

Program:
//Program for creation of user defined exception

import [Link];
class OddNumberException extends Exception
{
OddNumberException(String s)
{
super(s);
}
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

}
class Exe9d
{
public static void main(String[] args)
{
int num;
Scanner S = new Scanner([Link]);
[Link]("Enter any number : ");
num = [Link]();
//num = [Link]([Link]());
try
{
if(num%2 != 0)
throw new OddNumberException("Odd number exception");
else
[Link](" " + num + " is an even number");
}
catch(OddNumberException Ex)
{
[Link]("Error : " + [Link]());
}

[Link]("End of program");
}
}
Output:

D:\DNRCET>javac [Link]

D:\DNRCET>java Exe9d
Enter any number : 456
456 is an even number
End of program

D:\DNRCET>java Exe9d
Enter any number : 237
Error : Odd number exception
End of program

D:\DNRCET>

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

Exercise – 10 (Threads)
10 a.i). 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

Aim:- 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

Program:-
//Program for Multithreading by extending Thread Class
class ChildThread extends Thread
{
Thread t;
ChildThread(String name)
{
t = new Thread(this, name);
[Link]();
}
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
if([Link]().equals("First Thread"))
{
[Link](1000);
[Link]([Link]()+": Good Morning");
}
else if([Link]().equals("Second Thread"))
{
[Link](2000);
[Link]([Link]()+": Hello");
}
else
{
[Link](3000);
[Link]([Link]()+": Welcome");
}
}
catch(InterruptedException e)
{
[Link]([Link]()+" is interrupted");
}
}
}
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

}
class Exe10ai
{
public static void main(String args[])
{

ChildThread one = new ChildThread("First Thread");


ChildThread two = new ChildThread("Second Thread");
ChildThread three = new ChildThread("Third Thread");
}
}
Output:-

D:\DNRCET>javac [Link]

D:\DNRCET>java Exe10ai
First Thread: Good Morning
Second Thread: Hello
First Thread: Good Morning
Third Thread: Welcome
First Thread: Good Morning
Second Thread: Hello
First Thread: Good Morning
First Thread: Good Morning
Third Thread: Welcome
Second Thread: Hello
Second Thread: Hello
Third Thread: Welcome
Second Thread: Hello
Third Thread: Welcome

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

10 [Link]). Write a JAVA program that creates threads by implementing Runnable [Link]
thread display “Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds
and the third display “Welcome” every 3 seconds

Aim:-A JAVA program that creates threads by implementing Runnable [Link] thread
display “Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the
third display “Welcome” every 3 seconds

Program:-
//Program for Multithreading by implementing Runnable interface

class ChildThread implements Runnable


{
Thread t;
ChildThread(String name)
{
t = new Thread(this, name);
[Link]();
}
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
if([Link]().equals("First Thread"))
{
[Link](1000);
[Link]([Link]()+": Good Morning");
}
else if([Link]().equals("Second Thread"))
{
[Link](2000);
[Link]([Link]()+": Hello");
}
else
{
[Link](3000);
[Link]([Link]()+": Welcome");
}
}
catch(InterruptedException e)
{
[Link]([Link]()+" is interrupted");
}
}
}

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

}
class Exe10aii
{
public static void main(String args[])
{
ChildThread one = new ChildThread("First Thread");
ChildThread two = new ChildThread("Second Thread");
ChildThread three = new ChildThread("Third Thread");
}
}

Output:-
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe10aii
First Thread: Good Morning
Second Thread: Hello
First Thread: Good Morning
Third Thread: Welcome
First Thread: Good Morning
Second Thread: Hello
First Thread: Good Morning
First Thread: Good Morning
Third Thread: Welcome
Second Thread: Hello
Second Thread: Hello
Third Thread: Welcome
Second Thread: Hello
Third Thread: Welcome
Third Thread: Welcome

D:\DNRCET>

10 b). Write a java program illustrating isAlive and join ()

Aim:-A JAVA program illustrating isAlive and join ().

Program:-
//import [Link].*;
public class Exe10b implements Runnable {
public void run() {
Thread t = [Link]();
// tests if this thread is alive
[Link]("status = " + [Link]());
}
public static void main(String args[]) throws Exception {
Thread t = new Thread(new Exe10b());

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

// this will call run() function


[Link]();
// waits for this thread to die
[Link]();
// tests if this thread is alive
[Link]("status = " + [Link]());
}
}

Output:-
D:\DNRCET>javac [Link]

D:\DNRCET>java Exe10b
status = true
status = false

D:\DNRCET>

10 c). Write a Program illustrating Daemon Threads.

Aim:-A java Program illustrating Daemon Threads

Program:-
// Program for illustrating Daemon Threads
class Daemonthread extends Thread
{
public void run()
{
if([Link]().isDaemon())
[Link]("Daemon Thread");
else
[Link]("User Thread");
}
public static void main(String args[])
{
Daemonthread t1= new Daemonthread();
Daemonthread t2= new Daemonthread();
Daemonthread t3= new Daemonthread();
[Link](true);
[Link]();
[Link]();
[Link]();
}
}

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

Output:-

D:\DNRCET>javac [Link]

D:\DNRCET>java Daemonthread
Daemon Thread
User Thread
User Thread

D:\DNRCET>

Exercise - 11 (Threads continuity)


11 a).Write a JAVA program Producer Consumer Problem

Aim:-A JAVA program Producer Consumer Problem

Program:-
// Java program to implement solution of producer consumer problem

import [Link];
public class Exe11a
{
public static void main(String[] args) throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable()
{
public void run()
{
try
{
[Link]();
}
catch(InterruptedException e)
{
[Link]();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable()
{
public void run()
{
try
{
[Link]();
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

}
catch(InterruptedException e)
{
[Link]();
}
}
});
// Start both threads
[Link]();
[Link]();
// t1 finishes before t2
[Link]();
[Link]();
}
// This class has a list, producer (adds items to list and consumber (removes items).
public static class PC
{
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 1;
// Function called by producer thread
public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{
// producer thread waits while list is full
while ([Link]()==capacity)
wait();
[Link]("Producer produced-" + value);
// to insert the jobs in the list
[Link](value++);
// notifies the consumer thread that now it can start consuming
notify();
// makes the working of program easier to understand
[Link](1000);
}
}
}
// Function called by consumer thread
public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
// consumer thread waits while list is empty
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

while ([Link]()==0)
wait();
//to retrive the first job in the list
int val = [Link]();
[Link]("Consumer consumed-" + val);
// Wake up producer thread
notify();
[Link](1000);
}
}
}
}
}

Output:-

D:\DNRCET>javac [Link]

D:\DNRCET>java Exe11a
Producer produced-0
Consumer consumed-0
Producer produced-1
Consumer consumed-1
Producer produced-2
Consumer consumed-2
Producer produced-3
Consumer consumed-3
Producer produced-4
Consumer consumed-4
Producer produced-5
Consumer consumed-5
Producer produced-6
Consumer consumed-6
Producer produced-7
Consumer consumed-7
Producer produced-8
Consumer consumed-8
Producer produced-9
Consumer consumed-9
Producer produced-10
Consumer consumed-10

D:\DNRCET>

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

11 b).Write a case study on thread Synchronization after solving the above producer consumer
problem

Aim:- A case study on thread Synchronization after solving the above producer consumer
problem

In computing, the producer–consumer problem (also known as the bounded-buffer


problem) is a classic example of a multi-process synchronization problem. The problem describes
two processes, the producer and the consumer, which share a common, fixed-size buffer used as a
queue.
 The producer’s job is to generate data, put it into the buffer, and start again.
 At the same time, the consumer is consuming the data (i.e. removing it from the buffer),
one piece at a time.
Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the
consumer won’t try to remove data from an empty buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the
consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer
again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next
time the producer puts data into the buffer, it wakes up the sleeping consumer.
An inadequate solution could result in a deadlock where both processes are waiting to be
awakened.
Implementation of Producer Consumer Class
 A LinkedList list – to store list of jobs in queue.
 A Variable Capacity – to check for if the list is full or not
 A mechanism to control the insertion and extraction from this list so that we do not insert
into list if it is full or remove from it if it is empty.
Important Points
 In PC class (A class that has both produce and consume methods), a linked list of jobs and
a capacity of the list is added to check that producer does not produce if the list is full.
 In Producer class, the value is initialized as 0.
o Also, we have an infinite outer loop to insert values in the list. Inside this loop, we
have a synchronized block so that only a producer or a consumer thread runs at a
time.
o An inner loop is there before adding the jobs to list that checks if the job list is full,
the producer thread gives up the intrinsic lock on PC and goes on the waiting state.
o If the list is empty, the control passes to below the loop and it adds a value in the
list.
 In the Consumer class, we again have an infinite loop to extract a value from the list.
o Inside, we also have an inner loop which checks if the list is empty.
o If it is empty then we make the consumer thread give up the lock on PC and passes
the control to producer thread for producing more jobs.
o If the list is not empty, we go round the loop and removes an item from the list.
 In both the methods, we use notify at the end of all statements. The reason is simple, once
you have something in list, you can have the consumer thread consume it, or if you have
consumed something, you can have the producer produce something.

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

 sleep() at the end of both methods just make the output of program run in step wise
manner and not display everything all at once so that you can see what actually is
happening in the program.

Exercise – 12 (Packages)
12 a). Write a JAVA program illustrate class path

Aim:- A JAVA program illustrate class path

Program:-
package mypackage;
class Shape
{
int d1,d2;
Shape(int x,int y)
{
d1=x;
d2=y;
}
}
public class Rectangle extends Shape
{
public Rectangle(int x,int y)
{
super(x,y);
}
public void area()
{
[Link]("Area:"+ (d1*d2));
}
}
import mypackage.*;
class ShapeDemo1
{
public static void main(String args[])
{
Rectangle r = new Rectangle(20,30);
[Link]();
}
}
Output:-
C:\Users\admin>d:

D:\>cd DNRCET

D:\DNRCET>cd mypackage

D:\DNRCET\mypackage>javac [Link]

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

D:\DNRCET\mypackage>cd..

D:\DNRCET>javac [Link]

D:\DNRCET>java ShapeDemo1
Area:600

D:\DNRCET>

b). Write a case study on including in class path in your os environment of your package.

Aim:-
Program:-
COPEING THE PATH OF JAVA:-
First of all go to MYCOMPUTER and go to the drive where the java is installed. In that go to

PROGRAM FILES and then double click on java folder.


In that we have observed there is a folder with name java jdk, double click on the java jdk folder
and then go into the bin folder.
At this time we have to copy the path of the bin folder.

SETTING THE JAVA PATH:-


In order to set the path of the java in our system, first of all we need to open CONTROL PANEL
in our system and go to SYSTEM SETTINGS .

In system settings we need to go into the ADVANCED SYSTEM SETTINGS settings.


In advanced system settings we just click on ENVIRONMENT VARIABLES option.
In USER VARIABLES click on NEW button and type the " path" at VARIABLE NAME.
We need to paste the previously copied path of the bin folder at the place of VARIABLE
VALUE. Finally click on OK and then OK, then close the MYCOMPUTR window. Now the java
path is set. We are ready to use java facilities in our computer.

c). Write a JAVA program that import and use the defined your package in the previous
Problem

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

Program:-
import [Link];
class ShapeDemo2
{
public static void main(String args[])
{
Rectangle r = new Rectangle(20,30);
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

[Link]();
}
}

Output:-

D:\DNRCET>javac [Link]

D:\DNRCET>java ShapeDemo2
Area:600

D:\DNRCET>

class ShapeDemo3
{
public static void main(String args[])
{
[Link] r = new [Link](20,30);
[Link]();
}
}
Output:-

D:\DNRCET>javac [Link]

D:\DNRCET>java ShapeDemo3
Area:600

Exercise - 13 (Applet)
13 a).Write a JAVA program to paint like paint brush in applet.

Aim:- A JAVA program to paint like paint brush in applet.

Program:-
/* JAVA program to paint like paint brush in applet*/
import [Link].*;
import [Link].*;
import [Link].*;
public class Exe13a extends Applet implements MouseMotionListener
{
public void init()
{
addMouseMotionListener(this);
setBackground([Link]);
}
public void mouseDragged(MouseEvent me){
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

Graphics g=getGraphics();
[Link]([Link]);
[Link]([Link](),[Link](),5,5);
}
public void mouseMoved(MouseEvent me){}

}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
Output:-

13 b) Write a JAVA program to display analog clock using Applet.

Aim:-A JAVA program to display analog clock using Applet.

Program:-

//JAVA program to display analog clock using Applet


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class Exe13b extends Applet implements Runnable {

int width, height;

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

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

public void init() {


width = getSize().width;
height = getSize().height;
setBackground( [Link] );
}

public void start() {


if ( t == null ) {
t = new Thread( this );
[Link]( Thread.MIN_PRIORITY );
threadSuspended = false;
[Link]();
}
else {
if ( threadSuspended ) {
threadSuspended = false;
synchronized( this ) {
notify();
}
}
}
}

public void stop() {


threadSuspended = true;
}

public void run() {


try {
while (true) {

Calendar cal = [Link]();


hours = [Link]( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = [Link]( [Link] );
seconds = [Link]( [Link] );

SimpleDateFormat formatter
= new SimpleDateFormat( "hh:mm:ss", [Link]() );
Date date = [Link]();
timeString = [Link]( date );

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


if ( threadSuspended ) {
synchronized( this ) {
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

while ( threadSuspended ) {
wait();
}
}
}
repaint();
[Link]( 1000 ); // interval specified in milliseconds
}
}
catch (Exception e) { }
}

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


angle -= 0.5 * [Link];
int x = (int)( radius*[Link](angle) );
int y = (int)( radius*[Link](angle) );
[Link]( width/2, height/2, width/2 + x, height/2 + y );
}

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


angle -= 0.5 * [Link];
int x = (int)( radius*[Link](angle) );
int y = (int)( radius*[Link](angle) );
angle += 2*[Link]/3;
int x2 = (int)( 5*[Link](angle) );
int y2 = (int)( 5*[Link](angle) );
angle += 2*[Link]/3;
int x3 = (int)( 5*[Link](angle) );
int y3 = (int)( 5*[Link](angle) );
[Link]( width/2+x2, height/2+y2, width/2 + x, height/2 + y );
[Link]( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
[Link]( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
}

public void paint( Graphics g ) {


[Link]( [Link] );
drawWedge( 2*[Link] * hours / 12, width/5, g );
drawWedge( 2*[Link] * minutes / 60, width/3, g );
drawHand( 2*[Link] * seconds / 60, width/2, g );
[Link]( [Link] );
[Link]( timeString, 10, height-10 );
}
}
/*
<applet code="Exe13b" width="300" height="300">
</applet>
*/

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

Output:-

c). Write a JAVA program to create different shapes and fill colors using Applet.

Aim:- A JAVA program to create different shapes and fill colors using Applet

Program:-
import [Link].*;
import [Link].*;
public class Exe13c extends Applet
{

public void paint(Graphics g)


{
[Link](10,10,50,50);
[Link](10,60,40,30);
[Link]([Link]);
[Link](60,10,30,80);

[Link]([Link]);
[Link](20,110,60,30,5,5);

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

[Link]([Link]);
[Link]("Different shapes ",65,180);
[Link](230,10,200,150);

[Link]([Link]);
[Link](245,25,100,100);
}
}
/*<applet code="Exe13c"width=500 height=400></applet>*/

Output:-

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

Exercise - 14 (Event Handling)


a).Write a JAVA program that display the x and y position of the cursor movement using
Mouse.

Aim:- A JAVA program that display the x and y position of the cursor movement using
Mouse.

Program:-
//java program that display the x and y position of the cursor movement using mouse
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="Exe14a" width=300 height=300>
</applet>*/
public class Exe14a extends Applet implements MouseListener,MouseMotionListener
{
String msg=" ";
int mousex=0,mousey=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mousex=0;
mousey=10;
msg="MouseClicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mousex=0;
mousey=10;
msg="MouseEntered";
repaint();
}
public void mouseExited(MouseEvent me)
{
mousex=0;
mousey=10;
msg="MouseExited";
repaint();
}
public void mousePressed(MouseEvent me)
{
mousex=0;
mousey=10;

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

msg="down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
mousex=[Link]();
mousey=[Link]();
msg="up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mousex=[Link]();
mousey=[Link]();
msg="*";
showStatus("Dragging mouse at:"+mousex+","+mousey);
repaint();
}
public void mouseMoved(MouseEvent me)
{
mousex=[Link]();
mousey=[Link]();
showStatus("Moving mouse at:"+mousex+","+mousey);
}
public void paint(Graphics g)
{
[Link](msg,mousex,mousey);
}
}

Output:-

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

14 b).Write a JAVA program that identifies key-up key-down event user entering text in a
Applet.

Aim:- A JAVA program that identifies key-up key-down event user entering text in a
Applet.

Program:-
//java program that identifies key_up key_down event user entering text in a Applet
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="Exe14b"width=300 height=400>
</applet>
*/
public class Exe14b extends Applet implements KeyListener
{
int X=20,Y=30;
String msg="KeyEvents";
public void init()
{
addKeyListener(this);
requestFocus();
setBackground([Link]);
setForeground([Link]);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyDown");
int key=[Link]();
switch(key)
{
case KeyEvent.VK_UP:showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN:showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT:showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT:showStatus("Move to right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("key up");
}
public void keyTyped(KeyEvent k)
{

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

msg+=[Link]();
repaint();
}
public void paint(Graphics g)
{
[Link](msg,X,Y);
}
}

Output:-

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

Exercise - 15 (Swings)
a).Write a JAVA program to build a Calculator in Swings

Aim:- A JAVA program to build a Calculator in Swings

Program:-
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class Calculator implements ActionListener {


private static JTextField inputBox;

Calculator(){}
public static void main(String[] args) {
createWindow();
}

private static void createWindow() {


JFrame frame = new JFrame("Calculator");
[Link](JFrame.EXIT_ON_CLOSE);

createUI(frame);
[Link](200, 200);
[Link](null);
[Link](true);
}

private static void createUI(JFrame frame) {


JPanel panel = new JPanel();
Calculator calculator = new Calculator();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
[Link](layout);

inputBox = new JTextField(10);


[Link](false);

JButton button0 = new JButton("0");JButton button1 = new JButton("1");


JButton button2 = new JButton("2");JButton button3 = new JButton("3");
JButton button4 = new JButton("4");JButton button5 = new JButton("5");

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

JButton button6 = new JButton("6");JButton button7 = new JButton("7");


JButton button8 = new JButton("8");JButton button9 = new JButton("9");

JButton buttonPlus = new JButton("+");JButton buttonMinus = new JButton("-");


JButton buttonDivide = new JButton("/");JButton buttonMultiply = new JButton("x");
JButton buttonClear = new JButton("C");JButton buttonDot = new JButton(".");
JButton buttonEquals = new JButton("=");

[Link](calculator);[Link](calculator);
[Link](calculator);[Link](calculator);
[Link](calculator);[Link](calculator);
[Link](calculator);[Link](calculator);
[Link](calculator);[Link](calculator);

[Link](calculator);[Link](calculator);

[Link](calculator);[Link](calculator);
[Link](calculator);[Link](calculator);
[Link](calculator);

[Link] = [Link];
[Link] = 0; [Link] = 0; [Link](button1, gbc);
[Link] = 1; [Link] = 0; [Link](button2, gbc);
[Link] = 2; [Link] = 0; [Link](button3, gbc);
[Link] = 3; [Link] = 0; [Link](buttonPlus, gbc);
[Link] = 0; [Link] = 1; [Link](button4, gbc);
[Link] = 1; [Link] = 1; [Link](button5, gbc);
[Link] = 2; [Link] = 1; [Link](button6, gbc);
[Link] = 3; [Link] = 1; [Link](buttonMinus, gbc);
[Link] = 0; [Link] = 2; [Link](button7, gbc);
[Link] = 1; [Link] = 2; [Link](button8, gbc);
[Link] = 2; [Link] = 2; [Link](button9, gbc);
[Link] = 3; [Link] = 2; [Link](buttonDivide, gbc);
[Link] = 0; [Link] = 3; [Link](buttonDot, gbc);
[Link] = 1; [Link] = 3; [Link](button0, gbc);
[Link] = 2; [Link] = 3; [Link](buttonClear, gbc);
[Link] = 3; [Link] = 3; [Link](buttonMultiply, gbc);
[Link] = 3;

[Link] = 0; [Link] = 4; [Link](inputBox, gbc);


[Link] = 3; [Link] = 4; [Link](buttonEquals, gbc);
[Link]().add(panel, [Link]);
}

public void actionPerformed(ActionEvent e) {


String command = [Link]();
if ([Link](0) == 'C') {
[Link]("");
}else if ([Link](0) == '=') {
[Link](evaluate([Link]()));
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

}else {
[Link]([Link]() + command);
}
}

public static String evaluate(String expression) {


char[] arr = [Link]();
String operand1 = "";String operand2 = "";String operator = "";
double result = 0;

for (int i = 0; i < [Link]; i++) {


if (arr[i] >= '0' && arr[i] <= '9' || arr[i] == '.') {
if([Link]()){
operand1 += arr[i];
}else{
operand2 += arr[i];
}
}

if(arr[i] == '+' || arr[i] == '-' || arr[i] == '/' || arr[i] == '*') {


operator += arr[i];
}
}

if ([Link]("+"))
result = ([Link](operand1) + [Link](operand2));
else if ([Link]("-"))
result = ([Link](operand1) - [Link](operand2));
else if ([Link]("/"))
result = ([Link](operand1) / [Link](operand2));
else
result = ([Link](operand1) * [Link](operand2));
return operand1 + operator + operand2 + "=" +result;
}
}
Output:-

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

15 b). Write a JAVA program to display the digital watch in swing tutorial.

Aim:- A JAVA program to display the digital watch in swing tutorial.

Program:-
//java program to display the digital watch using swing

import [Link].*;
import java. awt.*;
import [Link].*;
import [Link].*;
public class Exe15b implements Runnable
{

JFrame f;
Thread t=null;
int hours=0,minutes=0,seconds=0;
String time="";
JButton b;
Exe15b()

{
f=new JFrame();
t=new Thread(this);
[Link]();
b=new JButton();
[Link](100,100,100,50);
[Link](b);

[Link](300,400);
[Link](null);
[Link](true);
[Link](f.EXIT_ON_CLOSE);
}
public void run()

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

{
try
{

while(true)
{
Calendar cal=[Link]();
hours=[Link](Calendar.HOUR_OF_DAY);
if(hours>12)hours-=12;
minutes=[Link]([Link]);

seconds=[Link]([Link]);
SimpleDateFormat obj=new SimpleDateFormat("hh:mm: a");
Date date=[Link]();
time=[Link](date);
printTime();
}

}
catch(Exception e)
{
}
}
public void printTime()

{
[Link](time);
}
public static void main(String args[])
{
new Exe15b();
}
}

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

Output:-

Exercise – 16 (Swings - Continued)


a). Write a JAVA program that to create a single ball bouncing inside a JPanel.

Aim:- A JAVA program that to create a single ball bouncing inside a JPanel.

Program:-
//java program to create a single ball bouncing inside a JPanel
import [Link].*;
import [Link].*;
public class Exe16a extends JPanel
{
int width;
int height;
float radius=20;
float diameter=radius*2;
float X=radius+50;
float Y=radius+20;
float dx=3;
float dy=3;
public Exe16a()
{
Thread thread=new Thread()

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

{
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
{
[Link](50);
}
catch(InterruptedException ex)
{
}
}
}
};
[Link]();
}
public void paintComponent(Graphics g)
{
[Link](g);
[Link]([Link]);
[Link]((int)(X-radius),(int)(Y-radius),(int)diameter,(int)diameter);
}
public static void main(String args[])
{
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

[Link](true);
JFrame f=new JFrame("Bouncing Ball");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300,200);
[Link](new Exe16a());
[Link](true);
}
}

Output:-

16 b). Write a JAVA program JTree as displaying a real tree upside down

Aim:-A JAVA program JTree as displaying a real tree upside down

Program:-
//java program for displaying a real tree using Jtree
import [Link].*;
import [Link];
public class Exe16b
{
JFrame f;
Exe16b()
{
f=new JFrame();
DefaultMutableTreeNode cse=new DefaultMutableTreeNode("CSE");
DefaultMutableTreeNode gents=new DefaultMutableTreeNode("Gents staff");
DefaultMutableTreeNode ladies=new DefaultMutableTreeNode("Ladies staff");
[Link](gents);
[Link](ladies);
DefaultMutableTreeNode s1=new DefaultMutableTreeNode("B V RAM KUMAR");
DefaultMutableTreeNode s2=new DefaultMutableTreeNode("A P V D L KUMAR");
[Link](s1);
[Link](s2);
DefaultMutableTreeNode l1=new DefaultMutableTreeNode("JYOSHNA");
DNR COLLEGE OF ENGINEERING AND TECHNOLOGY
JAVA Programming Lab

DefaultMutableTreeNode l2=new DefaultMutableTreeNode("SANJU");


[Link](l1);
[Link](l2);
JTree jt=new JTree(cse);
[Link](jt);
[Link](200,200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new Exe16b();
}
}

Output:-

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

ADD ON EXPEREMENTS

1.
2.

MODEL PRACTICAL END EXAMINATION QUESTIONS

II-II CSE – JAVA PROGRAMMING LAB EXTERNAL QUESTION PAPER

INTERNAL HOD

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY


JAVA Programming Lab

NAME OF THE EXIMINERS:

Name of the Examiner


i.
Name of the Physical laboratory:
ii. JAVA LAB
Room No LAB-1 & LAB-2
iii.
Name of the faculty in-charge (for curriculum lab- CL)
iv.
II [Link] (CSE) – II
iv. Class with section
Semester

v. AY and Semester 2021-22

DNR COLLEGE OF ENGINEERING AND TECHNOLOGY

You might also like