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)
{
System.out.println("Byte :"+b);
System.out.println("Short :"+s);
System.out.println("Int :"+i);
System.out.println("Long :"+l);
System.out.println("Float :"+f);
System.out.println("Double :"+d);
System.out.println("Char :"+c);
System.out.println("Boolean :"+bl);
}
}
Output:
D:\GSK\JAVA>javac DefaultValues.java 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 java.util.Scanner;
class Solutions
{
public static void main(String[] args)
{
int a,b,c;
double x,y;
Scanner s=new Scanner(System.in);
System.out.println(“Enter the values of a,b, and c”);
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
int d=(b*b)-4*a*c;
if(d<0)
{
System.out.println(“No real roots”);
}
else
{
double l=Math.sqrt(d);
x=(-b-l)/2*a;
y=(-b+l)/2*a;
System.out.println(“Roots of given equation:”+x+” “+y);
}
}
}
Output:
D:\GSK\JAVA>javac Solutions.java
D:\GSK\JAVA>java Solutions
Output:
D:\GSK\JAVA>javac Solutions.java
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 java.util.Scanner;
public class Racer
{
public static void main(String[] args)
{
float r1,r2,r3,r4,r5;
float average;
Scanner s = new Scanner(System.in);
System.out.print("Enter First Racer
Speed:"); r1 = s.nextFloat();
System.out.print("Enter Second Racer
Speed:"); r2 = s.nextFloat();
System.out.print("Enter Third Racer
Speed:"); r3 = s.nextFloat();
System.out.print("Enter Fourth Racer
Speed:"); r4 = s.nextFloat();
System.out.print("Enter Fifth Racer
Speed:"); r5 = s.nextFloat();
average = (r1+r2+r3+r4+r5) / 5;
System.out.println("Average:"+average);
if(r1 > average)
System.out.println("\n First Racer is qualify Racer Speed is:"+r1);
if(r2 > average)
System.out.println("\n Second Racer is qualify Racer Speed is:"+r2);
if(r3 > average)
System.out.println("\n Third Racer is qualify Racer Speed is:"+r3);
if(r4 > average)
System.out.println("\n Fourth Racer is qualify Racer Speed
is:"+r4); if(r5 > average)
System.out.println("\n Fifth Racer is qualify Racer Speed is:"+r5);
}
}
Output:
D:\GSK\JAVA>javac
Racer.java 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 java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
D:\GSK\JAVA>javac BinarySearch.java
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 java.util.Scanner;
class BubbleSort {
public static void main(String []args)
{ int n, i, j, swap;
Scanner in = new Scanner(System.in);
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 java.util.Scanner;
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 MergeSort.java
D:\GSK\JAVA>java MergeSort
Merge Sort Test
Output:
D:\GSK\JAVA>javac JavaStringBufferDeleteExample.java
D:\GSK\JAVA>java JavaStringBufferDeleteExample
World
Some Content
ello World
Exercise - 3 (Class, Objects)
Output:
D:\GSK\JAVA>javac Helloworld.java
D:\GSK\JAVA>java Helloworld
Hello
World
b). Write a JAVA program to implement constructor.
class Programming
{
Programming()
{
System.out.println("Constructor method called.");
}
Output:
D:\GSK\JAVA>javac Programming.java
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 ImplSquare.java
D:\GSK\JAVA>java ImplSquare
Variable values of object1 :
Object1 height = 0
Object1 width = 0
class Sum
{
void add(int a, int b)
{
System.out.println("Sum of two="+(a+b));
}
s.add(10,15);
s.add(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();
Rect.length = 7;
Rect.breadth = 16;
Rect.area();
System.out.println("The Area of rectangle of length "
+Rect.length+" and breadth "+Rect.breadth+" 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()
{
System.out.println("Student No : " + sno);
System.out.println("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()
{
System.out.println("Mark1 : " + mark1);
System.out.println("Mark2 : " + mark2);
}
}
class finaltot extends marks
{
private int total;
public void calc()
{
total = mark1 + mark2;
}
public void puttotal()
{
System.out.println("Total : " + total);
}
public static void main(String args[])
{
finaltot f = new finaltot();
f.setstud(100,"Nithya");
f.setmarks(78,89);
f.calc();
f.putstud();
f.putmarks();
f.puttotal();
}
}
Output:
D:\GSK\JAVA>javac finaltot.java
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 AbstractClassDemo.java
D:\GSK\JAVA>java AbstractClassDemo
class SuperExample {
int a = 10;
}
{ void display() {
int a = super.a;
System.out.println("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 java.lang.*;
import java.io.*;
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()
{
System.out.println ("Name of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("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;
System.out.println ("Percentage: "+percent+"%");
}
void display()
{
super.display();
}
}
class Multiple
{
public static void main(String args[])
{
Result R = new Result("Ra.one",12,93,84);
R.display();
R.percent_cal();
}
}
Output:
D:\GSK\JAVA>javac Multiple.java
D:\GSK\JAVA>java Multiple
Marks of Subject 1: 93
Marks of Subject 2: 84
Percentage: 88.0%
import java.util.Scanner;
class Division {
public static void main(String[] args) {
int a, b, result;
Scanner input = new
Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
try {
result = a / b;
System.out.println("Result = " +
result);
}
catch (ArithmeticException e)
{ System.out.println("Exception caught: Division by
zero.");
}
finally {
System.out.println("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) {
System.out.println("Err: Divided by Zero");
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Err: Array Out of Bound");
}
}
}
Output:
GSK\JAVA>java ExceptionExample
class Shape
{
void draw()
{
System.out.println("drawing...");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("drawing circle...");
}
}
class Triangle extends Shape
{
void draw()
{
System.out.println("drawing triangle...");
}
}
class TestPolymorphism
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
Output:
D:\GSK\JAVA>javac TestPolymorphism.java
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)
{
System.out.println("Exception caught");
}
}
Output:
D:\GSK\JAVA>javac Test.java
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];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
/* the above statement will throw ArrayIndexOutOfBoundException */
}
finally
{
System.out.println("finally is always executed.");
}
}
}
Output:
JAVA>java ExceptionTest
out of try
finally is always executed.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3
out of bounds for length 2 at ExceptionTest.main(ExceptionTest.java:9)
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
System.out.println(a.charAt(0));
catch (NullPointerException e)
System.out.println("\t NullPointerException..");
try
System.out.println(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)
{ System.out.println("Catch Block") ;
System.out.println(exp) ;
Output:
D:\GSK\JAVA>javac UserException.java
D:\GSK\JAVA>java UserException
Catch Block
try
{
Thread.sleep(1);
}
catch (InterruptedException ie)
{
try
{
Thread.sleep (2);
}
catch (InterruptedException ie)
{
try
{
Thread.sleep (3);
}
catch (InterruptedException ie)
{
new ThirdThread();
firstThread.start();
secondThread.start();
thirdThread.start();
}
}
Output:
JAVA>java ThreadDemo
HELLO
WELCOME
GOOD MORNING
try
{
Thread.sleep(1);
}
catch (InterruptedException ie)
{
try
{
Thread.sleep (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 ThreadExample.java
D:\GSK\JAVA>java ThreadExample
true
Thread
Example using isAlive() and join()
false
c). Write a Program illustrating Daemon Threads.
dt1.setDaemon(true);
dt1.start();
dt2.start();
dt3.start();
}
}
Output:
D:\GSK\JAVA>javac DaemonThread.java
D:\GSK\JAVA>java DaemonThread
Daemon Thread Works
user Thread Works
user Thread Works
Exercise - 11 (Threads continuity)
class ProducerConsumerTest {
p1.start();
c1.start();
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;
this.number = number;
{ int value = 0;
{ value =
cubbyhole.get();
}
}
private CubbyHole
number;
{ cubbyhole = c;
this.number = number;
{ cubbyhole.put(i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
Output:
D:\GSK\JAVA>javac ProducerConsumerTest.java
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 Simple.java
package mypack;
{ System.out.println("Welcome to package");
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . Simple.java
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. mypack.Simple 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 A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.A;
class B{
obj.msg();
}
}
Output:
Hello
Exercise - 13 (Applet)
a) Write a JAVA program to paint like paint brush in applet.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=”Paint.class” 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 = e.getX();
int y = e.getY();
backg.fillOval(x-10,y-10,20,20);
repaint();
e.consume();
}
public void update( Graphics g )
{ g.drawImage( backbuffer, 0, 0, this );
}
public void paint( Graphics g )
{ update( g );
}
}
0utput:
b) Write a JAVA program to display analog clock using Applet.
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
/*
*/
Thread t = null;
boolean threadSuspended;
{ width =
getSize().width;
height = getSize().height;
setBackground( Color.black );
{ if ( t == null ) {
threadSuspended = false;
t.start();
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*Math.PI/3;
angle += 2*Math.PI/3;
{ g.setColor( Color.gray );
g.setColor( Color.white );
}
Output:
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
int x[]={10,220,220};
int y[]={400,400,520};
int n=3;
g.drawLine(10,30,200,30);
g.setColor(Color.blue);
g.drawRect(10,40,200,30);
g.setColor(Color.red);
g.fillRect(10,80,200,30);
g.setColor(Color.orange);
g.drawRoundRect(10,120,200,30,20,20);
g.setColor(Color.green);
g.fillRoundRect(10,160,200,30,20,20);
g.setColor(Color.blue);
g.drawOval(10,200,200,30);
g.setColor(Color.black);
g.fillOval(10,240,40,40);
g.setColor(Color.yellow);
g.drawArc(10,290,200,30,0,180);
g.setColor(Color.yellow);
g.fillArc(10,330,200,30,0,180);
g.setColor(Color.pink);
g.fillPolygon(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 java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*
<applet code="AppletMouseXY" width=300 height=300>
</applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <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 += ke.getKeyChar();
repaint();
} // Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
} }
Output: