0% found this document useful (0 votes)
13 views

Java R20 Lab Manual

The document contains several Java programming exercises, including displaying default values of primitive data types, finding roots of quadratic equations, and implementing sorting algorithms like bubble sort and merge sort. It also covers class mechanisms, constructors, and method overloading. Each exercise includes code snippets and sample outputs demonstrating the functionality of the programs.

Uploaded by

settibhavana519
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Java R20 Lab Manual

The document contains several Java programming exercises, including displaying default values of primitive data types, finding roots of quadratic equations, and implementing sorting algorithms like bubble sort and merge sort. It also covers class mechanisms, constructors, and method overloading. Each exercise includes code snippets and sample outputs demonstrating the functionality of the programs.

Uploaded by

settibhavana519
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

lOMoAR cPSD| 27362123

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 */

public class PrimDt


{ byte b;
short s; int
k; long l;
float f;
double d;
boolean flag;
charch;
String str;

voidprintValue() {

System.out.println("default value of byte = "+ b);


System.out.println("default value of short = "+ s);
System.out.println("default value of int = "+ k);
System.out.println("default value of long = "+ l);
System.out.println("default value of float = "+ f);
System.out.println("default value of double = "+ d);
System.out.println("default value of boolean = "+ flag);
System.out.println("default value of char type= "+ ch);
System.out.println("default value of string = "+ str);
}
public static void main(String args[])
{
PrimDtob=new PrimDt();
ob.printValue();
}

OUTPUT:default value of byte = 0


default value of short = 0
default value of int = 0 default
value of long = 0 default value
of float = 0.0 default value of
double = 0.0 default value of
boolean = false default value of
char type= default value of
string = null
// b)Java program to find roots of a quadratic equation
lOMoAR cPSD| 27362123

importjava.util.Scanner;

classQuaEq
{

voidfindRoots(int a, int b, int c)


{
// If a is 0, then equation is not quadratic, but
linear double
r1,r2;

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);
}
}}

public static void main(String args[])


{

Scanner sc = new Scanner(System.in);


lOMoAR cPSD| 27362123

QuaEqob = new QuaEq();

System.out.print("Enter value for a :: ");


int a = sc.nextInt();

System.out.print("Enter value for b :: ");


int b = sc.nextInt();

System.out.print("Enter value for c :: ");


int c = sc.nextInt();
ob.findRoots(a,b,c);
sc.close();
}
}

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.

import java.io.*; import


java.util.Scanner;

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:-

Enter the speed of Racer-0: 60

Enter the speed of Racer-1: 75

Enter the speed of Racer-2: 92

Enter the speed of Racer-3: 65

Enter the speed of Racer-4: 85

The speed of qualifying racers is:


Racer-1: 75
Racer-2: 92
Racer-4: 85

Exercise - 2 (Operations, Expressions, Control-flow, Strings)

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;

while( first <= last )


{
if ( arr[mid] < key )
{ first =
mid + 1;
}
else if ( arr[mid] == key )
{
System.out.println("Element is found at position : " +
lOMoAR cPSD| 27362123

(mid+1));
break;
} else
{ last =
mid - 1;
}
mid = (first + last)/2;
}

if ( first > last ){


System.out.println("Element is not found!");
}
}
public static void main(String args[])
{
intnum,i,item,key,arr[]; Scanner input

= new Scanner(System.in);

System.out.println("Enter number of elements:");


num = input.nextInt();

//Creating array to store the all the numbers


arr = new int[num];

System.out.println("Enter " + num + " integers");


//Loop to store each numbers in array
for (i = 0;i <num; i++)
arr[i] = input.nextInt();

System.out.println("Enter the search value:");


key = input.nextInt();

binarySearch(arr,0,num-1,key);
}
} OUTPUT:-

nter number of elements:


6
Enter 6 integers
1
5
7
9
11
21 Enter the search
value:
11
Element is found at position : 5
lOMoAR cPSD| 27362123

OUTPUT:-

Enter number of elements:


5
Enter 5 integers
2
6
12
19
31 Enter the search
value:
8 Element is not
found!

----------------------------

b) Write a JAVA program to sort for an element in a given list


of elements using bubble sort importjava.util.Scanner;

public class BubSort


{
public static void main(String s[])
{
Scanner sc = new Scanner(System.in);
intarr[] = new int[20] ;

System.out.print("Enter no inegers to sort : ");


int n = sc.nextInt(); System.out.print("Enter
"+n+ " integers");

for(inti=0;i<n;i++)
arr[i]=sc.nextInt();

// sort the elements


for(inti=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if (arr[j] >arr[j+1])
{ int
temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}

// display sorted list

System.out.println("Sorted List ");


for(inti=0;i<n;i++)
System.out.println(arr[i]);
lOMoAR cPSD| 27362123

Output:-
Enter no inegers to sort : 4
Enter 4 integers
6
2
9
1

Sorted List
1
2
6
9

c) Write a JAVA program to sort for an element in a given list


of elements using merge sort.

importjava.util.Scanner;
importjava.util.Arrays;

public class Main {

// Merge two sub arrays L and M into array


void merge(int array[], int p, int q, int r)
{

int n1 = q - p + 1;
int n2 = r - q;

int L[] = new int[n1];


int M[] = new int[n2];

// fill the left and right array


for (inti = 0; i< n1; i++)
L[i] = array[p + i]; for (int j = 0;
j < n2; j++) M[j] = array[q +
1 + j];
// Maintain current index of sub-arrays and main array
inti, j, k;
i = 0;
j = 0;
k = p;
lOMoAR cPSD| 27362123

while (i< n1 && j < n2)


{
if (L[i] <= M[j])
{
array[k] = L[i];
i++;
}
Else
{
array[k] = M[j];
j++;
}
k++;
}

while (i< n1) {


array[k] = L[i];
i++;
k++;
}

while (j < n2) {


array[k] = M[j];
j++;
k++;
}
}
// Divide the array into two sub arrays, sort them and merge
them
voidmergeSort(int array[], int left, int right) {
if (left < right)
{
// m is the point where the array is divided into two sub
arrays int mid = (left + right) / 2;

// recursive call to each sub arrays


mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);

// Merge the sorted sub arrays


merge(array, left, mid, right);
}
}
public static void main(String args[]) {

// created an unsorted array

Scanner input = new Scanner(System.in);


lOMoAR cPSD| 27362123

System.out.print("Enter the number of integers to sort:");


intnum = input.nextInt(); int array[] = new
int[num]; System.out.println("Enter " + num + "
integers: ");

for (inti = 0; i<num; i++)


array[i] = input.nextInt();
Main ob = new Main();

// call the method mergeSort()


// pass argument: array, first index and last index
ob.mergeSort(array, 0, array.length - 1);

System.out.println("Sorted Array:");
System.out.println(Arrays.toString(array));
}}

OUTPUT:-

Enter the number of integers to sort:7


Enter 7 integers:
2
11
6
5
13
8
1 Sorted
Array:
[1, 2, 5, 6, 8, 11, 13]

d) Write a JAVA program using StringBuffer to delete, remove character.

publicStringBuffer delete(intstart_point, intend_point)

Parameters : The method accepts two parameters of integer type:

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.*;

public class StrBuf {


lOMoAR cPSD| 27362123

public static void main(String[] args)


{

StringBuffer sb1 = new StringBuffer("Java Programming");


System.out.println("given string :: "+ sb1);

// Deleting characters from index 2 to 7


sb1.delete(0, 5); System.out.println("After deletion
string is = " + sb1);

StringBuffer sb2 = new StringBuffer("The World Wide Web");


System.out.println("string = " + sb2);

// deleting characters from index 5 to index 9


sb2.delete(5,10); System.out.println("After deletion string
buffer is = " + sb2);

sb2.deleteCharAt(4); System.out.println("After deletion string


buffer is = " + sb2);

}
}

OUTPUT :-

given string :: Java Programming


After deletion string is = Programming
string = The World Wide Web
After deletion string buffer is = The WWide Web
After deletion string buffer is = The Wide Web

Exercise - 3 (Class, Objects)

a) Write a JAVA program to implement class mechanism. Create a class, methods


and invoke them inside main method. class Box
{ double
width; double
height; double
depth;

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();

// assign values to mybox1's instance variables


mybox1.width = 10; mybox1.height
= 20; mybox1.depth = 15;

/* assign different values to mybox2's instance variables */


mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;

// display volume

double vol1= mybox1.volume();


System.out.println("Volume of Box1 :: "+vol1);

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

b)Write a JAVA program to implement constructor. class

Box

{ double
width;
double
height;
double
depth;

Box(double w, double h, double d)


lOMoAR cPSD| 27362123

{
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

double vol1 = mybox1.volume();


System.out.println("Volume of Box1 :: "+vol1);

double vol2 = mybox2.volume();


System.out.println("Volume of Box2 :: "+vol2);

} // main() ends
} // class ends

OUTPUT:Using
Constructor...
Volume of Box1 :: 240.0
Volume of Box2 :: 24.0

Exercise - 4 (Methods)

a) Write a JAVA program to implement constructor overloading.

/* 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;

/* constructor used when all the dimensions specified */


Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

/* constructor used when no dimensions specified */


Box()
{
width = -1;
height = -1;
depth = -1;
}

/* constructor used when the cube is created */


Box(double len)
{
width = height = depth = len;
}

/* compute and return the volume */


double volume()
{
return width * height * depth;
}
}

public class OverloadConstructor


{
public static void main(String args[])
{
/* create boxes using the various constructors */
Box mybox1 = new Box(5, 2, 4);
Box mybox2 = new Box();
Box mycube = new Box(7);

doublevol;

vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
lOMoAR cPSD| 27362123

vol = mybox2.volume(); System.out.println("Volume


of mybox2 is " + vol);

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

b) Write a JAVA program implement method overloading.

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)) ;
}
}

public class Test


{
public static void main (String[] args)
lOMoAR cPSD| 27362123

{
MethOverloadob = new MethOverload();
ob.sum (8,5); ob.sum
(4.6f, 3.8f);
ob.sum(5,7.2f);
ob.sum(1.2,3.6);
}
}

OUTPUT:sum of two int variables


sum is 13 sum of two float
virables sum is 8.4 sum of int
and float variables sum is
12.2 sum of two double
variables sum is 4.8

Exercise - 5 (Inheritance)
a) Write a JAVA program to implement Single Inheritance

classStu_Data
{ introllno;
String sname;

Stu_Data(intrno, String name)


{
rollno=rno;
sname=name;
} void
show()
{
System.out.println("Rollno :: "+rollno);
System.out.println("Name :: "+sname);
}
}

class Student extends Stu_Data


{
intm,p,c;
Student(in
trno,
String
name, int
m1, int
m2, int
m3)
lOMoAR cPSD| 27362123

{
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

abstract class Shape


{
double dim1,dim2;
Shape(double a, double b)
{
dim1=a;
dim2=b;
}
abstract double area();
}

class Rectangle extends Shape


{
Rectangle(double a, double b)
{
super(a,b);
} double
area()
{ return
dim1*dim2; }
}
class Square extends Shape
{
Square(double a, double b)
{
super(a,b);
} double
area()
lOMoAR cPSD| 27362123

{ 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

Area of rectangle :: 12.0


Area of square :: 25.0
Area of triangle :: 3.0
Area of circle :: 50.24

Exercise - 6 (Inheritance - Continued)

a) Write a JAVA program give example for “super” keyword.


class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}

class Faculty extends Student


{
void message()
{
System.out.println("Good Morning Students");
}

void display()
{
message();//will invoke or call current class message() method
super.message();//will invoke or call parent class message()
method }

public static void main(String args[])


{
Faculty obj=new Faculty();
obj.display();
}
}

Output:-
Good Morning Students

Good Morning Sir

b) Write a JAVA program to implement Interface. What kind of Inheritance can be


achieved?

interface Writeable
{
lOMoAR cPSD| 27362123

void writes();
}
interface Readable
{ void
reads();

}
classStuData
{ intrno;
String name;

StuData(intrno, String name)


{

this.rno=rno;
this.name=name;
}
void display()
{
System.out.println("Roll No : "+ rno);
System.out.println("Name : "+ name);
}

class Student extends StuData implements Readable,Writeable


{
inttot_marks;

Student(intrno, String name, int marks)


{
super(rno,name);
tot_marks=marks;
} void show()
{
display();
System.out.println("Total_marks :: "+tot_marks);
}
public void reads()
{
System.out.print("Student reads.. ");
}
public void writes()
{
System.out.print("Student writes..");
}

public static void main(String args[])


{
lOMoAR cPSD| 27362123

Student s = new Student(111,"Samantha",345);


s.show();
s.reads();
s.writes();
}
}

Output:-

Roll No : 111
Name : Samantha
Total_marks :: 345 Student
reads.. Student writes..

EXCERCISE - 7

a) Write a JAVA program that describes exception handling mechanism


classExcepDemo { public static void
main(String args[]) { int d, a; try {
// monitor a block of code.
d = 0; a = 42 / d; System.out.println("This
will not be printed."); } catch
(ArithmeticException e)
{
// catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
} }

b) Write a JAVA program Illustrating Multiple catch clauses classMultiCatch{

public static void main(String args[]) {

try {

int a = args.length;

System.out.println("a = " + a); int b =

42 / a; int c[] = { 1 }; c[42] = 99; }

catch(ArithmeticException e) {
lOMoAR cPSD| 27362123

System.out.println("Divide by 0: " +

e); }

catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Accessing array elements beyond the


range : " + e); } catch(Exception e){

e.printStackTrace(); }

System.out.println("After try/catch

blocks.");

} }

Exercise – 8 (Runtime Polymorphism)

a) Write a JAVA program that implements Runtime polymorphism


// Using run-time polymorphism.

class Figure //super class


{ double dim1;
double dim2;
Figure(double a, double b)
{ dim1
= a;
dim2 =
b;
}
double area()
{
System.out.println("Area for Figure is undefined.");
return 0;
}
}

class Rectangle extends Figure


{
Rectangle(double a, double b)
{ super(a, b); }

// override area for rectangle


double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
lOMoAR cPSD| 27362123

}
}

class Triangle extends Figure


{
Triangle(double a, double b)
{ super(a,
b);
}
// override area for right triangle
double area()
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}

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; //super class ref variable

figref = r; System.out.println("Area is " +


figref.area());

figref = t; System.out.println("Area is " +


figref.area());

figref = f;
System.out.println("Area is " + figref.area());
}
}

The output from the program is shown here:


Inside Area for Rectangle.
Area is 45 Inside Area
for Triangle.
Area is 40 Area for Figure is
undefined.
Area is 0

EXCERCISE-9

a) Write a JAVA program for creation of Illustrating throw


lOMoAR cPSD| 27362123

classRethrow

public static void main(String args[]) {

int[] arr = {3,4,5}; try {

System.out.println(“Entered inner try block”);

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”);

System.out.println(“Throwing e and exiting inner catch


block”); throw e; }

}}

OUTPUT:-

G:\JAVA>java Rethrow

Entered try block

Array element[0]=3 Array element[1]=4 Array element[2]=5

Array Index Out of Bounds Exception Caught Throwing e and exiting inner catch block

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

atRethrow.main(Rethrow.java:9)

b) Write a JAVA program for creation of Illustrating finally classFinallyDemo{

public static void main(String args[])


{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
lOMoAR cPSD| 27362123

}
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...

c) Write a JAVA program for creation of Java Built-in Exceptions

import java.io.*; //

read text from a file

class Excep3 {

public static void main(String[] args) { try{

FileReader file = new FileReader("g:/java/a.txt");

BufferedReaderfileInput = new BufferedReader(file);


lOMoAR cPSD| 27362123

// Print first 3 lines of file for

(int counter = 0; counter < 3; counter++)

System.out.println(fileInput.readLine());

System.out.println("Reached end of the program...");

fileInput.close(); }//try ends

catch(FileNotFoundException e)
{ System.out.println("Specified file is not found

\n"+e); } catch(IOException e) {

System.out.println("IO Exception raised \n "+e); }

catch(Exception e) {

e.printStackTrace();

}}

OUTPUT:-

G:\JAVA>type a.txt

programming in Java

util package

Dennis Ritchie developed by C

Oracle corporation

Unix operating system

G:\JAVA>java Excep3

programming in Java

util package

Dennis Ritchie developed by C

Reached end of the program...


lOMoAR cPSD| 27362123

d)Write a JAVA program for creation of User Defined Exception

// 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);
}
}

public class Excep5


{
voidageCheck(int age) throws InvalidAgeException
{
if((age<1)||(age>100))
{
throw new InvalidAgeException("Invalid Age....");
}
else
System.out.println("Valid age");
}

public static void main(String args[])


{
Scanner sc = new Scanner(System.in);
Excep5 obj = new Excep5();

System.out.println("Enter age of a person : ");


int age=sc.nextInt();
try
{
obj.ageCheck(age);
}
catch (InvalidAgeException e)
{
System.out.println("Caught the exception");
System.out.println(e.getMessage());
}
}
}

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

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
}

public class MultiThread4{ public static void

main(String arg[]) {

System.out.println("Main thread started....");

// create 3 threads newGoodMngThread("First");

newGoodMngThread("Second");

newGoodMngThread("Third");

System.out.println("Exiting main thread......");

Output:-

D:\javaPrgs>java MultiThread4

Main thread started....


Starting thread :Thread[First,5,main]
Starting thread :Thread[Second,5,main]
First says Good Morning
Starting thread :Thread[Third,5,main]
Second says Hello!!!!
Third says Welcome...
Exiting main thread......
First thread exits
lOMoAR cPSD| 27362123

First says Good Morning


Second thread exits
Second says Hello!!!!
First thread exits
First says Good Morning
Third thread exits
Third says Welcome...
First thread exits
First says Good Morning
Second thread exits
Second says Hello!!!!
First thread exits
First says Good Morning
First thread exits
First says Good Morning
Third thread exits
Third says Welcome...
Second thread exits
Second says Hello!!!!
First thread exits
First says Good Morning
First thread exits
First says Good Morning
Second thread exits

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
}

public class MultiThreadRunn{ public static


void main(String arg[]) {
System.out.println("Main thread started....");

// create 3 threads
newGoodMngThread("First");
newGoodMngThread("Second");
newGoodMngThread("Third");

System.out.println("Exiting main thread......");


}
}

Output:-
D:\javaPrgs>javac MultiThreadRunn.java

D:\javaPrgs>java MultiThreadRunn
Main thread started....
Starting thread :Thread[First,5,main]
lOMoAR cPSD| 27362123

Starting thread :Thread[Second,5,main]


First says Good Morning
Starting thread :Thread[Third,5,main]
Second says Hello!!!!
Third says Welcome...
Exiting main thread......
First thread exits
First says Good Morning
Second thread exits
Second says Hello!!!!
First thread exits
First says Good Morning
Third thread exits
Third says Welcome...
First thread exits
First says Good Morning
Second thread exits
Second says Hello!!!!
First thread exits
First says Good Morning

c) Write a Java program illustrating isAlive() and join()


// Creating Multiple Threads -- use methods isAlive() and join().

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

System.out.println(tname+" has been interrupted");


}
System.out.println(tname + "thread exits");
}
}

public class MThread_isAlive{ public


static void main(String arg[])
{
// create 3 threads
MyThread t1=new MyThread("First");
MyThread t2=new MyThread("Second");
MyThread t3=new MyThread("Third");

System.out.println("First thread is alive: "+


t1.th.isAlive());
System.out.println("Second thread is alive: "+
t2.th.isAlive());
System.out.println("Third thread is alive: "+
t3.th.isAlive());

// wait for threads to finish


try {
System.out.println("Waiting for threads to
finish."); t1.th.join(); t2.th.join();
t3.th.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("First thread is alive: "+
t1.th.isAlive());
System.out.println("Second thread is alive: "+
t2.th.isAlive());
System.out.println("Third thread is alive:
"+t3.th.isAlive());
System.out.println("Main thread exiting......");
}
}
Output:-

D:\javaPrgs>java MThread_isAlive particulars of


new thread :Thread[First,5,main] particulars of
new thread :Thread[Second,5,main] First : k=1
particulars of new thread :Thread[Third,5,main]
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......

d) Program illustrating daemon thread

public class DaemonTh extends Thread


{
publicDaemonTh(String name1)
{
super(name1);
}
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println(getName() + " is Daemon thread");
}
else
{
System.out.println(getName() + " is User thread");
}
}
public static void main(String[] args)
{
DaemonTh D1 = new DaemonTh("D1");
lOMoAR cPSD| 27362123

DaemonTh D2 = new DaemonTh("D2");


DaemonTh D3 = new DaemonTh("D3");

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

a) Write a Java Program for producer consumer problem /*

producer consumer using threads

class ABC { privateint contents;


privateboolean available =
false;

public synchronized int get() {


while (available == false) {
try {
wait();
} catch (InterruptedException e) {}
} available
= false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch
lOMoAR cPSD| 27362123

(Interrupte
dException
e) { }
} contents
= value;
available =
true;
notifyAll();
}
}
class Consumer extends Thread {
private ABC abc;
privateint number;

public Consumer(ABC c, int number) {


abc = c;
this.number = number;
}
public void run() { int
value = 0; for (inti = 0;
i< 10; i++) { value =
abc.get();
System.out.println("Consumer #" + this.number + " got: " +
value);
}
}
}
class Producer extends Thread {
private ABC abc;
privateint number;
public Producer(ABC c, int number) {
abc = c;
this.number = number;
} public void run() {
for (inti = 0; i< 10; i++)
{
abc.put(i);
System.out.println("Producer #" + this.number + " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}

public class ProConTest


lOMoAR cPSD| 27362123

{
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

b) Write a case study on thread synchronization

Thread Synchronization

In a multithreading environment where multiple threads are involved, there are


clashesmayoccur when more than one thread tries to get the same resource at the same time.
These clashes result in “race condition” and thus the program produces unexpected results.
lOMoAR cPSD| 27362123

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.

This is done in Java using “Thread Synchronization”.

We use keywords “synchronized” and “volatile” to achieve Synchronization in Java We need


synchronization when the shared object or resource is mutable. If the resource is immutable,
then the threads will only read the resource either concurrently or individually.

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.

We use a concept called Monitors to implement synchronization. A monitor can be accessed


by only one thread at a time. When a thread gets the lock, then, we can say the thread has
entered the monitor. When a monitor is being accessed by a particular thread, the monitor is
locked and all the other threads trying to enter the monitor are suspended until the accessing
thread finishes and releases the lock.

Synchronized Keyword

Java provides a keyword “Synchronized” that can be used in a program to mark a


Critical section. The critical section can be a block of code or a complete method. Thus, only
one thread can access the critical section marked by the 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.

There are 2 types of synchronization as explained below:


#1) Process Synchronization
Process Synchronization involves multiple processes or threads executing simultaneously.
They ultimately reach a state where these processes or threads commit to a specific sequence
of actions.
lOMoAR cPSD| 27362123

#2) Thread Synchronization


In Thread Synchronization, more than one thread is trying to access a shared space. The threads
are synchronized in such a manner that the shared space is accessed only by one thread at a
time.

In Java, we can use the synchronized keyword with:


• A block of code
• A method
The above types are the mutually exclusive types of thread synchronization. Mutual exclusion
keeps the threads accessing shared data from interfering with each other. The synchronized
keyword in java creates a block of code referred to as critical section.

synchronized (object)
{
Statements to be synchronized
}

To make a method synchronized, simply add the synchronized keyword to its declaration:

public class SynchronizedCounter {


privateint c = 0;

public synchronized void increment() {


c++;
}

public synchronized void decrement() {


c--;
}

public synchronized int value() {


return c;
}
}

If count is an instance of SynchronizedCounter, then making these methods synchronized has


two effects:

• 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/

b) A case study on including in class path in os environment

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

JAVA_HOME : C:\Program Files\Java\jdk1.8.0


JDK_HOME : %JAVA_HOME%
JRE_HOME : %JAVA_HOME%\jre
CLASSPATH : .;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib
PATH : your-unique-entries;%JAVA_HOME%\bin

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.

How to set Java path in Windows

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.

Set path from Windows command line (CMD)


Set path = jdk_path

Set Permanent Path of Java in Windows

In Windows inorder to set

Step 1: Right Click on MyComputer and click on properties

Step 2: Click on Advanced System Setting


lOMoAR cPSD| 27362123

Step 3: Select Advanced Tab and Click on Environment Variables

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.

How to Set Classpath for Java on Windows

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 :

Repeat the above steps: Steps1 to Step4 .


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 "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;

public class Balance


{

String name; longaccno;


doublebal;

public Balance(String n, long ano, double b)


{ name =
n;
accno=ano;
bal = b; }

public double deposit(double amt)


lOMoAR cPSD| 27362123

{
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;
}

public void show()


{
System.out.println("Account No : "+accno);
System.out.println("Name : "+name);
System.out.println("Balance : "+bal);
}

Save the file as Balance.java


Compile the file as follows
D:\javaPrgs>javac -d . Balance.java
It creates a subdirectory namedMyPack in the current path and adds the class Balance into that
directory

//Create a 昀椀 le called PkgDemo.javawchich imports the class Balance from package MyPack

importMyPack.Balance;

classPkgDemo
{
public static void main(String args[])
{

Balance cus1 = new Balance("Sunitha",233434,4500);


Balance cus2 = new Balance("Ravindra",112255,1500);

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

Balance after depositing Rs.700 is 5200.0

Customer2 details....
Account No : 112255
Name :Ravindra
Balance : 1500.0

Enter a lesser amount

Balance after withdrawing Rs.400 is 1100.0

a) Write a JAVA program to paint like paint brush in applet.


importjava.awt.Frame;
importjava.awt.Label;
importjava.awt.event.*;
importjava.awt.Graphics;
importjava.awt.Color; public class
MouseMotionListenerDemoC extends Frame
implements
MouseMotionListener
{
Label l1;
MouseMotionListenerDemoC()
{
addMouseMotionListener(this);
l1=new Label("Mouse not found yet....Get the mouse on to
the frame!!!");
l1.setBounds(20,50,500,50);
lOMoAR cPSD| 27362123

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);
}
}

b) Write a JAVA program to display analog clock using Applet.

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

grp.drawLine(clkwidth / 2, clkheight / 2, clkwidth / 2 + a, clkh


eight / 2 + b);
}
void drawWedge(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));
angle += 2 * Math.PI / 3;
int a2 = (int)(5 * Math.cos(angle));
int b2 = (int)(5 * Math.sin(angle));
angle += 2 * Math.PI / 3; int a3
= (int)(5 * Math.cos(angle)); int
b3 = (int)(5 * Math.sin(angle));
grp.drawLine(clkwidth / 2 + a2, clkheight / 2 + b2, clkwidth /
2
+ a, clkheight / 2 + b);
grp.drawLine(clkwidth / 2 + a3, clkheight / 2 + b3, clkwidth /
2
+ a, clkheight / 2 + b);
grp.drawLine(clkwidth / 2 + a2, clkheight / 2 + b2, clkwidth /
2
+ a3, clkheight / 2 + b3);
}
} public void paint(Graphics grp)
{
grp.setColor(Color.gray);
drawWedge(2 * Math.PI * clkhours / 12, clkwidth / 5, grp);
drawWedge(2 * Math.PI * clkminutes / 60, clkwidth / 3, grp);
drawHand(2 * Math.PI * clkseconds / 60, clkwidth / 2, grp);
grp.setColor(Color.white);
grp.drawString(clkString, 10, clkheight - 10);
grp.drawString("C-Sharpcorner.com", 113, 300); }

/*
<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.fillOval( x-r,y-r, 100, 100 );


g.setColor(Color.magenta);
g.drawString("Circle",275,100);

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);
}
}

You might also like