r20 Java Lab Manual Word Final
r20 Java Lab Manual Word Final
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
);
output:
javac
DefaultValues.java
java DefaultValues
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0
Char :
Boolean :fal
se String:
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:-
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+
+)
SAI TIRUMALA NVR ENGINEERING COLLEGE Page 2
JAVA PROGRAMMING LAB MANUAL
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.
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");
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;
}
Page 4
JAVA PROGRAMMING LAB MANUAL
if (status=true)
System.out.println(search + " found at
location " + (middle + 1) + ".");
else
System.out.println(search + " is not present
in the list.\n");
Page 5
JAVA PROGRAMMING LAB MANUAL
}
}
output:
java BinarySearch
Enter number of elements 5 Enter 5 integers 12 14 15 18 20 Enter val
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
Output:
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++];
}
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
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
);
}
}
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
;
Output:
Hello my name is
Raju And my age is
22
class Person
{
String
name; int
age;
Person()
{
name="Raju
"; age=22;
}
Person(String s, int i)
{
name=s
SAI TIRUMALA NVR ENGINEERING COLLEGE Page 10
age=i;
}
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.hashCo
de()); p2.talk();
}
}
Output:
p1 hashcode
705927765 My Name
is Raju
My Age is 22
p2 hashcode
705934457 My Name
is Sita
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
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
EXERCISE – 5
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
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
}
class AreaShape extends Shape
{
void findCircle(double r)
{
double a=3.14*r*r;
System.out.println("Area of Circle
= "+a);
}
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:
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();
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
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 not
possible");
}
finally{
System.out.println("LOGOUT");
}
}
}
Output:
WELCOME
Division with zero is not
possible LOGOUT
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 not
possible");
}
finally{
System.out.println("LOGOUT");
}
}
}
Output-1: Output-2:
WELCOME WELCOME
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 LOGOUT
EXERCISE – 8
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());
}
}
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).
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
Output:
Inside 1st catch Block
Inside 1st finally block
SAI TIRUMALA NVR ENGINEERING Page 23
COLLEGE
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
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("WEL
COME");
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;
}
Output-1:
WELCOME
Enter amount to withdraw: 26000
MyException: Balance is very high
Output-2:
WELCOME
Enter amount to withdraw: 15000
Balance is withdrawn
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:
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();
Output: t2.start();
GoodMorning
Hello
GoodMorning
Welcome
GoodMorning
Hello
GoodMorning
GoodMorning
Welcome
Hello
GoodMorning
GoodMorning
Hello
GoodMorning
Welcome
GoodMorning
Hello
GoodMorning
Welcome
Hello
Hello
Welcome
Hello
Welcome
Hello
Hello
Welcome
Welcome
Welcome
Welcome
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:
tru
e
r1
r1
tru
e
r2
t1.setDaemon(true);
t1.start();
t2.start();
t3.start();
}
}
Output:
daemon thread work
user thread work
user thread work
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)
{ }
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.
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
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(thi
s);
setBackground(Color.white)
;
}
public void mouseDragged(MouseEvent me)
{
Graphics g=getGraphics();
g.setColor(Color.red);
g.fillOval(me.getX(),me.getY(),5,
javac Painting.java
<html>
<applet code="Painting.class" width=700 height=500 >
</applet>
</html>
appletviewer Painting.html
if ( threadSuspended ) {
synchronized( this ) {
while
( threadSuspended ) {
wait();
}
}
}
repaint();
t.sleep( 1000 );
}
}
catch (Exception e) { }
}
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,1
0);
g.drawOval(230,10,200,15
0);
g.setColor(Color.blue);
g.fillOval(245,25,100,10
Output:
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);
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);
SAI TIRUMALA NVR ENGINEERING Page 39
COLLEGE
JAVA PROGRAMMING LAB MANUAL
Output: