Java R20 Lab Manual
Java R20 Lab Manual
Exercise : 1a) Write a JAVA program to display default value of all primitive data type
of JAVA
/* Write a JAVA program to display default value of all primitive data type
of JAVA */
voidprintValue() {
importjava.util.Scanner;
classQuaEq
{
if (a == 0)
{
System.out.println("Invalid");
return;
}
int D = b * b - 4 * a * c;
doublesqrt_val = Math.sqrt(D);
if (D > 0)
{
System.out.println("Roots are real and different \n");
r1=(-b+sqrt_val) /2*a;
r2=(-b-sqrt_val) /2*a;
System.out.println("root1 = "+r1);
System.out.println("root1 = "+r2);
} else
if (D == 0)
{
System.out.println("Roots are real and equal \n");
r1=(-b+sqrt_val) /2*a;
System.out.println("root1 = root2 = "+r1);
}
else // d < 0
{
System.out.println("Roots are complex and distinct \n");
System.out.println("root 1: "+(double)b / (2 * a) + " + i"
+ sqrt_val);
System.out.println("root2 : "+(double)b / (2 * a)
+ " - i" + sqrt_val);
}
}}
OUTPUT :-
Enter value for a :: 1
Enter value for b :: 2
Enter value for c :: 1
Roots are real and equal
root1 = root2 = -1.0
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.
classBikeRacers
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int speed[]=new int[5];
for(inti=0;i<5;i++) {
System.out.print("\nEnter the speed of Racer-"+i+":
");
speed[i]=sc.nextInt();
}
int sum=0;
for(inti=0;i<5;i++)
sum+=speed[i]; double
avg=sum/5;
System.out.print("\nThe speed of qualifying racers is:
");
lOMoAR cPSD| 27362123
for(inti=0;i<5;i++)
{
if(speed[i]>=avg)
System.out.print("\nRacer-"+i+": "+speed[i]);
}
}
}
OUTPUT:-
a) Write a JAVA program to search for an element in a given list of elements using binary
search mechanism.
importjava.util.Scanner;
classBinSearch
{
static void binarySearch(intarr[], int first, int last, int
key)
{
int mid = (first + last)/2;
(mid+1));
break;
} else
{ last =
mid - 1;
}
mid = (first + last)/2;
}
= new Scanner(System.in);
binarySearch(arr,0,num-1,key);
}
} OUTPUT:-
OUTPUT:-
----------------------------
for(inti=0;i<n;i++)
arr[i]=sc.nextInt();
Output:-
Enter no inegers to sort : 4
Enter 4 integers
6
2
9
1
Sorted List
1
2
6
9
importjava.util.Scanner;
importjava.util.Arrays;
int n1 = q - p + 1;
int n2 = r - q;
System.out.println("Sorted Array:");
System.out.println(Arrays.toString(array));
}}
OUTPUT:-
start_point – This refers to the beginning index and is included in the count. end_point – This
refer to the ending index and is excluded from the count.
Return Value : The method returns the string after deleting the substring formed by the
range mentioned in the parameters.
importjava.lang.*;
}
}
OUTPUT :-
double volume()
{
return (width * height * depth);
}
}
lOMoAR cPSD| 27362123
class Main
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
// display volume
double vol2=mybox2.volume();
System.out.print("Volume of Box2 :: "+vol2);
} // main() ends
} // class ends
OUTPUT:-
Volume of Box1 :: 3000.0
Volume of Box2 :: 162.0
Box
{ double
width;
double
height;
double
depth;
{
width=w;
height=h
;
depth=d;
}
double volume()
{
return (width * height * depth);
}
}
class Main
{
public static void main(String args[])
{
Box mybox1 = new Box(5,6,8);
Box mybox2 = new Box(3,4,2);
System.out.println("Using Constructor...");
// display volume
} // main() ends
} // class ends
OUTPUT:Using
Constructor...
Volume of Box1 :: 240.0
Volume of Box2 :: 24.0
Exercise - 4 (Methods)
/* In this program, Box defines the three constructors to initialize the dimensions of a box
various ways. */
lOMoAR cPSD| 27362123
class Box
{ double
width; double
height; double
depth;
doublevol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
lOMoAR cPSD| 27362123
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
OUTPUT :-
Volume of mybox1 is 40.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
classMethOverload
{
void sum (int a, int b)
{
System.out.println("sum of two int variables") ;
System.out.println("sum is "+(a+b)) ;
}
void sum (float a, float b)
{
System.out.println("sum of two float virables");
System.out.println("sum is "+(a+b));
}
void sum (int a, float b)
{
System.out.println("sum of int and float variables") ;
System.out.println("sum is "+(a+b)) ;
}
void sum (double a, double b)
{
System.out.println("sum of two double variables") ;
System.out.println("sum is "+(a+b)) ;
}
}
{
MethOverloadob = new MethOverload();
ob.sum (8,5); ob.sum
(4.6f, 3.8f);
ob.sum(5,7.2f);
ob.sum(1.2,3.6);
}
}
Exercise - 5 (Inheritance)
a) Write a JAVA program to implement Single Inheritance
classStu_Data
{ introllno;
String sname;
{
super(rno,name);
m=m1; p=m2;
c=m3; }
inttot_marks()
{
returnm+p+c;
}
floatavg()
{
return (m+p+c)/3.0f;
}
void display()
{
show();
System.out.println("Marks in 3 sub :: "+m+" "+p+" "+c);
System.out.println("Total :: "+tot_marks());
System.out.println("Average :: "+avg());
}
}
class Main
{
public static void main(String args[])
{
Student ob = new Student(501,"Ruchitha",65,54,71);
ob.display();
}
}
OUTPUT:-
Rollno :: 501
Name :: Ruchitha
Marks in 3 sub :: 65 54 71
Total :: 190
Average :: 63.333332
b)Write a JAVA program to implement multi level Inheritance
// MULTILEVEL INHERITANCE
class A
lOMoAR cPSD| 27362123
{ int a;
A(int a)
{
this.a = a;
}
voidshowA()
{
System.out.println("a : "+a);
}
}
class B extends A
{ int
b;
B(int a, int b)
{
super(a);
this.b=b;
}
voidshowB()
{
System.out.println("b: "+b);
}
}
class C extends B
{ int
c;
C(int a, int b, int c)
{
super(a,b);
this.c=c;
}
voidshowC()
{
showA();
showB();
System.out.pr
intln("c:
"+c);
System.out.println("Sum = "+sum());
} int
sum()
{
returna+b+c;
lOMoAR cPSD| 27362123
}
}
class Main{
public static void main(String args[])
{
C obj = new C(4,7,9);
obj.showC();
}
}
c)Write a java program for abstract class to find areas of different shapes
{ return
dim1*dim1;
}
}
class Triangle extends Shape
{
Triangle(double a, double b)
{
super(a,b);
} double
area()
{
return dim1*dim2*0.5;
}
}
class Circle extends Shape
{
Circle(double a, double b)
{
super(a,b);
} double
area()
{
return 3.14*dim1*dim2;
}
}
class Main{
public static void main(String[] args)
{
Rectangle r=new Rectangle(3,4);
Square s = new Square(5,5);
Triangle t = new Triangle(2,3);
Circle c = new Circle(4,4);
System.out.println("Abstract class Demo......\n");
System.out.println("Area of rectangle :: "+r.area());
System.out.println("Area of square :: "+s.area());
System.out.println("Area of triangle :: "+t.area());
System.out.println("Area of circle :: "+c.area());
}
}
Output:-
Abstract classes......
lOMoAR cPSD| 27362123
void display()
{
message();//will invoke or call current class message() method
super.message();//will invoke or call parent class message()
method }
Output:-
Good Morning Students
interface Writeable
{
lOMoAR cPSD| 27362123
void writes();
}
interface Readable
{ void
reads();
}
classStuData
{ intrno;
String name;
this.rno=rno;
this.name=name;
}
void display()
{
System.out.println("Roll No : "+ rno);
System.out.println("Name : "+ name);
}
Output:-
Roll No : 111
Name : Samantha
Total_marks :: 345 Student
reads.. Student writes..
EXCERCISE - 7
try {
int a = args.length;
catch(ArithmeticException e) {
lOMoAR cPSD| 27362123
System.out.println("Divide by 0: " +
e); }
catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace(); }
System.out.println("After try/catch
blocks.");
} }
}
}
classFindAreas
{ public static void main(String args[])
{
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8) Figure
figref = f;
System.out.println("Area is " + figref.area());
}
}
EXCERCISE-9
classRethrow
for(inti=0;i<=3;i++)
System.out.println(“Array element[”+i+”]=”+arr[i]);
System.out.println(“Exiting try block”);
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array Index Out of Bounds Exception
Caught”);
}}
OUTPUT:-
G:\JAVA>java Rethrow
Array Index Out of Bounds Exception Caught Throwing e and exiting inner catch block
atRethrow.main(Rethrow.java:9)
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
finally
{
System.out.println(“Inside finally block…”);
}
} }
Output:-
G:\JAVA>javac FinallyDemo.java
G:\JAVA>java FinallyDemo
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
Inside finally block...
G:\JAVA>java FinallyDemoaa bb cc
a=3
Array index oob: java.lang.ArrayIndexOutOfBoundsException: 42
Inside finally block...
import java.io.*; //
class Excep3 {
System.out.println(fileInput.readLine());
catch(FileNotFoundException e)
{ System.out.println("Specified file is not found
\n"+e); } catch(IOException e) {
catch(Exception e) {
e.printStackTrace();
}}
OUTPUT:-
G:\JAVA>type a.txt
programming in Java
util package
Oracle corporation
G:\JAVA>java Excep3
programming in Java
util package
// program to raise an exception when age of a person is beyond the range 1..100
importjava.util.Scanner;
classInvalidAgeException extends Exception
{
publicInvalidAgeException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
OUTPUT:-
G:\JAVA>java Excep5
Enter age of a person :
56
lOMoAR cPSD| 27362123
Valid age
G:\JAVA>java Excep5
Enter age of a person :
-2
Caught the exception
Invalid Age....
G:\JAVA>java Excep5
Enter age of a person :
104
Caught the exception
Invalid Age....
EXERCISE :10
a) Creating Multiple Threads by extending thread class first thread says "good morning",
second thread says "hello" ,third thread says "welcome"
importjava.lang.*;
classGoodMngThread extends Thread
{
String tname;
Thread th;
GoodMngThread(String str)
{
tname=str;
th = new Thread(this,tname); // creates thread
System.out.println("Starting thread :"+th);
th.start();
}
public void run()
{
intj,k,sum=0,prd=1;
while(true)
{ try
{
if (tname=="First")
{
System.out.println(tname+" says Good Morning");
Thread.sleep(1000);
}
else
if (tname=="Second")
{
lOMoAR cPSD| 27362123
}//while
}//run
}
main(String arg[]) {
newGoodMngThread("Second");
newGoodMngThread("Third");
Output:-
D:\javaPrgs>java MultiThread4
b) Creating Multiple Threads by implementing Runnable interface- first thread says "good
morning", second thread says "hello" ,third thread says "welcome"
importjava.lang.*;
classGoodMngThread implements Runnable
{
String tname;
Thread th;
GoodMngThread(String str)
{
tname=str;
th = new Thread(this,tname); // creates thread
System.out.println("Starting thread :"+th);
th.start();
}
public void run()
{
intj,k,sum=0,prd=1;
while(true)
{ try
lOMoAR cPSD| 27362123
{ if
(tname=="First")
{
System.out.println(tname+" says Good Morning");
Thread.sleep(1000);
} else if
(tname=="Second")
{
System.out.println(tname+" says Hello!!!!");
Thread.sleep(2000);
}
else
if (tname=="Third")
{
System.out.println(tname+" says Welcome...");
Thread.sleep(3000);
}
System.out.println(tname + " thread exits");
} //try
catch(InterruptedExceptionie) {
System.out.println("Thread interrupted.."); }
}//while
}//run
}
// create 3 threads
newGoodMngThread("First");
newGoodMngThread("Second");
newGoodMngThread("Third");
Output:-
D:\javaPrgs>javac MultiThreadRunn.java
D:\javaPrgs>java MultiThreadRunn
Main thread started....
Starting thread :Thread[First,5,main]
lOMoAR cPSD| 27362123
importjava.lang.*; classMyThread
implements Runnable { String
tname; // thread name
Thread th; // thread object
MyThread(String str)
{
tname=str;
th = new Thread(this,tname);
System.out.println("particulars of new thread :"+th);
th.start();
} public
void run()
{
try{
for (int k = 1; k<=4; k++)
{
System.out.println(tname + " : k="+k);
Thread.sleep(250);
}
}catch (InterruptedException ex)
{
lOMoAR cPSD| 27362123
Second : k=1
Third : k=1
First thread is alive: true
Second thread is alive: true
Third thread is alive: true
Waiting for threads to finish.
Third : k=2
First : k=2
Second : k=2
Third : k=3
First : k=3
Second : k=3
Third : k=4
Second : k=4
First : k=4
Thirdthread exits
Firstthread exits
Secondthread exits
First thread is alive: false
Second thread is alive: false
Third thread is alive: false
Main thread exiting......
D1.setDaemon(true);
D1.start();
D2.start();
D3.setDaemon(true);
D3.start();
}
}
Output:-
D:\javaPrgs>javac DaemonTh.java
D:\javaPrgs>java DaemonTh
D1 is Daemon thread
D3 is Daemon thread
D2 is User thread
Exercise – 11
(Interrupte
dException
e) { }
} contents
= value;
available =
true;
notifyAll();
}
}
class Consumer extends Thread {
private ABC abc;
privateint number;
{
public static void main(String[] args)
{
ABC c = new ABC();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
Output:-
D:\javaPrgs>javac ProConTest.java
D:\javaPrgs>java ProConTest
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Consumer #1 got: 2
Producer #1 put: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9
Thread Synchronization
For example, a single file is being updated by two threads. If one thread T1 is in the process of
updating this file say some variable. Now while this update by T1 is still in progress, let’s say
the second thread T2 also updates the same variable. This way when multiple threads are
involved, we should manage these threads in such a way that a resource can be accessed by a
single thread at a time. In the above example, the file that is accessed by both the threads should
be managed in such a way that T2 cannot access the file until T1 is done accessing it.
In this case, we do not need to synchronize the resource. In this case, JVM ensures that Java
synchronized code is executed by one thread at a time.
Most of the time, concurrent access to shared resources in Java may introduce errors like
“Memory inconsistency” and “thread interference”. To avoid these errors we need to go for
synchronization of shared resources so that the access to these resources is mutually exclusive.
Synchronized Keyword
We can write the concurrent parts (parts that execute concurrently) for an application using
the Synchronized keyword. We also get rid of the race conditions by making a block of code
or a method Synchronized.
When we mark a block or method synchronized, we protect the shared resources inside these
entities from simultaneous access and thereby corruption.
synchronized (object)
{
Statements to be synchronized
}
To make a method synchronized, simply add the synchronized keyword to its declaration:
• First, it is not possible for two invocations of synchronized methods on the same
object to interleave. When one thread is executing a synchronized method for an
object, all other threads that invoke synchronized methods for the same object block
(suspend execution) until the first thread is done with the object.
• Second, when a synchronized method exits, it automatically establishes a
happensbefore relationship with any subsequent invocation of a synchronized method
for the same object. This guarantees that changes to the state of the object are visible
to all threads.
lOMoAR cPSD| 27362123
EXPERIMENT – 12
a) Illustration of class path AIM: To write a JAVA program, illustrate class path
import java.net.URL; importjava.net.URLClassLoader;
public class App
{
public static void main(String[] args)
{
ClassLoadersysClassLoader =
ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();
for(inti=0; i<urls.length; i++)
{
System.out.println(urls[i].getFile());
}
}
}
OUTPUT: E:/java%20work/
AIM: To write a case study on including in class path in your os environment of your package.
Classpath in Java is the path to directory or list of the directories which is used by
ClassLoaders to find and load class in Java program. Classpath can be specified using
CLASSPATH environment variable which is case insensitive, -cp or classpath command-
line option. Environment variables are typically named in uppercase, with words joined with
underscore such as: JAVA_HOME .
Environment Variables
Many problems in the installation and running of Java applications are caused by incorrect
setting of environment variables especially in confoguring PATH, CLASSPATH and
JAVA_HOME.
Java PATH is the environment variable where we specify the locations of binaries.
lOMoAR cPSD| 27362123
When you run a program from the command line, the operating system uses the PATH
environment variable to search for the program in your local file system. In Java, for run any
program we use 'java.exe' and for compile java code use javac.exe . These all executable(.exe)
files are available in bin folder so we set path up to bin folder. The Operating System will look
in this PATH for executable. You can set the path environment variable temporary (command
line) and Permanent.
Step 4: Then you get Environment Variable window and Click on New...
lOMoAR cPSD| 27362123
Then you get a small window "New System Variable" and there you can set "Variable Name" and
"Variable Value". Set Variable Name as "path" and Variable Value as "your jdk path".
Click "OK" button. Now you set your Java Path and next is setting up ClassPath.
Java CLASSPATH is the path for Java application where the classes you compiled will be available. It is a
parameter in the Java Virtual Machine or the Java compiler that specifies the location of user-defined
classes and packages. The parameter may be set either on the command-line, or through an environment
variable. If CLASSPATH is not set, it is defaulted to the current directory. If you set the CLASSPATH , it
is important to include the current working directory (.). Otherwise, the current directory will not be
searched
setclasspath=.;C:\Program Files\Java\jdk1.8.0\lib\*
In Windows inorder to set ClassPath :
Then you get a small window "New System Variable" and there you can set "Variable Name"
and "Variable Value". Set Variable Name as "ClassPath" and Variable Value as "your class
path" (ex: C:\Program Files\Java\jdk1.8.0\lib\* ).
c) Write a JAVA program that import and use the defined your package in the previous
Problem packageMyPack;
{
bal=bal+amt;
returnbal;
}
public double withdraw(double amt)
{
if (bal>100)
{ if (bal-
amt> 100)
bal=bal-amt; else
System.out.println("\nEnter a lesser amount");
}
returnbal;
}
//Create a 昀椀 le called PkgDemo.javawchich imports the class Balance from package MyPack
importMyPack.Balance;
classPkgDemo
{
public static void main(String args[])
{
System.out.println("Customer1 details....");
cus1.show();
System.out.println("\nBalance after depositing Rs.700 is "+
cus1.deposit(700));
lOMoAR cPSD| 27362123
System.out.println("\nCustomer2 details....");
cus2.show();
cus2.withdraw(2200);
System.out.println("\nBalance after depositing Rs.400 is "+
cus1.withdraw(400));
}
}
Output:-
D:\javaPrgs>javac -d . Balance.java
D:\javaPrgs>javac PkgDemo.java
D:\javaPrgs>java PkgDemo
Customer1 details....
Account No : 233434
Name :Sunitha
Balance : 4500.0
Customer2 details....
Account No : 112255
Name :Ravindra
Balance : 1500.0
add(l1);
setSize(500,500);
setLayout(null);
setVisible(true);
}
public static void main(String a[])
{
MouseMotionListenerDemoCmmldc=new
MouseMotionListenerDemoC();
}
public void mouseDragged(MouseEvent me)
{ l1.setText("Mouse Dragged"+me.getX()+" , "+me.getY());
Graphics g=getGraphics();
g.setColor(Color.red);
g.fillOval(me.getX(),me.getY(),20,20);
} public void
mouseMoved(MouseEvent me)
{ l1.setText("Mouse Moved"+me.getX()+" ,
"+me.getY());
//Graphics g=getGraphics();
//g.setColor(Color.green);
//g.fillOval(me.getX(),me.getY(),20,20);
}
}
import java.util.*;
import java.text.*;
import java.applet.*;
import java.awt.*;
public class SimpleAnalogClock extends Applet implements Runnable
{
int clkhours = 0, clkminutes = 0, clkseconds = 0;
String clkString = "";
int clkwidth, clkheight;
Thread thr = null;
boolean threadSuspended;
public void init()
{
clkwidth = getSize().width;
clkheight = getSize().height;
setBackground(Color.black);
}
public void start()
{
if (thr == null)
lOMoAR cPSD| 27362123
{
thr = new Thread(this);
thr.setPriority(Thread.MIN_PRIORITY);
threadSuspended = false;
thr.start();
} else
{
if (threadSuspended)
{
threadSuspended = false;
synchronized(this)
{
notify();
}
}
}
}
public void stop()
{
threadSuspended = true;
}
public void run()
{
try
{
while (true)
{
Calendar clndr = Calendar.getInstance();
clkhours = clndr.get(Calendar.HOUR_OF_DAY);
if (clkhours > 12) clkhours -= 12;
clkminutes = clndr.get(Calendar.MINUTE);
clkseconds = clndr.get(Calendar.SECOND);
SimpleDateFormat frmatter = new
SimpleDateFormat("hh:mm: ss", Locale.getDefault());
Date d = clndr.getTime();
clkString = frmatter.format(d);
if (threadSuspended)
{
synchronized(this)
{
while (threadSuspended)
{
wait();
}
}
}
repaint();
thr.sleep(1000);
}
} catch (Exception e)
{}
}
void drawHand(double angle, int radius, Graphics grp)
{
angle -= 0.5 * Math.PI;
int a = (int)(radius * Math.cos(angle));
int b = (int)(radius * Math.sin(angle));
lOMoAR cPSD| 27362123
/*
<applet code="SimpleAnalogClock.class" width="350" height="350">
</applet>
c) Write a JAVA program to create different shapes and fill colors using Applet.
import
java.applet.*;
import
java.awt.*;
public class
ShapColor extends
Applet{
int
x=300,y=100,r=50;
public void paint(Graphics g){
g.setColor(Color.red); //Drawing line color is red
g.drawLine(3,300,200,10);
g.setColor(Color.magenta);
g.drawString("Line",100,100);
g.drawOval(x-r,y-r,100,100);
g.setColor(Color.yellow); //Fill the yellow color in circle
lOMoAR cPSD| 27362123
g.drawRect(400,50,200,100);
g.setColor(Color.yellow); //Fill the yellow color in rectangel
g.fillRect( 400, 50, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangle",450,100);
}
}