Java Lab Manual 2-1 R20
Java Lab Manual 2-1 R20
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[])
{
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");
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;
Page 8
JAVA PROGRAMMING LAB MANUAL
for(int i=0;i<n;i++)
System.out.print(" "+a[i]);
}
}
Output:
javac MergeSort.java
java MergeSort
Page 9
JAVA PROGRAMMING LAB MANUAL
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:
Page 11
JAVA PROGRAMMING LAB MANUAL
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:
Page 13
JAVA PROGRAMMING LAB MANUAL
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
class SuperClass
{
void add(int a,int b)
{
int c=a+b;
System.out.println("Addition is "+c);
}
}
class Demo{
Output:
Addition is 11
Subtraction is 5
Addition is 42
Page 15
JAVA PROGRAMMING LAB MANUAL
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
}
class AreaShape extends Shape
{
void findCircle(double r)
{
double a=3.14*r*r;
System.out.println("Area of Circle = "+a);
}
Output:
Page 17
JAVA PROGRAMMING LAB MANUAL
EXERCISE – 6
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:
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:
Page 19
JAVA PROGRAMMING LAB MANUAL
EXERCISE – 7
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
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:
Page 22
JAVA PROGRAMMING LAB MANUAL
b). Write a Case study on run time polymorphism, inheritance that implements in
above problem
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
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
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
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:
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)
{
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
t1.setDaemon(true);
t1.start();
t2.start();
t3.start();
}
}
Output:
Page 32
JAVA PROGRAMMING LAB MANUAL
EXCERCISE-11
11-a).Write a JAVA program Producer Consumer Problem
import java.util.*;
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.
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%
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;
import pack.Addition;class
DemoPack
{
public static void main(String[] args)
{
Addition a1=new Addition();
a1.add(15,27);
}
}
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.*;
javac Painting.java
<html>
<applet code="Painting.class" width=700 height=500 >
</applet>
</html>
appletviewer Painting.html
Output:
Page 38
JAVA PROGRAMMING LAB MANUAL
Page 39
JAVA PROGRAMMING LAB MANUAL
if ( threadSuspended ) {
synchronized( this ) {
while ( threadSuspended ) {
wait();
}
}
}
repaint();
t.sleep( 1000 );
}
}
catch (Exception e) { }
}
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 );
}
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.*;
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
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