0% found this document useful (0 votes)
2 views45 pages

Java Lab Manual

The document contains a series of laboratory exercises and Java programming tasks for students at Kallam Haranadhareddy Institute of Technology. Each exercise includes a description, the Java code to implement the task, and is structured for educational purposes. The exercises cover topics such as primitive data types, quadratic equations, sorting algorithms, inheritance, and abstract classes.

Uploaded by

B.srinadh Naidu
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)
2 views45 pages

Java Lab Manual

The document contains a series of laboratory exercises and Java programming tasks for students at Kallam Haranadhareddy Institute of Technology. Each exercise includes a description, the Java code to implement the task, and is structured for educational purposes. The exercises cover topics such as primitive data types, quadratic equations, sorting algorithms, inheritance, and abstract classes.

Uploaded by

B.srinadh Naidu
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

KALLAM HARANADHAREDDY

INSTITUTE OF TECHNOLOGY
(APPROVED BY AICTE NEW DELHI, AFFLIATED TO
JNTUK, KAKINADA) CHOWDAVARAM, GUNTUR-19

Roll No:

CERTIFICATE
This is to Certify that the Bonafide Record of the Laboratory Work done by

Mr/Ms……………………………………………………………………………………………

of……..[Link]/[Link]/Diploma……...Semester in …………Branch has completed………

experiments in ……………………………………………………….…………………………

Laboratory during the Academic year 20 -20

Faculty-in-charge Head of the Department

Internal Examiner External Examiner


INDEX

PAGE
EX.
NO DATE NAME OF THE EXPERIMENT FROM TO MARKS SIGNATURE

.
PAGE
EX.
NO DATE NAME OF THE EXPERIMENT FROM TO MARKS SIGNATURE

.
PAGE

EX.
NO DATE NAME OF THE EXPERIMENT FROM TO MARKS SIGNATURE

.
Exercise:
Date: Roll No:
Exercise:
Date: Roll No:

EXERCISE-1(a)

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

Program:
import [Link].*;
class Ex1a
{
static int i;
static double d;
static float f;
static boolean b;
static String s;
public static void main(String args[])
{
[Link]("int default value = "+ i);
[Link]("double default value = "+ d);
[Link]("float default value = "+ f);
[Link]("boolean default value = "+ b);
[Link]("String default value = "+ s);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-1(b)

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.

Prpgram:
public class Ex1b
{
public static void main(String[] args)
{
double a = 1, b = 5, c = 6;
double r1, r2;

double det = b * b - 4 * a * c;

if (det > 0) {

r1 = (-b + [Link](det)) / (2 * a);


r2 = (-b - [Link](det)) / (2 * a);

[Link]("root1 = %.2f and root2 = %.2f", r1, r2);


}

else if (det == 0) {

r1 = r2 = -b / (2 * a);
[Link]("root1 = root2 = %.2f;", r1);
}

else
{
double real = -b / (2 * a);
double imag = [Link](-det) / (2 * a);
[Link]("root1 = %.2f+%.2fi", real, imag);
[Link]("\nroot2 = %.2f-%.2fi", real, imag);
}
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-1()

1(c) //Five Bikers Compete in a race such that they drive at a constant speed
which may or may not be the same as the other.
//To qualify the race, the speed of a racer must be more than the average speed of
all 5 racers.
//Take as input the speed of each racer and print back the speed of qualifying
racers.

Program:
import [Link];
class Ex1c
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
int speed[]=new int[5];
for(int i=0;i<5;i++)
{
[Link]("\nEnter the speed of Racer-"+(i+1)+": ");
speed[i]=[Link]();
}
int sum=0;
for(int i=0;i<5;i++)
sum+=speed[i];
double avg=sum/5;
[Link]("\nThe speed of qualifying race is: "+avg);
[Link]("\nThe speed of qualifying racers is: ");
for(int i=0;i<5;i++)
{
if(speed[i]>=avg)
[Link]("\nRacer-"+i+": "+speed[i]);
}
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-2(a)

2(a)//Write a JAVA program to search for an element in a given list of elements


//using binary search mechanism.
Program:
class Ex2a
{
public static void main(String args[])
{
int first, last, middle;

int a[] = {10,20,30,40,50,60,80};

[Link]("*** Binary Search ***");


for(int i=0;i<[Link];i++)
[Link](" "+a[i]);
[Link]();
int key = 60;
first = 0;
last=[Link]-1;
middle = (first + last)/2;

while( first <= last )


{
if ( a[middle] < key )
first = middle + 1;
else if ( a[middle] == key )
{
[Link](key + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
[Link](key + " is not found.\n");
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-2(b)

2(b)//Write a JAVA program to sort for an element in a given list of elements using
bubble sort
Program:
class Ex2b
{
public static void main(String[] args)
{
int arr[] ={10,5,8,2,12,3,9,1};

int n = [Link];

[Link]("Array Before Bubble Sort");


for(int i=0; i < n; i++)
[Link](arr[i] + " ");
[Link]();

int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(arr[j-1] > arr[j])
{

temp = arr[j-1];

arr[j-1] = arr[j];
arr[j] = temp;
}

}
}

[Link]("Array After Bubble Sort");


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

}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-2(c)

2(c)Write a JAVA program to sort for an element in a given list of elements using
merge sort.
Program:
class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]

void merge(int arr[], int l, int m, int r)


{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;

/* Create temp arrays */


int L[] = new int [n1];
int R[] = new int [n2];

/*Copy data to temp arrays*/


for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];

/* Merge the temp arrays */

// Initial indexes of first and second subarrays


int i = 0, j = 0;

// Initial index of merged subarry array


int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:
k++;
}

/* Copy remaining elements of L[] if any */


while (i < n1)
{
arr[k] = L[i];

i++;
k++;
}

/* Copy remaining elements of R[] if any */


while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-2(d)

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


Program:
public class ex2d
{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("Java programming");
[Link]("string1: " + sb);

sb = [Link](2,6);
[Link]("After deleting: " + sb);

sb = new StringBuffer("let us learn java");


[Link]("string2: " + sb);

sb = [Link](0, 7);
[Link]("After deleting: " + sb);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-3(a)

3(a)//Write a JAVA program to implement class mechanism.


//Create a class, methods and invoke them inside main method.
Program:
public class Ex3a
{
// Static method
static void Hello()
{
[Link]("Hello KHIT");

// Public method
public void Hai()
{
[Link]("Hai KHIT");
}

// Main method
public static void main(String[] args)
{
Hello(); // Call the static method
// Hai(); //This would compile an error

Ex3a x = new Ex3a(); // Create an object of class


[Link](); // Call the public method on the object
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-3(B)

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


Program:
public class Ex3b
{
int rollno;
String name;

// default constructor
Ex3b()
{
rollno = 501;
name = "CSE";
[Link]("default constructor called");
}

Ex3b(int i, String s)
{
rollno = i;
name = s;
[Link]("parameterized constructor called");
}
void display(){ [Link](rollno+" "+name); }

public static void main(String[] args)


{
Ex3b x1 = new Ex3b(); // Create an object of class
[Link]();
Ex3b x2 = new Ex3b(401,"ECE"); // Create an object of class
[Link]();
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-4(a)

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


Program:
public class ex4a
{
int rollno;
String name;
int age;

// default constructor
ex4a()
{
rollno = 501;
name = "CSE";

}
ex4a(int i, String s)

{
rollno = i;
name = s;
}
ex4a(int i, String s, int j)
{
rollno = i;
name = s;
age = j;
}
void display()
{
[Link]("rollno"+"\t"+"name"+"\t"+"age");
[Link](rollno+"\t"+name+"\t"+age); }

public static void main(String[] args)


{
ex4a x1 = new ex4a(); // Create an object of class
[Link]();
ex4a x2 = new ex4a(401,"ECE"); // Create an object of class
[Link]();
ex4a x3 = new ex4a(201,"EEE",20);
[Link]();
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-4(b)

4(b): Write a JAVA program implement method overloading.


Program:
class DisplayOverloading
{
public void disp(char c)
{
[Link](c);
}
public void disp(char c, int num)

{
[Link](c + " "+num);
}
}
class Ex4b
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
[Link]('a');
[Link]('a',10);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-5(a)

5(a) :Write a JAVA program to implement Single Inheritance


Program:
class SuperClass
{
void add(int a,int b)
{
int c=a+b;
[Link]("Addition is "+c);

}
}
class SubClass extends SuperClass
{
void sub(int a,int b)
{
int c=a-b;
[Link]("Subtraction is "+c);
}
}
class Ex5a
{
public static void main( String args[] )
{
SuperClass s1=new SuperClass();
[Link](5,6);
SubClass s2=new SubClass();
[Link](15,10);
[Link](15,27);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-5(b)

5(b)Write a JAVA program to implement multi level Inheritance


Program:
class A
{
void showA()
{
[Link]("Method A");
}

}
class B extends A
{
void showB()
{
[Link]("Method B");
}
}
class C extends B
{
void showC()
{
[Link]("Method C");
}
}
class Ex5b
{
public static void main(String[] args)
{
C c1=new C();
[Link]();
[Link]();
[Link]();
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-5(c)

5c) Write a java program for abstract class to find areas of different shapes
Program:
abstract class Shape
{
abstract void findCircle(double r);
abstract void findTriangle(double b, double h);
abstract void findRectangle(double w, double h);
}
class Ex5c extends Shape
{

void findCircle(double r)
{
double a=3.14*r*r;
[Link]("Area of Circle = "+a);
}
void findTriangle(double b, double h)
{
double a=0.5*b*h;
[Link]("Area of Triangle = "+a);
}
void findRectangle(double w, double h)
{
double a=w*h;
[Link]("Area of Rectangle = "+a);
}
public static void main(String[] args)
{
Ex5c as=new Ex5c();
[Link](4.3);
[Link](6.1,4.5);
[Link](5.5,7.2);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-6(a)

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


class One
{
int i=10;
void show()
{
[Link]("Super Class Method i: "+i);
}

}
class Two extends One
{
int i=20;
void show()
{
[Link]("Sub Class Method i: "+i);
[Link]();
[Link]("Super Class Variable i: "+super.i);
}
}
class Demo
{
public static void main( String args[] )
{
Two t=new Two();
[Link]();
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-6(b)

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

interface Father
{
double HT=6.2;
void height();
}
interface Mother
{
double HT=5.8;
void color();
}
class Child implements Father, Mother
{
public void height()
{
double ht=([Link]+[Link])/2;

[Link]("Child's Height= "+ht);


}
public void color()
{
[Link]("Child Color= brown");
}
public static void main(String[] args)
{
Child c=new Child();
[Link]();
[Link]();
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-7(a)

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


Program:
class Ex7a
{
public static void main(String[] args)
{
try{
[Link](“WELCOME”);
int a=5;
int b=0;

int c=a/b;
[Link](“The Division is “+c);
}
catch(ArithmeticException ae)
{
[Link](“Division with zero is not
possible”);
}
finally{
[Link](“LOGOUT”);
}
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-7(b)

7b).Write a JAVA program Illustrating Multiple catch clauses


Program:
import [Link].*;
class Ex7b
{
public static void main(String[] args)

{
try
{
[Link]("WELCOME");
Scanner sc=new Scanner([Link]);
[Link]("Enter a value: ");
int a=[Link]();
[Link]("Enter b value: ");
int b=[Link]();
int c=a/b;
[Link]("The Division is "+c);
}
catch(InputMismatchException ae)
{
[Link]("Wrong Input");
}
catch(ArithmeticException ae)
{
[Link]("Division with zero is not possible");
}
finally
{
[Link]("LOGOUT");
}
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCIS-8(a)

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


Program:
class Bank
{
float interest()
{
return 0;
}
}

class SBI extends Bank


{
float interest()
{
return 8.4f;
}
}
class AXIS extends Bank
{
float interest()
{
return 7.3f;
}
}
class RuntimePoly
{
public static void main(String args[])
{
Bank b1=new SBI();
[Link]("SBI Rate of Interest:"+[Link]());
Bank b2=new AXIS();
[Link]("Axis Rate of Interest:"+[Link]());
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-8(b)

8b). Write a Case study on run time polymorphism, inheritance that implements in
above problem Runtime Polymorphism (or Dynamic polymorphism)

It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in


which a call to an overridden method is resolved at runtime, that’s why it is called runtime
polymorphism. I have already discussed method overriding in detail in a separate tutorial,
refer it: Method Overriding in Java.

In this previous example we have three classes Bank, SBI and AXIS. Bank is a parent
class and SBI and AXIS are child classes. The child classes are overriding the method
interest() of parent class. In this previous example we have child class object assigned to
the parent class reference so in order to determine which method would be called, the type
of the object would be determined at run-time. It is the type of object that determines
which version of the method would be called (not the type of reference).

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-9(a)

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


Program:
import [Link].*;
class Ex9a
{
public static void main(String[] args)
{
try
{
[Link]("WELCOME");
throw new NullPointerException("Exception Data");
}
catch(NullPointerException ne)
{
[Link](ne);
}
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-9(b)

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


Program:
class Ex9b
{
public static void main(String[] args)
{
try
{
int i = 10/0;
}
catch(Exception ex)
{
[Link]("Inside 1st catch Block");
}
finally
{
[Link]("Inside 1st finally block");
}
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-10(a)

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

Program:
class A extends Thread
{
synchronized public void run()
{
try {
int i=0;
while (i<5) {
sleep(1000);
[Link]("Good morning");

i++;
}
}
catch(Exception e)
{}
}
}
class B extends Thread
{
synchronized public void run()
{
try {
int i=0;
while (i<5) {
sleep(2000);
[Link]("Hello");
i++;
}
}
catch(Exception e)
{}
}
}
class C extends Thread
{
synchronized public void run()
{
try {
int i=0;

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:
while (i<5) {
sleep(3000);
[Link]("Welcome");
i++;
}
}
catch(Exception e)
{}
}
}
class Ex10a
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
[Link]();
[Link]();
[Link]();
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-10(b)

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


Program:
public class Ex10b extends Thread
{
public void run()

{
[Link]("run started ");
try {
[Link](500);
}catch(InterruptedException ie){ }
[Link]("run ended ");
}
public static void main(String[] args)
{
Ex10b t1=new Ex10b();
Ex10b t2=new Ex10b();
[Link]();
[Link]([Link]());
[Link]([Link]());

// try{
// [Link](); //Waiting for t1 to finish
// }catch(InterruptedException ie){}

[Link]();
[Link]([Link]());
[Link]([Link]());
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-10(c)

10(c). Write a Program illustrating Daemon Threads.


Program:
public class Ex10c extends Thread{

public void run(){


[Link]("Is this thread Daemon? - "+isDaemon());
}
public static void main(String args[]){
Ex10c t1 = new Ex10c();
Ex10c t2 = new Ex10c();
Ex10c t3 = new Ex10c();
[Link](true);
[Link]();
[Link]();
[Link]();
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-11(a)

11(a). Write a JAVA program Producer Consumer Problem


Program:
class Q
{

int n;
boolean valueSet = false;
synchronized int get()
{
while(!valueSet)
try
{
wait();
}
catch(InterruptedException e) { }
[Link]("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n)
{
while(valueSet)
try {
wait();
}
catch(InterruptedException e) { }
this.n = n;
valueSet = true;
[Link]("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
newThread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
[Link](i++);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
try{
while(true) {

[Link]();
[Link](1000);}
} catch(Exception e) { }
}
}
class Th9 {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
[Link]("Press Control-C to stop.");
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-11(b)

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

Synchronization:

When thread is already acting on an object, preventing any other thread from
acting on the same object is called Thread Synchronization or thread safe. Thread
synchronization is recommended when multiple threads are used on the same object.
In the above Producer-Consumer program we are synchronization on
StringBuffer Object. In the Producer Thread [Link]()method is sending a
notification to the Consumer thread that the StringBuffer object sb is available, and
it can be used now.
Meanwhile, what the Consumer thread is doing? It is waiting for the notification
that the StringBuffer object sb (of Producer class) is available. Here, there is no need of
using sleep() method to go into sleep for some time wait() method stops waiting as
soon as it receives the notification. So there is no time delay to receive the data from the
Producer.

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

ECERCISE-12(a)

12(a). How does the Java run-time system know where to look for packages that
you create?

• The answer has three parts. First, by default, the Java run-time system uses the
current working directory as its starting point. Thus, if your package is in a
subdirectory of the current directory, it will be found.
• Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
• Third, you can use the -classpath option with java and javac to specify the path to
your classes.

Consider an example
This example has two packages. Remember that one package named KHIT held
at E: drive and another named CSE at F: drive of computer system.

Store class A in E drive

public class A
{
public void call()
{
[Link]("Hi I am Class A from KHIT package (E: Drive)");
}
}

Store class Demo in F drive


public class Demo
{
public static void main(String args[])
{
[Link]("Hello I am Demo class from CSE package(F: Drive)\n");
[Link]("Trying to call Class A from KHIT package (E: Drive)\n");
A a = new A();
[Link]();
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-12(b)

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

Program:
package pack2;
class Addition1
{
public void add(int a,int b)
{

int c=a+b;
[Link](“The sum is “+c);
}
}

Write program to use this pack2 in another class

Program:
Import pack2.Addition1;
class Demopack
{
public static void main (String args[])
{
Addition a1=new Addition();
[Link](10,30);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-13(a)

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


Program:
import [Link].*;
import [Link].*;
import [Link].*;

/*
<applet code="Ex13a" width=600 height=600>
</applet>
*/

public class Ex13a extends Applet implements MouseMotionListener {

public void init() {


addMouseMotionListener( this );
setBackground([Link]);
}

public void mouseDragged(MouseEvent e) {


Graphics g = getGraphics();
[Link]([Link]);
[Link]([Link](),[Link](),5,5);
}

public void mouseMoved(MouseEvent e) { }


}
Output:

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-13(b)

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


Program:
import [Link];
import [Link].*;
import [Link].*;

/*
<applet code="Ex13b" width=600 height=600>
</applet>
*/

public class Ex13b extends Applet {

@Override
public void init()
{
// Applet window size & color
[Link](new Dimension(800, 400));
setBackground(new Color(50, 50, 50));
new Thread() {
@Override
public void run()
{
while (true) {
repaint();
delayAnimation();
}
}
}.start();
}

// Animating the applet


private void delayAnimation()
{
try {

// Animation delay is 1000 milliseconds


[Link](1000);
}
catch (InterruptedException e) {
[Link]();
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:
// Paint the applet
@Override
public void paint(Graphics g)
{
// Get the system time
Calendar time = [Link]();

int hour = [Link](Calendar.HOUR_OF_DAY);


int minute = [Link]([Link]);
int second = [Link]([Link]);

// 12 hour format
if (hour > 12) {
hour -= 12;
}

// Draw clock body center at (400, 200)


[Link]([Link]);
[Link](300, 100, 200, 200);

// Labeling
[Link]([Link]);
[Link]("12", 390, 120);
[Link]("9", 310, 200);
[Link]("6", 400, 290);
[Link]("3", 480, 200);

// Declaring variables to be used


double angle;
int x, y;

// Second hand's angle in Radian


angle = [Link]((15 - second) * 6);

// Position of the second hand


// with length 100 unit
x = (int)([Link](angle) * 100);
y = (int)([Link](angle) * 100);

// Red color second hand


[Link]([Link]);
[Link](400, 200, 400 + x, 200 - y);

// Minute hand's angle in Radian


angle = [Link]((15 - minute) * 6);

// Position of the minute hand

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

// with length 80 unit


x = (int)([Link](angle) * 80);
y = (int)([Link](angle) * 80);

// blue color Minute hand


[Link]([Link]);
[Link](400, 200, 400 + x, 200 - y);

// Hour hand's angle in Radian


angle = [Link]((15 - (hour * 5)) * 6);

// Position of the hour hand


// with length 50 unit
x = (int)([Link](angle) * 50);
y = (int)([Link](angle) * 50);

// Black color hour hand


[Link]([Link]);
[Link](400, 200, 400 + x, 200 - y);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-13(c)

13(c). Write a JAVA program to create different shapes and fill colors using Applet.
Program:
import [Link].*;
import [Link].*;

/*
<applet code="Ex13c" width=800 height=400>
</applet>
*/

public class Ex13c extends Applet{


int x=300,y=100,r=50;

public void paint(Graphics g){


[Link]([Link]); //Drawing line color is red
[Link](3,300,200,10);
[Link]([Link]);
[Link]("Line",100,100);

[Link](x-r,y-r,100,100);
[Link]([Link]); //Fill the yellow color in circle
[Link]( x-r,y-r, 100, 100 );
[Link]([Link]);
[Link]("Circle",275,100);

[Link](400,50,200,100);
[Link]([Link]); //Fill the yellow color in rectangel
[Link]( 400, 50, 200, 100 );
[Link]([Link]);
[Link]("Rectangel",450,100);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-14(a)

14(a). Write a JAVA program that display the x and y position of the cursor
movement using Mouse.
Program:
import [Link].*;
import [Link].*;
import [Link].*;

/*
<applet code="Ex14a" width=800 height=400>
</applet>
*/

public class Ex14a extends Applet implements MouseMotionListener {

int x=100, y=100;


String str = "";

public void init() {


addMouseMotionListener( this );
}

public void mouseDragged( MouseEvent e ) {


int x = [Link]();
int y = [Link]();
str = "Mouse Dragged "+x+" , "+y;
repaint();
}
public void mouseMoved( MouseEvent e ) {
int x = [Link]();
int y = [Link]();
str = "Mouse Moved "+x+" , "+y;
repaint();
}
public void paint( Graphics g ) {
[Link](str, x, y);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR
Exercise:
Date: Roll No:

EXERCISE-14(b)

14(b). Write a JAVA program that identifies key-up key-down event user entering text in a Applet.
Program:
import [Link].*;
import [Link].*;
import [Link].*;

/*
<applet code="Ex14b" width=600 height=400>
</applet>
*/

public class Ex14b extends Applet implements KeyListener


{
String str=" ";
int x = 100, y = 100;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
str= "key pressed: ";
repaint();
}
public void keyReleased(KeyEvent ke)
{
str= "key Released ";
repaint();
}
public void keyTyped(KeyEvent ke)
{
str=str+[Link]();
repaint();
}
public void paint(Graphics g)
{
[Link](str,x,y);
}
}

KALLAM HARANADHAREDDY INSTITUTE OF TECHNOLOGY, CHOWDAVARAM


GUNTUR

You might also like