0% found this document useful (0 votes)
15 views53 pages

Java Lab Manual

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

Java Lab Manual

refer for java
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 53

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
M.HANUMANTHARAO ,KITS, GUNTUR Page 1
JAVA PROGRAMMING LAB MANUAL

1-b) Write a JAVA program that display the roots of quadratic equation ax2+bx+c=0.
import java.util.Scanner;
public class Quadratic_Equation
{
public static void main(String[] args)
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
double sq = Math.sqrt(b * b - 4 * a * c);
double root1 = (-b+sq)/(2*a); double
root2 = (-b-sq)/(2*a);
System.out.println("First root
is:"+root1); System.out.println("Second
root is:"+root2);
}
}

output:
javac Quadratic_Equation.java
java Quadratic_Equation 1 6 9
First root is:-3.0
Second root is:-3.0

1-c). Five Bikers Compete in a race such that they drive at a constant speed which may
or may not be the same as the other. To qualify the race, the speed of a racer must be
more than the average speed of all 5 racers. Take as input the speed of each racer and
print back the speed of qualifying racers.
import java.io.*;
import java.util.*;
class BikeRacers
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int speed[]=new int[5];
for(int i=0;i<5;i++)
{
System.out.print("\nEnter the speed of
Racer-"+i+": "); speed[i]=sc.nextInt();
}
int sum=0;
for(int i=0;i<5;i++)
sum+=speed[i];
double avg=sum/5;
M.HANUMANTHARAO ,KITS, GUNTUR Page 2
JAVA PROGRAMMING LAB MANUAL

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

1-d) Write a case study on public static void main (250 words)
Ans:
 public : is an Access Modifier, which defines who can access this Method. Public
means that this Method will be accessible by any Class (If other Classes are able to
access this Class.).
 static methods are the methods, which can be called and executed without creating
the objects. Since we want to call main() method without using an object, we should
declare main () method as static.
 void : is used to define the Return Type of the Method. It defines what the method can
return. Void means the Method will not return any value.
 main: is the name of the Method. This Method name is searched by JVM as a starting
point for an application with a particular signature only.
 String args[ ] : is the parameter to the main Method.

M.HANUMANTHARAO, KITS, GUNTUR Page 3


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) + ".");
else
System.out.println(search + " is not present
in the list.\n");
M.HANUMANTHARAO, KITS, GUNTUR Page 4
JAVA PROGRAMMING LAB MANUAL

}
}
output
:
java BinarySearch
Enter number of elements 5
Enter 5 integers 12 14 15 18 20
Enter value to find 15
15 found at location 3
2-b). Write a JAVA program to sort for an element in a given list of elements
using bubble sort
import java.util.Scanner;
class BubbleSort{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter No. of Elements: ");
int n=sc.nextInt();
int a[]=new int[n];
System.out.print("Enter "+n+" Elements:
"); for(int i=0;i<n;i++)
a[i]=sc.nextInt();
for(int i=0;i<n;i++)
{
for(int j=1;j<n-i;j++)
{
if(a[j]<a[j-1])
{
int t=a[j];
a[j]=a[j-1];
a[j-1]=t;
}
}
}
System.out.print("Array After Bubble Sort
is: "); for(int i=0;i<n;i++)
System.out.print(" "+a[i]);
}
}
Output
:
javac BubbleSort.java
java BubbleSort
Enter No. of Elements: 5
Enter 5 Elements: 9 8 7 6 5 4
Array After Bubble Sort is: 5 6 7 8 9
M.HANUMANTHARAO ,KITS, GUNTUR Page 5
JAVA PROGRAMMING LAB MANUAL

2-c). Write a JAVA program to sort for an element in a given list of elements
using merge sort.
import java.util.Scanner;
class MergeSort
{
void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
/ recursively
sort sort(a, low,
mid); sort(a, mid,
high);
/ merge two sorted
subarrays int[] temp = new
int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j+
+];
else if (j == high)
temp[k] = a[i+
+];
else if (a[j]<a[i])
temp[k] = a[j+
+];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k+
+) a[low + k] =
temp[k];
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter No. of Elements: ");
int n=sc.nextInt();
int a[]=new int[n];
System.out.print("Enter "+n+" Elements:
"); for(int i=0;i<n;i++)
a[i]=sc.nextInt();
MergeSort ms=new MergeSort();
ms.sort(a,0,n);
System.out.print("Array After Merge Sort
is: "); for(int i=0;i<n;i++)
M.HANUMANTHARAO ,KITS, GUNTUR Page 6
JAVA PROGRAMMING LAB MANUAL

System.out.print(" "+a[i]);
}
}
Output
:
javac MergeSort.java
java MergeSort
Enter No. of Elements: 10
Enter 10 Elements: 9 8 7 6 5 4 3 2 1 0
Array After Merge Sort is: 0 1 2 3 4 5 6 7 8 9

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

M.HANUMANTHARAO ,KITS, GUNTUR Page 7


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

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;
}

M.HANUMANTHARAO ,KITS, GUNTUR Page 8


JAVA PROGRAMMING LAB MANUAL

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

M.HANUMANTHARAO ,KITS, GUNTUR Page 9


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

M.HANUMANTHARAO ,KITS, GUNTUR Page 10


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

M.HANUMANTHARAO ,KITS, GUNTUR Page 11


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
b). Write a JAVA program to implement multi level Inheritance

class A
{
void showA()
{
System.out.println("Method A");
}
}
class B extends A
{
void showB()
{
System.out.println("Method B");
}
}
M.HANUMANTHARAO ,KITS, GUNTUR Page 12
JAVA PROGRAMMING LAB MANUAL

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

Output:
Method C
Method B
Method A

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

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);
}

M.HANUMANTHARAO ,KITS, GUNTUR Page 13


JAVA PROGRAMMING LAB MANUAL

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

M.HANUMANTHARAO ,KITS, GUNTUR Page 14


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

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();
}

M.HANUMANTHARAO ,KITS, GUNTUR Page 15


JAVA PROGRAMMING LAB MANUAL

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

M.HANUMANTHARAO ,KITS, GUNTUR Page 16


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 not possible");
}
finally{
System.out.println("LOGOUT");
}
}
}

Output:
WELCOME
Division with zero is not possible
LOGOUT

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);
}
M.HANUMANTHARAO ,KITS, GUNTUR Page 17
JAVA PROGRAMMING LAB MANUAL

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

Output-1: Output-2:
WELCOME WELCOM
E
Enter a value: 5 Enter a value: 5
Enter b value: k Enter b value: k
Wrong Input Division with zero is not possible
LOGOUT LOGOU
T

M.HANUMANTHARAO ,KITS, GUNTUR Page 18


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:
"+b1.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

M.HANUMANTHARAO ,KITS, GUNTUR Page 19


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

M.HANUMANTHARAO ,KITS, GUNTUR Page 20


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

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
M.HANUMANTHARAO ,KITS, GUNTUR Page 21
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

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 very
high");
throw me;
}

M.HANUMANTHARAO ,KITS, GUNTUR Page 22


JAVA PROGRAMMING LAB MANUAL

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

M.HANUMANTHARAO ,KITS, GUNTUR Page 23


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++)
{
try{

M.HANUMANTHARAO ,KITS, GUNTUR Page 24


JAVA PROGRAMMING LAB MANUAL

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
Welcome
Hello
M.HANUMANTHARAO ,KITS, GUNTUR Page 25
JAVA PROGRAMMING LAB MANUAL

Welcome
Hello
Hello
Welcome
Welcome
Welcome
Welcome

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

M.HANUMANTHARAO ,KITS, GUNTUR Page 26


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
M.HANUMANTHARAO ,KITS, GUNTUR Page 27
JAVA PROGRAMMING LAB MANUAL

EXCERCISE-11
11-a).Write a JAVA program Producer Consumer Problem
import java.util.*;
class Producer extends Thread
{
StringBuffer sb=new StringBuffer();
public void run()
{
synchronized(sb)
{
for(int i=1;i<=10;i++)
{
sb.append(i+" : ");
System.out.println("Appending
"); try{
Thread.sleep(100);
}
catch(InterruptedException ie)
{ }
}
sb.notify();
}
}
}
class Consumer extends Thread
{
Producer prod;
Consumer(Producer prod)
{
this.prod=prod;
}
public void run()
{
synchronized(prod.sb)
{
try{
prod.sb.wait();
}
catch(Exception e)
{ }

M.HANUMANTHARAO ,KITS, GUNTUR Page 28


JAVA PROGRAMMING LAB MANUAL

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 :

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

M.HANUMANTHARAO ,KITS, GUNTUR Page 29


JAVA PROGRAMMING LAB MANUAL

EXCERCISE-12
12-a) Write a case study on including in class path in your os environment
of your package.
Setting CLASSPATH:
The CLASSPATH is an environment variable that tells the Java compiler where to
look for class files to import. CLASSPATH is generally set to a directory or a JAR (Java
Archive) file.
 To see what is there in currently in CLASSPATH variable in your system. You can type the
command in windows.
echo %CLASSPATH%
 Suppose, preceding command has disp1ayed class path as:
C:\rnr;.
 This means the current class path is set to rnr directory in C: \ and also to the current
directory represented by dot (.). Our package pack does not exist in either rnr or current
directory. Our package exists in D:\sub, as:
set CLASSPATH=D:\sub;.;%CLASSPATH%

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

package pack;
public class Addition
{
public void add(int a,int b)
{
int c=a+b;
System.out.println("The sum is "+c);
}
}
 To compile the program by using following command,
javac -d . Addition.java

 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

M.HANUMANTHARAO ,KITS, GUNTUR Page 30


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

M.HANUMANTHARAO ,KITS, GUNTUR Page 31


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;
}

public void run()


{
try
{
M.HANUMANTHARAO ,KITS, GUNTUR Page 32
JAVA PROGRAMMING LAB MANUAL

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 );
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 );
}
M.HANUMANTHARAO ,KITS, GUNTUR Page 33
JAVA PROGRAMMING LAB MANUAL

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:

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:

M.HANUMANTHARAO ,KITS, GUNTUR Page 34


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:

M.HANUMANTHARAO ,KITS, GUNTUR Page 35


JAVA PROGRAMMING LAB MANUAL

14-b)Write a JAVA program that identifies key-up key-down event user entering
text in a Applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Key extends Applet implements
KeyListener {
int X=20,Y=30;
String msg="";
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent k)
{
showStatus("Key Pressed");
msg="Key Pressed";
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
msg="Key Up";
repaint();
}
public void keyTyped(KeyEvent k)
{
showStatus("Key Typed");
msg="Key Typed";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Output:

M.HANUMANTHARAO ,KITS, GUNTUR Page 36


JAVA PROGRAMMING LAB MANUAL

EXCERCISE-15
15-a) Write a JAVA program to build a Calculator in Swings
import javax.swing.*;
import java.awt.event.*;
class Calc implements
ActionListener {
JFrame f;
JTextField t;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
JButton bdiv,bmul,bsub,badd,bdec,beq,bdel,bclr;

static double a=0,b=0,result=0;


static int operator=0;

Calc()
{
f=new JFrame("Calculator");
t=new JTextField();
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b0=new JButton("0");
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
bdec=new JButton(".");
beq=new JButton("=");

bdel=new JButton("\u21d0"); //
bclr=new JButton("C");

t.setBounds(30,40,280,30);
b7.setBounds(40,100,50,40);
b8.setBounds(110,100,50,40);
b9.setBounds(180,100,50,40);
bdiv.setBounds(250,100,50,40);

b4.setBounds(40,170,50,40);
b5.setBounds(110,170,50,40);
b6.setBounds(180,170,50,40);
bmul.setBounds(250,170,50,40);

b1.setBounds(40,240,50,40);
b2.setBounds(110,240,50,40);
M.HANUMANTHARAO ,KITS, GUNTUR Page 37
JAVA PROGRAMMING LAB MANUAL

b3.setBounds(180,240,50,40);
bsub.setBounds(250,240,50,40);

bdec.setBounds(40,310,50,40);
b0.setBounds(110,310,50,40);
beq.setBounds(180,310,50,40);
badd.setBounds(250,310,50,40);

bdel.setBounds(60,380,80,40);
bclr.setBounds(180,380,50,40);

f.add(t);
f.add(b7);
f.add(b8);
f.add(b9);
f.add(bdiv);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(bmul);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(bsub);
f.add(bdec);
f.add(b0);
f.add(beq);
f.add(badd);
f.add(bdel);
f.add(bclr);

f.setLayout(null);
f.setVisible(true);
f.setSize(350,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
badd.addActionListener(this);
bdiv.addActionListener(this);
bmul.addActionListener(this);

M.HANUMANTHARAO ,KITS, GUNTUR Page 38


JAVA PROGRAMMING LAB MANUAL

bsub.addActionListener(this);
bdec.addActionListener(this);
beq.addActionListener(this);
bdel.addActionListener(this);
bclr.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==b1)
t.setText(t.getText().concat("1")
);
if(e.getSource()==b2)
t.setText(t.getText().concat("2")
);
if(e.getSource()==b3)
t.setText(t.getText().concat("3")
);
if(e.getSource()==b4)
t.setText(t.getText().concat("4")
);
if(e.getSource()==b5)
t.setText(t.getText().concat("5")
);
if(e.getSource()==b6)
t.setText(t.getText().concat("6")
);
if(e.getSource()==b7)
t.setText(t.getText().concat("7")
);
if(e.getSource()==b8)
t.setText(t.getText().concat("8")
);
if(e.getSource()==b9)
t.setText(t.getText().concat("9")
);
if(e.getSource()==b0)
t.setText(t.getText().concat("0")
);
if(e.getSource()==bdec)
t.setText(t.getText().concat(".")
);
if(e.getSource()==badd)
{
a=Double.parseDouble(t.getText());
operator=1;
t.setText("");
}
if(e.getSource()==bsub)
{
a=Double.parseDouble(t.getText());
operator=2;
t.setText("");
}
if(e.getSource()==bmul)
{
a=Double.parseDouble(t.getText());
operator=3;
t.setText("");
}
if(e.getSource()==bdiv)

M.HANUMANTHARAO ,KITS, GUNTUR Page 39


JAVA PROGRAMMING LAB MANUAL

{
a=Double.parseDouble(t.getText());
operator=4;
t.setText("");
}
if(e.getSource()==beq)
{
b=Double.parseDouble(t.getText());
switch(operator)
{
case 1: result=a+b; break;
case 2: result=a-b; break;
case 3: result=a*b; break;
case 4: result=a/b; break;
default: result=0;
}
t.setText(""+result);
}
if(e.getSource()==bclr)
t.setText("");
if(e.getSource()==bdel)
{
String s=t.getText();
t.setText("");
for(int i=0;i<s.length()-1;i++)
t.setText(t.getText()
+s.charAt(i));
}
}
public static void main(String...s)
{
new Calc();
}
}

Output:

M.HANUMANTHARAO ,KITS, GUNTUR Page 40


JAVA PROGRAMMING LAB MANUAL

15-b) Write a JAVA program to display the digital watch in swing tutorial.
import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.util.*;
public class DigitalWatch implements
Runnable {
JFrame f;
Thread t=null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
JButton b;
DigitalWatch()
{
f=new JFrame();

t = new Thread(this);
t.start();

b=new JButton();
b.setBounds(100,100,100,50);

f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
}
public void run()
{
try{
while (true)
{
Calendar cal = Calendar.getInstance();
hours =
cal.get( Calendar.HOUR_OF_DAY ); if
( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );

SimpleDateFormat form = new


SimpleDateFormat("hh:mm:ss"); Date date =
cal.getTime();
timeString = form.format( date );

b.setText(timeString);

t.sleep( 1000 );
}
}
catch (Exception e) { }
}
public static void main(String[] args)
{
new DigitalWatch();
}
}

M.HANUMANTHARAO ,KITS, GUNTUR Page 41


JAVA PROGRAMMING LAB MANUAL

M.HANUMANTHARAO ,KITS, GUNTUR Page 42


JAVA PROGRAMMING LAB MANUAL

EXERCISE – 16 (SWINGS - CONTINUED)


16-a) Write a JAVA program that to create a single ball bouncing inside a JPanel.
import java.awt.*;
import javax.swing.*;
public class BouncingBall extends JPanel
{
int width;
int height;
float radius = 40;
float diameter = radius * 2;
float X = radius + 50;
float Y = radius + 20;
float dx = 3;
float dy = 3;

public BouncingBall()
{
Thread thread = new Thread() {
public void run() {
while (true) {

width = getWidth();
height = getHeight();

X = X + dx ;
Y = Y + dy;

if (X - radius < 0) {
dx = -dx;
X = radius;
} else if (X + radius > width) {
dx = -dx;
X = width - radius;
}

if (Y - radius < 0) {
dy = -dy;
Y = radius;
} else if (Y + radius > height) {
dy = -dy;
Y = height - radius;
}
repaint();

try {
Thread.sleep(50);
} catch (InterruptedException ex) {
}

}
M.HANUMANTHARAO ,KITS, GUNTUR Page 43
JAVA PROGRAMMING LAB MANUAL

}
};
thread.start();
}

public void paintComponent(Graphics


g) { super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval((int)(X-radius), (int)(Y-radius),
(int)diameter, (int)diameter);
}

public static void main(String[] args) {


JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Bouncing Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setContentPane(new BouncingBall());
frame.setVisible(true);
}
}
Output:

16-b) Write a JAVA program JTree as displaying a real tree upside down
import javax.swing.*;
import javax.swing.tree.*;

public class TreeComponent


{
public static void main(String[] args)
{
JFrame frame = new JFrame("Creating a JTree Component!");
DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Color",
true);
DefaultMutableTreeNode black = new DefaultMutableTreeNode("Black");
DefaultMutableTreeNode blue = new DefaultMutableTreeNode("Blue");
DefaultMutableTreeNode nBlue = new DefaultMutableTreeNode("Navy
Blue");
DefaultMutableTreeNode dBlue = new DefaultMutableTreeNode("Dark
Blue");
DefaultMutableTreeNode green = new DefaultMutableTreeNode("Green");
DefaultMutableTreeNode white = new DefaultMutableTreeNode("White");
parent.add(black);
parent.add(blue);
blue.add(nBlue);
blue.add(dBlue);
parent.add(green );
parent.add(white);
JTree tree = new JTree(parent);
frame.add(tree);
M.HANUMANTHARAO ,KITS, GUNTUR Page 44
JAVA PROGRAMMING LAB MANUAL
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setSize(200,200);
frame.setVisible(true);
}
}

Output:

M.HANUMANTHARAO ,KITS, GUNTUR Page 45

You might also like