0% found this document useful (0 votes)
49 views44 pages

Java Lab Manual 2-1 R20

B tech Subject
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)
49 views44 pages

Java Lab Manual 2-1 R20

B tech Subject
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
You are on page 1/ 44

JAVA PROGRAMMING LAB MANUAL

EXERCISE-1
1-a) Write a JAVA program to display default value of all primitive data types of JAVA
class DefaultValues
{
byte b;
short s;
int i;
long l;
float f;
double d;
char c;
boolean bl;
String s;
public static void main(String[] args)
{
DefaultValues df=new DefaultValues();
System.out.println("Byte :"+df.b);
System.out.println("Short :"+df.s);
System.out.println("Int :"+df.i);
System.out.println("Long :"+df.l);
System.out.println("Float :"+df.f);
System.out.println("Double :"+df.d);
System.out.println("Char :"+df.c);
System.out.println("Boolean :"+df.bl);
System.out.println("String :"+df.s);
}
}

output:
javac DefaultValues.java
java DefaultValues
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0
Char :
Boolean :false
String: null

Page 1
JAVA PROGRAMMING LAB MANUAL

1-b) Write a JAVA program that display the roots of quadratic equation ax2+bx+c=0.

import java.util.*;

class Quadratic
{
public static vod main(String args[])
{

Scanner sc=new Scanner(System.in);


System.out.println("enter the a,b,c values");
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
double d=(b*b)-(4*a*c);
double root1,root2;
if(d==0)
{
System.out.println("roots are real and equal");
root1=root2=-b/(2*a);
System.out.println("root1="+root1+"root2="+root2);
}
else if(d>0)
{
System.out.println("roots are real and unequal");
root1=(-b+Math.sqrt(d))/(2*a);
root2=(-b-Math.sqrt(d))/(2*a);
System.out.println("root1="+root1+"root2="+root2);
}
else
{
System.out.println("roots are imaginary");
}
}
}

output:
javac Quadratic_Equation.java
java Quadratic_Equation 1 2 1
First root is:-1.0
Second root is:-1.0

Page 2
JAVA PROGRAMMING LAB MANUAL

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

class BikeRacers
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int speed[]=new int[5];
for(int i=0;i<5;i++)
{
System.out.print("\nEnter the speed of Racer-"+i+": ");
speed[i]=sc.nextInt();
}
int sum=0;
for(int i=0;i<5;i++)
sum+=speed[i];
double avg=sum/5;
System.out.print("\nThe speed of qualifying racers is: ");
for(int i=0;i<5;i++)
{
if(speed[i]>=avg)
System.out.print("\nRacer-"+i+": "+speed[i]);
}
}
}

Output:
javac BikeRacers.java
java BikeRacers
Enter the speed of Racer-0: 50
Enter the speed of Racer-1: 55
Enter the speed of Racer-2: 60
Enter the speed of Racer-3: 65
Enter the speed of Racer-4: 70
The speed of qualifying racers is:
Racer-2: 60
Racer-3: 65
Racer-4: 70

Page 3
JAVA PROGRAMMING LAB MANUAL

Page 4
JAVA PROGRAMMING LAB MANUAL

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

import java.util.Scanner;

class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
boolean status=false;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of elements");
n = sc.nextInt();
array = new int[n];
System.out.print("\nEnter " + n + " integers");

for (c = 0; c < n; c++)


array[c] = sc.nextInt();

System.out.print("\nEnter value to find");


search = sc.nextInt();

first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
status=true;
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}

if (status=true)
System.out.println(search + " found at location " +
(middle + 1) + ".");
Page 5
JAVA PROGRAMMING LAB MANUAL
else
System.out.println(search + " is not present in thelist.\n");

}
}

output:
java BinarySearch
Enter number of elements 5
Enter 5 integers 12 14 15 18 20
Enter value to find 15
15 found at location 3

Page 6
JAVA PROGRAMMING LAB MANUAL
2-b). Write a JAVA program to sort for an element in a given list of elements using
bubble sort

import java.util.Scanner;

class BubbleSort{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter No. of Elements: ");
int n=sc.nextInt();
int a[]=new int[n];
System.out.print("Enter "+n+" Elements: ");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
for(int i=0;i<n;i++)
{
for(int j=1;j<n-i;j++)
{
if(a[j]<a[j-1])
{
int t=a[j];
a[j]=a[j-1];
a[j-1]=t;
}
}
}
System.out.print("Array After Bubble Sort is: ");
for(int i=0;i<n;i++)
System.out.print(" "+a[i]);
}
}

Output:

javac BubbleSort.java
java BubbleSort
Enter No. of Elements: 5
Enter 5 Elements: 9 8 7 6 5 4
Array After Bubble Sort is: 5 6 7 8 9

Page 7
JAVA PROGRAMMING LAB MANUAL
2-c). Write a JAVA program to sort for an element in a given list of elements using
merge sort.

import java.util.Scanner;

class MergeSort
{
void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
// recursively sort
sort(a, low, mid);
sort(a, mid, high);
// merge two sorted subarrays
int[] temp = new int[N];
int i = low, j = mid;

for (int k = 0; k < N; k++)


{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}

Page 8
JAVA PROGRAMMING LAB MANUAL

for (int k = 0; k < N; k++)


a[low + k] = temp[k];
}

public static void main(String[] args)


{
Scanner sc=new Scanner(System.in);
System.out.print("Enter No. of Elements: ");
int n=sc.nextInt();
int a[]=new int[n];
System.out.print("Enter "+n+" Elements: ");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
MergeSort ms=new MergeSort();
ms.sort(a,0,n);
System.out.print("Array After Merge Sort is: ");

for(int i=0;i<n;i++)
System.out.print(" "+a[i]);
}
}

Output:

javac MergeSort.java
java MergeSort

Enter No. of Elements: 10


Enter 10 Elements: 9 8 7 6 5 4 3 2 1 0
Array After Merge Sort is: 0 1 2 3 4 5 6 7 8 9

Page 9
JAVA PROGRAMMING LAB MANUAL

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

class StringBufferExample
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello World");
sb1.delete(0,6);
System.out.println(sb1);
sb1.delete(1,2);
System.out.println(sb1);
}
}

Output:

javac StringBufferExample.java

java StringBufferExample

World
orld

Page 10
JAVA PROGRAMMING LAB MANUAL

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

class Person
{
String name;
int age; void
talk()
{
System.out.println("Hello my name is "+name);
System.out.println("and my age is "+age);
}
}
class Demo
{
public static void main(String args[])
{
Person p = new Person();
p.name="Raju";
p.age=22;
p.talk();
}
}

Output:

Hello my name is Raju


And my age is 22

Page 11
JAVA PROGRAMMING LAB MANUAL

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

class Person
{
String name;
int age;
Person()
{
name="Raju";
age=22;
}
Person(String s, int i)
{
name=s;
age=i;
}

void talk()
{
System.out.println("My Name is "+name);
System.out.println("My Age is "+age);
}
}
class Demo
{
public static void main(String args[])
{
Person p1 = new Person();
System.out.println("p1 hashcode "+p1.hashCode());
p1.talk();
Person p2 = new Person("Sita",23);
System.out.println(p2.hashCode());
p2.talk();
}
}

Output:
p1 hashcode 705927765
My Name is Raju
My Age is 22
p2 hashcode 705934457
My Name is Sita
My Age is 23

Page 12
JAVA PROGRAMMING LAB MANUAL

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

class Box
{
double width, height, depth;
Box()
{
width = height = depth = 0;
}
Box(double len)
{
width = height = depth = len;
}
Box(double w, double h, double d)
{
width = w; height
= h;depth = d;
}

double volume()
{
return width * height * depth;
}
}
public class Test
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mybox3 = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
vol = mybox3.volume();
System.out.println(" Volume of mybox3 is " + vol);
}
}

Output:

Volume of mybox1 is 3000.0


Volume of mybox2 is 0.0
Volume of mybox3 is 343.0

Page 13
JAVA PROGRAMMING LAB MANUAL

4-b). Write a JAVA program implement method overloading.

class MethodOverloading
{
void add(int a,int b)
{
int c = a+b;
System.out.println("The Sum is "+c);
}
void add(int a,int b,int c)
{
int d = a+b+c;
System.out.println("The Sum is "+d);
}
public static void main(String[] args)
{
MethodOverloading m = new MethodOverloading();
m.add(22,31);
m.add(5,27,35);
}
}

Output:

The Sum is 53
The Sum is 67

Page 14
JAVA PROGRAMMING LAB MANUAL

EXERCISE – 5

a). Write a JAVA program to implement Single Inheritance

class SuperClass
{
void add(int a,int b)
{
int c=a+b;
System.out.println("Addition is "+c);
}
}

class SubClass extends SuperClass


{
void sub(int a,int b)
{
int c=a-b;
System.out.println("Subtraction is "+c);
}
}

class Demo{

public static void main( String args[] )


{
SuperClass s1=new SuperClass();
s1.add(5,6);
SubClass s2=new SubClass();
s2.sub(15,10);
s2.add(15,27);
}
}

Output:

Addition is 11
Subtraction is 5
Addition is 42

Page 15
JAVA PROGRAMMING LAB MANUAL

b). Write a JAVA program to implement multi level Inheritance

class A
{
void showA()
{
System.out.println("Method A");
}
}
class B extends A
{
void showB()
{
System.out.println("Method B");
}
}

class C extends B
{
void showC()
{
System.out.println("Method C");
}
}
class MultiLevel
{
public static void main(String[] args)
{
C c1=new C();
c1.showC();
c1.showB();
c1.showA();
}
}

Output:
Method C
Method B
Method A

Page 16
JAVA PROGRAMMING LAB MANUAL

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

abstract class Shape


{
abstract void findCircle(double r);
abstract void findTriangle(double b, double h);
abstract void findRectangle(double w, double h);

}
class AreaShape extends Shape
{
void findCircle(double r)
{
double a=3.14*r*r;
System.out.println("Area of Circle = "+a);
}

void findTriangle(double b, double h)


{
double a=0.5*b*h;
System.out.println("Area of Triangle = "+a);
}

void findRectangle(double w, double h)


{
double a=w*h;
System.out.println("Area of Rectangle = "+a);
}

public static void main(String[] args)


{
AreaShape as=new AreaShape();
as.findCircle(4.3);
as.findTriangle(6.1,4.5);
as.findRectangle(5.5,7.2);
}
}

Output:

Area of Circle = 58.0586


Area of Triangle = 13.725
Area of Rectangle = 39.6

Page 17
JAVA PROGRAMMING LAB MANUAL

EXERCISE – 6

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

class One
{
int i=10;
void show()
{
System.out.println("Super Class Method i: "+i);
}
}
class Two extends One
{
int i=20;
void show()
{
System.out.println("Sub Class Method i: "+i);super.show();
System.out.println("Super Class Variable i: "+super.i);
}
}

class Demo{
public static void main( String args[] )
{
Two t=new Two();
t.show();
}
}

Output:

Sub Class Method i: 20


Super Class Method i: 10
Super Class Variable i: 10

Page 18
JAVA PROGRAMMING LAB MANUAL

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

interface Father
{
double HT=6.2;
void height();
}

interface Mother
{
double HT=5.8;
void color();
}
class Child implements Father, Mother
{
public void height()
{
double ht=(Father.HT+Mother.HT)/2;
System.out.println("Child's Height= "+ht);
}
public void color()
{
System.out.println("Child Color= brown");
}
public static void main(String[] args)
{
Child c=new Child();
c.height();
c.color();
}
}

Output:

Child's Height= 6.0


Child Color= brown

Page 19
JAVA PROGRAMMING LAB MANUAL

EXERCISE – 7

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

class Division
{
public static void main(String[] args)
{
try{
System.out.println("WELCOME");int a=5;
int b=0; int
c=a/b;
System.out.println("The Division is "+c);
}
catch(ArithmeticException ae)
{
System.out.println("Division with zero is notpossible");
}
finally{
System.out.println("LOGOUT");
}
}
}

Output:

WELCOME
Division with zero is not possible
LOGOUT

Page 20
JAVA PROGRAMMING LAB MANUAL

b).Write a JAVA program Illustrating Multiple catch clauses

import java.util.*;

class Division
{
public static void main(String[] args)
{
try{
System.out.println("WELCOME");
Scanner sc=new Scanner(System.in);
System.out.print("Enter a value: ");
int a=sc.nextInt();
System.out.print("Enter b value: ");
int b=sc.nextInt();
int c=a/b;
System.out.println("The Division is "+c);
}

catch(InputMismatchException ae)
{
System.out.println("Wrong Input");
}
catch(ArithmeticException ae)
{
System.out.println("Division with zero is notpossible");
}
finally{
System.out.println("LOGOUT");
}
}
}

Output-1:

WELCOME
Enter a value: 5
Enter b value: a
Wrong Input
LOGOUT

Output-2:

WELCOME
Enter a value: 5
Enter b value: 0
Division with zero is not possible
LOGOUT
Page 21
JAVA PROGRAMMING LAB MANUAL

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

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

Output:

SBI Rate of Interest: 8.4


AXIS Rate of Interest: 7.3

Page 22
JAVA PROGRAMMING LAB MANUAL

b). 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).

Page 23
JAVA PROGRAMMING LAB MANUAL

EXERCISE – 9

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


import java.util.*;

class ThrowException
{
public static void main(String[] args)
{
try{
System.out.println("WELCOME");
throw new NullPointerException("Exception Data");
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
}
}

Output:
WELCOME
java.lang.NullPointerException: Exception Data

Page 24
JAVA PROGRAMMING LAB MANUAL
b). Write a JAVA program for creation of Illustrating finally

class MyFinallyBlock
{
public static void main(String[] a)
{
try
{
int i = 10/0;
}
catch(Exception ex)
{
System.out.println("Inside 1st catch Block");
}
finally
{
System.out.println("Inside 1st finally block");
}
}
}

Output:
Inside 1st catch Block
Inside 1st finally block

Page 25
JAVA PROGRAMMING LAB MANUAL

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


class BuiltIn
{
public static void main(String args[])
{
int marks[] = { 40, 50, 60 };
System.out.println("Hello 1");

try
{
int m1 = marks[3];
System.out.println("Marks are " + m1);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Size of array greater than 3");
}
}
}

Output:
Hello 1
Size of array greater than 3

Page 26
JAVA PROGRAMMING LAB MANUAL

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

import java.util.Scanner;
class MyException extends Exception
{
MyException(String str)
{
super(str);
}
}
class ExceptionDemo
{
public static void main(String[] args)
{
try{ System.out.println("WELCOME");
System.out.print("Enter amount to withdraw: ");
Scanner sc=new Scanner(System.in);
double bal=sc.nextDouble();
if(bal>25000)
{
MyException me=new MyException("Balance is veryhigh");
throw me;
}
System.out.println("Balance is withdrawn");
}
catch(MyException me)
{
System.out.println(me);
}
}
}

Output-1:
WELCOME
Enter amount to withdraw: 26000
MyException: Balance is very high
Output-2:
WELCOME
Enter amount to withdraw: 15000
Balance is withdrawn

Page 27
JAVA PROGRAMMING LAB MANUAL

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

Program:

class GoodMorning extends Thread


{
public void run()
{
for(int i=0;i<10;i++)
{
try{
Thread.sleep(1000);
}
catch(Exception e){}
System.out.println("GoodMorning");
}
}
}
class Hello extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
try{
Thread.sleep(2000);
}
catch(Exception e){}
System.out.println("Hello");
}
}
}
class Welcome extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{

Page 28
JAVA PROGRAMMING LAB MANUAL
try{
Thread.sleep(3000);
}
catch(Exception e){}
System.out.println("Welcome");
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{

GoodMorning gm=new GoodMorning();


Thread t1=new Thread(gm);
Hello hl=new Hello();
Thread t2=new Thread(hl);
Welcome wc=new Welcome();
Thread t3=new Thread(wc);
t1.start();
t2.start();
t3.start();
}
}

Output:

GoodMorning
Hello
GoodMorning
Welcome
GoodMorning
Hello
GoodMorning
GoodMorning
Welcome
Hello
GoodMorning
GoodMorning
Hello
GoodMorning
Welcome
GoodMorning
Hello
GoodMorning
Welcome
Hello
Hello

Page 29
JAVA PROGRAMMING LAB MANUAL
Welcome
Hello
Welcome
Hello
Hello
Welcome
Welcome
Welcome
Welcome

Page 30
JAVA PROGRAMMING LAB MANUAL
10-b) Write a program illustrating isAlive()and join ()

Program:
class MyThread extends Thread

{
public void run()
{
System.out.println("r1 ");try {
Thread.sleep(500);
}
catch(InterruptedException ie) { }
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());
}
}

Output:

true
r1
r1
true
r2
r2

Page 31
JAVA PROGRAMMING LAB MANUAL

10-c) Write a Program illustrating Daemon Threads.


Program:

class DaemonThread extends Thread


{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("daemon thread work");
}
else
{
System.out.println("user thread work");
}
}
public static void main(String[] args)
{
DaemonThread t1=new DaemonThread();
DaemonThread t2=new DaemonThread();
DaemonThread t3=new DaemonThread();

t1.setDaemon(true);

t1.start();
t2.start();
t3.start();
}
}

Output:

daemon thread work


user thread work
user thread work

Page 32
JAVA PROGRAMMING LAB MANUAL

EXCERCISE-11
11-a).Write a JAVA program Producer Consumer Problem

import java.util.*;

class Producer extends Thread


{
StringBuffer sb=new StringBuffer();
public void run()
{
synchronized(sb)
{
for(int i=1;i<=10;i++)
{
sb.append(i+" : ");
System.out.println("Appending");
try{
Thread.sleep(100);
}
catch(InterruptedException ie)
{ }
}
sb.notify();
}
}
}

class Consumer extends Thread


{
Producer prod;
Consumer(Producer prod)
{
this.prod=prod;
}
public void run()
{
synchronized(prod.sb)
{
try{
prod.sb.wait();
}

Page 33
JAVA PROGRAMMING LAB MANUAL

catch(Exception e)
{ }
System.out.println("Data is: "+prod.sb);
}
}
}

class Communciate
{
public static void main(String[] args)
{
Producer p=new Producer();
Consumer c=new Consumer(p);Thread
t1=new Thread(p); Thread t2=new
Thread(c);
t2.start(); //Consumer thread will start first
t1.start();
}
}

Output:
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending

Data is: 1 : 2 : 3 : 4 : 5 : 6 : 7 : 8 : 9 : 10 :

Page 34
JAVA PROGRAMMING LAB MANUAL

11-b) Write a case study on thread Synchronization after solving the aboveproducer
consumer problem
Synchronization:
When thread is already acting on an object, preventing any other thread from acting
on the same object is called Thread Synchronization or thread safe. Thread synchronization is
recommended when multiple threads are used on the same object.

In the above Producer-Consumer program we are synchronization on StringBuffer


Object. In the Producer Thread sb.notify()method is sending a notification to the
Consumer thread that the StringBuffer object sb is available, and it can be used now.

Meanwhile, what the Consumer thread is doing? It is waiting for the notification that
the StringBuffer object sb (of Producer class) is available. Here, there is no need of using

sleep() method to go into sleep for some time wait() method stops waiting as soon as it
receives the notification. So there is no time delay to receive the data from the Producer.

Page 35
JAVA PROGRAMMING LAB MANUAL
EXCERCISE-12
12-a) Write a case study on including in class path in your os environment ofyour
package.
Setting CLASSPATH:
The CLASSPATH is an environment variable that tells the Java compiler where to
look for class files to import. CLASSPATH is generally set to a directory or a JAR (Java
Archive) file.
 To see what is there in currently in CLASSPATH variable in your system. You can type
the command in windows.
 echo %CLASSPATH%

 Suppose, preceding command has disp1ayed class path as:


C:\rnr;.
 This means the current class path is set to rnr directory in C: \ and also to the current
directory represented by dot (.). Our package pack does not exist in either rnr or current
directory. Our package exists in D:\sub, as:

set CLASSPATH=D:\sub;.;%CLASSPATH%

Page 36
JAVA PROGRAMMING LAB MANUAL

12-b) Write a JAVA program that import and use the defined your package inthe
previous Problem

package pack;

public class Addition


{
public void add(int a,int b)
{
int c=a+b;
System.out.println("The sum is "+c);
}
}

 To compile the program by using following command,


javac -d . Addition.java

 write program to import use Addition class of a package pack.

import pack.Addition;class
DemoPack
{
public static void main(String[] args)
{
Addition a1=new Addition();
a1.add(15,27);
}
}

Output: java DemoPack


The Sum is 42

Page 37
JAVA PROGRAMMING LAB MANUAL
EXCERCISE-13
a).Write a JAVA program to paint like paint brush in applet.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Painting extends Applet implements MouseMotionListener


{
public void init()
{
addMouseMotionListener(this);
setBackground(Color.white);
}
public void mouseDragged(MouseEvent me)
{
Graphics g=getGraphics();
g.setColor(Color.red);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}

javac Painting.java

<html>
<applet code="Painting.class" width=700 height=500 >
</applet>
</html>

appletviewer Painting.html

Output:

Page 38
JAVA PROGRAMMING LAB MANUAL

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


import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;

public class MyClock extends Applet implements Runnable


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

public void init() {


width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}

public void start()


{
if ( t == null )
{
t = new Thread( this );
t.setPriority( Thread.MIN_PRIORITY );
threadSuspended = false;
t.start();
}
else
{
if ( threadSuspended )
{
threadSuspended = false;
synchronized( this ) {
notify();
}
}
}
}

public void stop()


{
threadSuspended = true;
}

Page 39
JAVA PROGRAMMING LAB MANUAL

public void run()


{
try
{
while (true)
{
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );

if ( threadSuspended ) {
synchronized( this ) {
while ( threadSuspended ) {
wait();
}
}
}
repaint();
t.sleep( 1000 );
}
}
catch (Exception e) { }
}

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


{
angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
g.drawLine( width/2, height/2, width/2 + x, height/2 + y);
}

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


{
angle -= 0.5 * Math.PI;
int x = (int)( radius*Math.cos(angle) );
int y = (int)( radius*Math.sin(angle) );
angle += 2*Math.PI/3;
int x2 = (int)( 5*Math.cos(angle) );
int y2 = (int)( 5*Math.sin(angle) );
angle += 2*Math.PI/3;
int x3 = (int)( 5*Math.cos(angle) );
int y3 = (int)( 5*Math.sin(angle) );
g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );

Page 40
JAVA PROGRAMMING LAB MANUAL
g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );
g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );
}

public void paint( Graphics g )


{
g.setColor( Color.gray );
drawWedge( 2*Math.PI * hours / 12, width/5, g ); drawWedge(
2*Math.PI * minutes / 60, width/3, g );drawHand( 2*Math.PI *
seconds / 60, width/2, g ); g.setColor( Color.white );
}
}

Output:

Page 41
JAVA PROGRAMMING LAB MANUAL
c). Write a JAVA program to create different shapes and fill colors using Applet.

import java.awt.*;
import java.applet.*;

public class DrawShapes extends Applet


{
public void paint(Graphics g)
{
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.setColor(Color.blue);
g.fillRect(60,10,30,80);
g.setColor(Color.green);
g.drawLine(100,140,230,10);
g.drawOval(230,10,200,150);
g.setColor(Color.blue);
g.fillOval(245,25,100,100);
}
}

Output:

Page 42
JAVA PROGRAMMING LAB MANUAL

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

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class DisplayXY extends Applet implements MouseMotionListener
{
int x,y; String
str="";
public void init()
{
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent me)
{
x = me.getX();
y = me.getY();
str = "Mouse Dragged "+x+" , "+y;
repaint();
}
public void mouseMoved(MouseEvent me)
{
x = me.getX();
y = me.getY();
str = "Mouse Moved "+x+" , "+y;
repaint();
}
public void paint(Graphics g)
{
g.drawString(str, x, y);
}
}

Output:

Page 43

Copy protected with Online-PDF-No-Copy.com


JAVA PROGRAMMING LAB MANUAL

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

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Key extends Applet implements KeyListener
{
int X=20,Y=30;
String msg=""; public void
init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent k)
{
showStatus("Key Pressed");msg="Key
Pressed"; repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");msg="Key
Up"; repaint();
}
public void keyTyped(KeyEvent k)
{
showStatus("Key Typed");msg="Key
Typed"; repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}

Output:

Page 44

Copy protected with Online-PDF-No-Copy.com

You might also like