Java Lab Manual For Cse r20
Java Lab Manual For Cse r20
Exercise - 1 (Basics)
a). Write a JAVA program to display default value of all primitive data
type of JAVA
AIM:
JAVA program to display default value of all primitive data type of JAVA
PROGRAM:
class DefaultValues
{
static byte b;
static short s;
static int i;
static long l;
static float f;
static double d;
static char c;
static boolean bl;
public static void main(String[] args)
{
[Link]("Byte :"+b);
[Link]("Short :"+s);
[Link]("Int :"+i);
[Link]("Long :"+l);
[Link]("Float :"+f);
[Link]("Double :"+d);
[Link]("Char :"+c);
[Link]("Boolean :"+bl);
}
}
Output:
D:\GSK\JAVA>javac [Link] D:\GSK\
JAVA>java DefaultValues
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0
Char:
Boolean: false
b). Write a java program that display the roots of a quadratic equation
ax2+bx+c=0. Calculate the discriminate D and basing on value of D, describe
the nature of root.
AIM: Java program that display the roots of a quadratic equation ax2+bx+c=0 and
Calculating the discriminate D basing on value of D and describing the nature of
root.
PROGRAM:
import [Link];
class Solutions
{
public static void main(String[] args)
{
int a,b,c;
double x,y;
Scanner s=new Scanner([Link]);
[Link](“Enter the values of a,b, and c”);
a=[Link]();
b=[Link]();
c=[Link]();
int d=(b*b)-4*a*c;
if(d<0)
{
[Link](“No real roots”);
}
else
{
double l=[Link](d);
x=(-b-l)/2*a;
y=(-b+l)/2*a;
[Link](“Roots of given equation:”+x+” “+y);
}
}
}
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java Solutions
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java Solutions
AIM:
Java Program for 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 and to qualify the race, the
speed of a racer must be more than the average speed of all 5 racers. Take as input
the speed of each racer and print back the speed of qualifying racers.
PROGRAM:
import [Link];
public class Racer
{
public static void main(String[] args)
{
float r1,r2,r3,r4,r5;
float average;
Scanner s = new Scanner([Link]);
[Link]("Enter First Racer
Speed:"); r1 = [Link]();
[Link]("Enter Second Racer
Speed:"); r2 = [Link]();
[Link]("Enter Third Racer
Speed:"); r3 = [Link]();
[Link]("Enter Fourth Racer
Speed:"); r4 = [Link]();
[Link]("Enter Fifth Racer
Speed:"); r5 = [Link]();
average = (r1+r2+r3+r4+r5) / 5;
[Link]("Average:"+average);
if(r1 > average)
[Link]("\n First Racer is qualify Racer Speed is:"+r1);
if(r2 > average)
[Link]("\n Second Racer is qualify Racer Speed is:"+r2);
if(r3 > average)
[Link]("\n Third Racer is qualify Racer Speed is:"+r3);
if(r4 > average)
[Link]("\n Fourth Racer is qualify Racer Speed
is:"+r4); if(r5 > average)
[Link]("\n Fifth Racer is qualify Racer Speed is:"+r5);
}
}
Output:
D:\GSK\JAVA>javac
[Link] D:\GSK\JAVA>java
Speed:45
Enter Second Racer Speed:55
Enter Third Racer Speed:60
Enter Fourth Racer Speed:65
Enter Fifth Racer Speed:70
Average:59.0
import [Link];
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java BinarySearch
Enter number of elements
5
Enter 5 integers
2
5
8
10
15
Enter value to find
8
8 found at location 3.
b). Write a JAVA program to sort for an element in a given list of
elements using bubble sort
import [Link];
class BubbleSort {
public static void main(String []args)
{ int n, i, j, swap;
Scanner in = new Scanner([Link]);
D:\GSK\JAVA>java BubbleSort
Input number of integers to sort
5
Enter 5 integers
5
4
3
2
1
Sorted list of numbers
1
2
3
4
5
(c). Write a JAVA program to sort for an element in a given list of elements
using merge sort.
import [Link];
public class MergeSort
{
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
sort(a, low, mid);
sort(a, mid, high);
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];
}
}
}
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java MergeSort
Merge Sort Test
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java JavaStringBufferDeleteExample
World
Some Content
ello World
Exercise - 3 (Class, Objects)
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java Helloworld
Hello
World
b). Write a JAVA program to implement constructor.
class Programming
{
Programming()
{
[Link]("Constructor method called.");
}
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java Programming
class Square
{
int height;
int width;
Square()
{
height = 0;
width = 0;
}
Square(int side)
{
height = width = side;
}
class ImplSquare
{
public static void main(String args[])
{
Square sObj1 = new Square();
Square sObj2 = new Square(5);
Square sObj3 = new Square(2,3);
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java ImplSquare
Variable values of object1 :
Object1 height = 0
Object1 width = 0
class Sum
{
void add(int a, int b)
{
[Link]("Sum of two="+(a+b));
}
[Link](10,15);
[Link](10,20,30);
}
}
Output:
JAVA>java Polymorphism
Sum of two=25
Sum of three=60
Exercise - 5 (Inheritance)
class Dimensions
{
int length;
int breadth;
}
class Area
{
public static void main(String args[])
{
Rectangle Rect = new Rectangle();
[Link] = 7;
[Link] = 16;
[Link]();
[Link]("The Area of rectangle of length "
+[Link]+" and breadth "+[Link]+" is "+Rect.a);
}
}
Output:
JAVA>java Area
class students
{
private int sno;
private String sname;
public void setstud(int no,String name)
{
sno = no;
sname = name;
}
public void putstud()
{
[Link]("Student No : " + sno);
[Link]("Student Name : " + sname);
}
}
class marks extends students
{
protected int mark1,mark2;
public void setmarks(int m1,int m2)
{
mark1 = m1;
mark2 = m2;
}
public void putmarks()
{
[Link]("Mark1 : " + mark1);
[Link]("Mark2 : " + mark2);
}
}
class finaltot extends marks
{
private int total;
public void calc()
{
total = mark1 + mark2;
}
public void puttotal()
{
[Link]("Total : " + total);
}
public static void main(String args[])
{
finaltot f = new finaltot();
[Link](100,"Nithya");
[Link](78,89);
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java finaltot
Student No : 100
Mark1 : 78
Mark2 : 89
Total : 167
c). Write a java program for abstract class to find areas of different shapes
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java AbstractClassDemo
class SuperExample {
int a = 10;
}
{ void display() {
int a = super.a;
[Link]("The value is : " + a);
}
}
class MainClass {
Output:
GSK\JAVA>java MainClass
The value is : 10
b). Write a JAVA program to implement Interface. What kind of
Inheritance can be achieved?
import [Link].*;
import [Link].*;
interface Exam
{
void percent_cal();
}
class Student
{
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2)
{
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
}
void display()
{
[Link] ("Name of Student: "+name);
[Link] ("Roll No. of Student: "+roll_no);
[Link] ("Marks of Subject 1: "+mark1);
[Link] ("Marks of Subject 2: "+mark2);
}
}
class Result extends Student implements Exam
{
Result(String n, int r, int m1, int m2)
{
super(n,r,m1,m2);
}
public void percent_cal()
{
int total=(mark1+mark2);
float percent=total*100/200;
[Link] ("Percentage: "+percent+"%");
}
void display()
{
[Link]();
}
}
class Multiple
{
public static void main(String args[])
{
Result R = new Result("[Link]",12,93,84);
[Link]();
R.percent_cal();
}
}
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java Multiple
Marks of Subject 1: 93
Marks of Subject 2: 84
Percentage: 88.0%
import [Link];
class Division {
public static void main(String[] args) {
int a, b, result;
Scanner input = new
Scanner([Link]);
[Link]("Input two integers");
a = [Link]();
b = [Link]();
try {
result = a / b;
[Link]("Result = " +
result);
}
catch (ArithmeticException e)
{ [Link]("Exception caught: Division by
zero.");
}
finally {
[Link]("finally block will execute always.");
}
}
}
Output:
JAVA>java Division
Input two integers
4
5
Result = 0
finally block will execute always.
D:\GSK\JAVA>java Division
Input two integers
5
0
Exception caught: Division by zero.
finally block will execute always.
b).Write a JAVA program Illustrating Multiple catch clauses
}catch (ArithmeticException e) {
[Link]("Err: Divided by Zero");
}catch (ArrayIndexOutOfBoundsException e) {
[Link]("Err: Array Out of Bound");
}
}
}
Output:
GSK\JAVA>java ExceptionExample
class Shape
{
void draw()
{
[Link]("drawing...");
}
}
class Rectangle extends Shape
{
void draw()
{
[Link]("drawing rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
[Link]("drawing circle...");
}
}
class Triangle extends Shape
{
void draw()
{
[Link]("drawing triangle...");
}
}
class TestPolymorphism
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
[Link]();
s=new Circle();
[Link]();
s=new Triangle();
[Link]();
}
}
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java TestPolymorphism
drawing rectangle...
drawing circle...
drawing triangle...
b). Write a Case study on run time polymorphism, inheritance
that implements in above problem
Polymorphism in Java
There are two types of polymorphism in java: compile time polymorphism and
runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is
known as upcasting. For example:
class A
class B extends A
A a=new B();//upcasting
In the above example, we are creating three classes Rectangle, Circle and Triangle.
Rectangle class extends Shape class and overrides its draw() method, Circle class
extends Shape class and overrides its draw() method and Triangle class extends
Shape class and overrides its draw() method . We are calling the draw() method by
the reference variable of Parent class. Since it refers to the subclass object and
subclass method overrides the Parent class method, subclass method is invoked at
runtime.
class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
[Link]("Exception caught");
}
}
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java Test
Exception caught
b). Write a JAVA program for creation of Illustrating finally
class ExceptionTest
{
public static void main(String[] args)
{
int a[]= new int[2];
[Link]("out of try");
try
{
[Link]("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
[Link]("finally is always executed.");
}
}
}
Output:
JAVA>java ExceptionTest
out of try
finally is always executed.
Exception in thread "main" [Link]: Index 3
out of bounds for length 2 at [Link]([Link])
c). Write a JAVA program for creation of Java Built-in Exceptions
class Exception_Demo {
try
int a = 30, b = 0;
catch (ArithmeticException e)
try
// size 5
catch (ArrayIndexOutOfBoundsException e)
try
[Link]([Link](0));
catch (NullPointerException e)
[Link]("\t NullPointerException..");
try
[Link](num);
catch (NumberFormatException e)
}
Output:
GSK\JAVA>java Exception_Demo
ArithmeticException Demo
ArrayIndexOutOfBoundsException Demo
NullPointerException Demo
NullPointerException..
NumberFormatException Demo
MyException(String str2)
{ str1=str2;
class UserException{
catch(MyException exp)
{ [Link]("Catch Block") ;
[Link](exp) ;
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java UserException
Catch Block
try
{
[Link](1);
}
catch (InterruptedException ie)
{
try
{
[Link] (2);
}
catch (InterruptedException ie)
{
try
{
[Link] (3);
}
catch (InterruptedException ie)
{
new ThirdThread();
[Link]();
[Link]();
[Link]();
}
}
Output:
JAVA>java ThreadDemo
HELLO
WELCOME
GOOD MORNING
try
{
[Link](1);
}
catch (InterruptedException ie)
{
try
{
[Link] (3);
}
catch (InterruptedException ie)
{
Output:
JAVA>java ThreadDemo1
HELLO
GOOD MORNING
WELCOME
b). Write a program illustrating isAlive and join ()
}
}
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java ThreadExample
true
Thread
Example using isAlive() and join()
false
c). Write a Program illustrating Daemon Threads.
[Link](true);
[Link]();
[Link]();
[Link]();
}
}
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java DaemonThread
Daemon Thread Works
user Thread Works
user Thread Works
Exercise - 11 (Threads continuity)
class ProducerConsumerTest {
[Link]();
[Link]();
class CubbyHole
{ private int
contents;
try {
wait();
} catch (InterruptedException e) {}
available = false;
notifyAll();
return contents;
}
try {
wait();
} catch (InterruptedException e) { }
contents = value;
available = true;
notifyAll();
{ cubbyhole = c;
[Link] = number;
{ int value = 0;
{ value =
[Link]();
}
}
private CubbyHole
number;
{ cubbyhole = c;
[Link] = number;
{ [Link](i);
try {
sleep((int)([Link]() * 100));
} catch (InterruptedException e) { }
Output:
D:\GSK\JAVA>javac [Link]
D:\GSK\JAVA>java ProducerConsumerTest
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
The producer’s job is to generate data, put it into the buffer, and start again.
At the same time, the consumer is consuming the data (i.e. removing it from
the buffer), one piece at a time.
Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and
that the consumer won’t try to remove data from an empty buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full. The next
time the consumer removes an item from the buffer, it notifies the producer, who
starts to fill the buffer again. In the same way, the consumer can go to sleep if it
finds the buffer to be empty. The next time the producer puts data into the buffer, it
wakes up the sleeping consumer.
An inadequate solution could result in a deadlock where both processes are waiting
to be awakened.
Exercise – 12 (Packages)
a). Write a JAVA program illustrate class path
//save as [Link]
package mypack;
{ [Link]("Welcome to package");
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . [Link]
The -d switch specifies the destination where to put the generated class file. You
can use any directory name like /home (in case of Linux), d:/abc (in case of
windows) etc. If you want to keep the package within the same directory, you can
use . (dot).
You need to use fully qualified name e.g. [Link] etc to run the class.
Welcome to package
What is Classpath?
Classpath is system environment variable used by the Java compiler and JVM.
Java compiler and JVM is used Classpath to determine the location of
required class files.
C:\Program Files\Java\jdk1.6.0\bin
In order to set Classpath for Java in Windows (any version either Windows
XP, Windows 2000 or Windows 7) you need to specify the value of environment
variable CLASSPATH, the name of this variable is not case sensitive and it
doesn’t matter if the name of your environment variable is Classpath,
CLASSPATH or classpath in Java.
c). Write a JAVA program that import and use the defined your package
in the previous Problem
//save by [Link]
package pack;
public class A{
//save by [Link]
package mypack;
import pack.A;
class B{
[Link]();
}
}
Output:
Hello
Exercise - 13 (Applet)
a) Write a JAVA program to paint like paint brush in applet.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code=”[Link]” width=500, height=500>
</applet>
*/
public class Paint extends Applet implements MouseMotionListener {
addMouseMotionListener( this );
}
public void mouseMoved( MouseEvent e ) {
} public void mouseDragged( MouseEvent e )
{ int x = [Link]();
int y = [Link]();
[Link](x-10,y-10,20,20);
repaint();
[Link]();
}
public void update( Graphics g )
{ [Link]( backbuffer, 0, 0, this );
}
public void paint( Graphics g )
{ update( g );
}
}
0utput:
b) Write a JAVA program to display analog clock using Applet.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
/*
*/
Thread t = null;
boolean threadSuspended;
{ width =
getSize().width;
height = getSize().height;
setBackground( [Link] );
{ if ( t == null ) {
threadSuspended = false;
[Link]();
else {
if ( threadSuspended )
{ threadSuspended = false;
synchronized( this ) {
notify();
{ threadSuspended = true;
{ try {
while (true) {
if ( threadSuspended ) {
synchronized( this ) {
while ( threadSuspended )
{ wait();
repaint();
catch (Exception e) { }
}
void drawWedge( double angle, int radius, Graphics g )
); angle += 2*[Link]/3;
angle += 2*[Link]/3;
{ [Link]( [Link] );
[Link]( [Link] );
}
Output:
import [Link].*;
import [Link].*;
/*
</applet>
*/
int x[]={10,220,220};
int y[]={400,400,520};
int n=3;
[Link](10,30,200,30);
[Link]([Link]);
[Link](10,40,200,30);
[Link]([Link]);
[Link](10,80,200,30);
[Link]([Link]);
[Link](10,120,200,30,20,20);
[Link]([Link]);
[Link](10,160,200,30,20,20);
[Link]([Link]);
[Link](10,200,200,30);
[Link]([Link]);
[Link](10,240,40,40);
[Link]([Link]);
[Link](10,290,200,30,0,180);
[Link]([Link]);
[Link](10,330,200,30,0,180);
[Link]([Link]);
[Link](x,y,n);
}
Exercise - 14 (Event Handling)
a).Write a JAVA program that display the x and y position of the cursor
movement using Mouse.
import [Link].*;
import [Link].*;
import [Link];
/*
<applet code="AppletMouseXY" width=300 height=300>
</applet>
*/
import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code="SimpleKey" width=300 height=100>
</applet> */
public class SimpleKey extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output
coordinates public void init() {
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke)
{ showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{ showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{ msg += [Link]();
repaint();
} // Display keystrokes.
public void paint(Graphics g) {
[Link](msg, X, Y);
} }
Output: