0% found this document useful (0 votes)
11 views40 pages

Java Programming Exercises Overview

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views40 pages

Java Programming Exercises Overview

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

[Link] Date Title of the Experiment Page no Marks Remarks


1. a) display default value of all 3-5
primitive data type of JAVA
b) Write a java program that
display the roots of a quadratic
equation ax2
+bx=0. Calculate the
discriminate D and basing on
value of D, describe the nature of
root.
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.
2. a) binary search mechanism. 6-10
b) bubble sort
c) merge sort
d) StringBuffer to delete, remove
character.
3. a) program to implement class 11-12
mechanism
b) program to implement
constructor.
4. a) implement constructor 13-14
overloading.
b) implement method
overloading.
5. a)Single Inheritance 15-18
b)Multi level Inheritance
c) program for abstract class to
find areas of different shapes.
6. a)Super Keyword 19-20
b)Interface
7. a) program that describes 21-22
exception handling mechanism
b) program Illustrating Multiple
catch clauses
8. a)Runtime Polymorphism 23-26

1
b)case study on Runtime
polymorphism
9. a)Illustrating throw 27-29
b)Illustrating finally
c)creation of Java Bulit-in
Exceptions
d)creation of user defined
exceptions.
10. a) Write a JAVA program that 30-33
creates threads by extending
Thread class .First thread display
“Good Morning “every 1 sec, the
second thread displays “Hello
“every 2 seconds and the third
display “Welcome” every 3
seconds ,(Repeat the same by
implementing Runnable)
b) illustrating isAlive() and join()
c) illustrating Daemon Threads
11. a) Producer Consumer Problem 34-37
b) case study on thread
Synchronization after solving the
above producer consumer
problem.
12. a) illustrate class path 38-40
b) case study on including in
class path in your OS
environment of your package
c) program that import and use
the defined your package.

2
Exercise-1
a) Aim: Write a JAVA program to display default value of all primitive data type of
JAVA.
Program:
class Main
{
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:

b) Aim: Write a java program that display the roots of a quadratic equation ax2 +bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.
Program:
import [Link];
class Main
{

3
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int a=[Link]();
int b=[Link]();
int c=[Link]();
double d,r1,r2;
d=(b*b)-(4*a*c);
if(d>0)
{
[Link]("roots are real");
r1=((-b)+[Link](d))/(2*a);
r2=((-b)-[Link](d))/(2*a);
[Link]("root1 is "+r1);
[Link]("root2 is "+r2);
}
else if(d==0)
{
[Link]("roots are equal");
r1=(-b)/(2*a);
[Link]("root is"+r1);
}
else
{
[Link]("roots are imaginary");
}
}
}
Output:

c) Aim: 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.
Program:
import [Link].*;
class Main
{
static float S1,S2,S3,S4,S5;

4
static float AvgSpeed;
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter Speed of five Bike Racer");
S1 = [Link]();
S2 = [Link]();
S3 = [Link]();
S4 = [Link]();
S5 = [Link]();
AvgSpeed=(S1+S2+S3+S4+S5)/5;
[Link]("Average Speed="+AvgSpeed);
if( S1>AvgSpeed)
[Link]("The Speed of Qualifying Racer is "+S1);
if( S2>AvgSpeed)
[Link]("The Speed of Qualifying Racer is "+S2);
if( S3>AvgSpeed)
[Link]("The Speed of Qualifying Racer is "+S3);
if( S4>AvgSpeed)
[Link]("The Speed of Qualifying Racer is "+S4);
if( S5>AvgSpeed)
[Link]("The Speed of Qualifying Racer is "+S5);
}
}
Output:

5
Exercise-2

a) Aim: Write a JAVA program to search for an element in a given list of elements
using binary search mechanism.
Program:
import [Link].*;
class Main
{
public static void binarySearch(int arr[], 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 )
{
[Link]("Element is found at index: " + mid);
break;
}
else
last = mid - 1;
mid = (first + last)/2;
}
if ( first > last )
[Link]("Element is not found!");
}
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int n,key;
[Link]("Enter the size of array:");
n=[Link]();
int arr[] = new int[n];
[Link]("Enter the elements of array:");
for(int i=0;i<n;i++)
arr[i]=[Link]();
[Link]("Enter the value of key:");
key=[Link]();
int last=n-1;
binarySearch(arr,0,last,key);
}
}

6
Output:

b) Aim: Write a JAVA program to sort for an element in a given list of elements using
bubble sort.
Program:
import [Link].*;
class Main
{
static void bubbleSort(int[] arr)
{
int n = [Link];
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(arr[j-1] > arr[j])
{
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}

}
}
}
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int n,key;
[Link]("Enter the size of array:");
n=[Link]();
int arr[] = new int[n];
[Link]("Enter the elements of array:");
for(int i=0;i<n;i++)
arr[i]=[Link]();
bubbleSort(arr);
[Link]("Array After Bubble Sort:");
for(int i=0; i < n; i++)

7
[Link](arr[i] + " ");
}
}
Output:

c) Aim: Write a JAVA program to sort for an element in a given list of elements using
merge sort.
Program:
import [Link].*;
class Main
{
static void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
int LeftArray[]=new int[n1];
int RightArray[]=new int[n2];
for (int x = 0; x < n1; x++)
LeftArray[x] = a[beg + x];
for (int y = 0; y < n2; y++)
RightArray[y] = a[mid + 1 + y];
i = 0;
j = 0;
k = beg;
while (i < n1 && j < n2)
{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++; A
}
while (i<n1)

8
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}
static void mergeSort(int a[], int beg, int end)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int n,key;
[Link]("Enter the size of array:");
n=[Link]();
int a[] = new int[n];
[Link]("Enter the elements of array:");
for(int i=0;i<n;i++)
a[i]=[Link]();
mergeSort(a,0,n - 1);
[Link]("Array After Merge Sort:");
for(int i=0; i < n; i++)
[Link](a[i] + " ");
}
}
Output:

9
d) Aim: Write a JAVA program using StringBuffer to delete, remove character.
Program:
class Main
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello World");
[Link](0, 6);
[Link](sb1);
[Link](0, [Link]());
[Link](sb1);
sb1 = new StringBuffer("Hello World");
[Link](0);
[Link](sb1);
}
}
Output:

10
Exercise-3
a) Aim: Write a JAVA program to implement class mechanism. Create a class, methods
and invoke them inside main method.
Program:
class Box
{
double width,height,depth;
double volume()
{
return width*height*depth;
}
Box(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
}
class Main
{
public static void main(String args[])
{
Box obj=new Box(10,20,30);
Box obj1=new Box(3,6,9);
double vol;
vol=[Link]();
[Link]("volume is"+vol);
vol=[Link]();
[Link]("volume is"+vol);
}
}
Output:

b) Aim: Write a JAVA program to implement constructor.


Program:
class Box
{
double width,height,depth;
double volume()
{

11
return width*height*depth;
}
void dim(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
}
class Main
{
public static void main(String args[])
{
Box obj=new Box();
Box obj1=new Box();
double vol;
[Link](10,20,30);
[Link](20,30,40);
vol=[Link]();
[Link]("volume is"+vol);
vol=[Link]();
[Link]("volume is"+vol);
}
}
Output:

12
Exercise-4
a) Aim: Write a JAVA program to implement constructor overloading.
Program:
class Rectangle
{
Rectangle()
{
[Link]("default constructor");
}
Rectangle(int x)
{
[Link]("area="+x*x);
}
Rectangle(double x)
{
[Link]("area="+x*x);
}
Rectangle(int x,int y)
{
[Link]("area="+x*y);
}
Rectangle(double x,int y)
{
[Link]("area="+x*y);
}
public static void main(String args[])
{
Rectangle obj=new Rectangle();
Rectangle obj1=new Rectangle(10);
Rectangle obj2=new Rectangle(10.5);
Rectangle obj3=new Rectangle(10,20);
Rectangle obj4=new Rectangle(10.5,20);
}

Output:

13
b) Aim: Write a JAVA program implement method overloading.
Program:
class Overload
{
void area(int a)
{
int y=a*a;
[Link]("area of square:"+y);
}
void area(int l,int b)
{
int x=l*b;
[Link]("area of rectangle:"+x);
}
void area(int l,int b,int h)
{
int y=l*b*h;
[Link]("volume:"+y);
}
}
class Main
{
public static void main(String args[])
{
Overload obj=new Overload();
[Link](2);
[Link](2,4);
[Link](2,4,6);
}
}
Output:

14
Exercise-5
a) Aim: Write a JAVA program to implement Single Inheritance.
Program:
class Room
{
int length,width;
Room(int l,int w)
{
length=l;
width=w;
}
int area()
{
return length*width;
}
}
class Bedroom extends Room
{
int height;
Bedroom(int l,int w,int h)
{
super(l,w);
height=h;
}
int volume()
{
return length*width*height;
}
}
class Main
{
public static void main(String args[])
{
Bedroom obj=new Bedroom(10,20,30);
int res=[Link]();
[Link]("area is"+res);
int res1=[Link]();
[Link]("volume is"+res1);
}
}

15
Output:

b) Aim: Write a JAVA program to implement multilevel Inheritance.


Program:
class Room
{
int length,width;
Room(int l,int w)
{
length=l;
width=w;
}
int area()
{
return length*width;
}
}
class Bedroom extends Room
{
int height;
Bedroom(int l,int w,int h)
{
super(l,w);
height=h;
}
int volume()
{
return length*width*height;
}
}
class Living extends Bedroom
{
int breadth;
Living(int l,int w,int h,int b)
{
super(l,w,h);
breadth=b;
}
int volume1()
{
return length*width*height*breadth;
}

16
}
class Main
{
public static void main(String args[])
{
Living obj=new Living(10,20,30,40);
int res=[Link]();
[Link]("area is:"+res);
int res1=[Link]();
[Link]("volume is:"+res1);
int res2=obj.volume1();
[Link]("volume is:"+res2);
}
}
Output:

c) Aim: Write a java program for abstract class to find areas of different shapes.
Program:
import [Link].*;
abstract class Calc
{
abstract void findTriangle(double b,double h);
abstract void findRectangle(double l,double b);
abstract void findSquare(double s);
abstract void findCircle(double r);
}
class Area extends Calc
{
void findTriangle(double b,double h)
{
double area=(b*h)/2;
[Link]("area of triangle:"+area);
}
void findRectangle(double l,double b)
{
double area=l*b;
[Link]("area of rectangle:"+area);
}
void findSquare(double s)
{
double area=s*s;
[Link]("area of square:"+area);

17
}
void findCircle(double r)
{
double area=3.14*r*r;
[Link]("area of circle:"+area);
}
}
class Main
{
public static void main(String args[ ])
{
double l,b,h,r,s;
Area obj=new Area( );
Scanner sc=new Scanner([Link]);
[Link]("enter breadth and height:");
b=[Link]( );
h=[Link]( );
[Link](b,h);
[Link]("enter length and breadth:");
l=[Link]( );
b=[Link]( );
[Link](l,b);
[Link]("enter side of square:");
s=[Link]( );
[Link](s);
[Link]("enter radius of circle:");
r=[Link]( );
[Link](r);
}
}
Output:

18
Exercise-6

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


Program:
class A
{
void callMe( )
{
[Link]("hello CSD");
}
}
class B extends A
{
void callMe( )
{
[Link]( );
[Link]("all are good girls");
}
}
class Main
{
public static void main(String args[ ])
{
B obj=new B( );
[Link]( );
}
}
Output:

b) Aim: Write a JAVA program to implement Interface. What kind of Inheritance can be
achieved?
Ans: We can achieve Multiple Inheritance by using the Interfaces. The code is given
below as follows:
Program:
interface Area
{
final static float pi=3.14f;
float compute(float x,float y);
}
class Rec implements Area
{
public float compute(float x,float y)

19
{
return(x*y);
}
}
class Cir implements Area
{
public float compute(float x,float y)
{
return (pi*x*y);
}
}
class Main
{
public static void main(String args[ ])
{
Rec objr=new Rec( );
Cir objc=new Cir( );
Area ar;
ar=objr;
[Link]("area of rectangle:"+[Link](10,20));
ar=objc;
[Link]("area of circle:"+[Link](10,10));
}
}
Output:

20
Exercise-7
a) Aim: Write a JAVA program that describes exception handling mechanism.
Program:
class Main
{
public static void main(String args[])
{
int a=10,b=5,c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
[Link]("division by zero error.");
}
y=a/(b+c);
[Link]("y="+y);
}
}
Output:

b) Aim: Write a JAVA program Illustrating Multiple catch clauses.


Program:
class Main
{
public static void main(String args[])
{
int a[]={5,10};
try
{
int x=a[2]/a[1];
}
catch(ArithmeticException e)
{
[Link]("division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("array index error");
}
21
catch(ArrayStoreException e)
{
[Link]("Wrong entry");
}
int y=a[1]/a[0];
[Link]("y="+y);
}
}
Output:

22
Exercise-8

a) Aim: Write a JAVA program that implements Runtime polymorphism.


Program:
class A
{
void m1()
{
[Link]("Inside A's m1 method");
}
}
class B extends A
{
void m1()
{
[Link]("Inside B's m1 method");
}
}
class C extends A
{
void m1()
{
[Link]("Inside C's m1 method");
}
}
class Main
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A ref;
ref = a;
ref.m1();
ref = b;
ref.m1();
ref = c;
ref.m1();
}
}
Output:

23
b) Aim: Write a Case study on run time polymorphism, inheritance that implements in
above problem.
THEORY:
POLYMORPHISM:
Polymorphism in java is a concept by which we can perform a single action by different
ways. Polymorphism is derived from two Greek words 'poly' and 'morphs'. The word
'poly' means many and 'morphs' means forms so polymorphism means many forms.
There are two types of polymorphisms in java.
[Link]-time polymorphism.
[Link]-time polymorphism.
We can perform polymorphism in java by method overloading and method overriding.
Memory at compile time is called static allocation. If you overload static method in
java, It is called compile time polymorphism. Java resolves call to overloading methods
at compile time is called static polymorphism.
eg: Overloading.
RUNTIME POLYMORPHISM:
Runtime polymorphism or dynamic method dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile time. In this process, an
overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the
reference variable.
UPCASTING:
When reference variable of parent class refers to the object of child class. It is known
as upcasting. Java uses this fact to resolve calls to overridden methods at runtime.
superclass obj = new subclass
superclass
^
| extends
Subclass
For example:
class A
{
// statements
}
class B extends A
{
//statements
}
A a=new B();
Example Program:
class B
{
void run()
{
[Link]("running");
}

24
}
class S extends B
{
void run()
{
[Link]("running safely");
}
public static void main(String args[])
{
B obj=new S();
[Link]();
}
}
Output:

We are creating two classes B and S.S class extends B class and overrides its run() method.
We are calling the run method by the reference variable of the parent class. Since it refers to
the sub class object and sub class method overrides the parent class method, sub class method
is invoked at runtime.
Example for runtime polymorphism:
class A
{
void m()
{
[Link]("inside A's method");
}
}
class B extends A
{
void m()
{
[Link]("inside B's method");
}
}
class C extends A
{
void m()
{
[Link]("inside C's method");
}
}
class D
{
public static void main(String args[])
{
A a=new A();
B b=new B();

25
C c=new C();
A ref;
ref=a;
ref.m();
ref=b;
ref.m();
ref=c;
ref.m();
}
}
Output:

Java Runtime polymorphism with data member:


Method is overridden not the data member, so runtime polymorphism can't be achieved by data
member. In the example given below, both the classes have a data member. We are accessing
the data member by the reference variable of parent class which refers to the subclass object.
Since we are accessing the data member which is overridden, hence it will access the data
member of parent class.

26
Exercise-9

a) Aim: Write a JAVA program for creation of Illustrating throw.


Program:
class Main
{
static void demo()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
[Link]("caught inside demo");
throw e;
}
}
public static void main(String args[])
{
try
{
demo();
}
catch(NullPointerException e)
{
[Link]("recaught"+e);
}
}
}
Output:

b) Aim: Write a JAVA program for creation of Illustrating finally.


Program:
class Main
{
public static void main(String args[])
{
int a=10,b=5,c=5;
int x,y;
try

27
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
[Link]("division by zero");
}
finally
{
y=a/(b+c);
[Link]("y="+y);
}
}
}
Output:

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


Program:
class Main
{
public static void main(String args[])
{
try
{
int a[] = new int[5];
a[6] = 9;
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Array Index is Out Of Bounds");
}
}
}
Output:

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


Program:
class Demo extends Exception
{
Demo(String msg)
{

28
super(msg);
}
public String toString()
{
return "Exception in thread\"main\" Exceptdemo:"+getMessage();
}
}
class Test
{
static void test()throws Demo
{
throw new Demo("testing");
}
public static void main(String args[])
{
try
{
test();
}
catch(Demo e)
{
[Link](e);
}
}
}
Output:

29
Exercise-10

a) Aim: Write a JAVA program that creates threads by extending Thread class .First
thread display “Good Morning “every 1 sec, the second thread displays “Hello “every
2 seconds and the third display “Welcome” every 3 seconds ,(Repeat the same by
implementing Runnable).
Program:
import [Link].*;
import [Link].*;
class A extends Thread
{
public void run()
{
for(int i=0;i<3;i++)
{
[Link]("GOOD MORNING");
try
{
[Link](1000);
}
catch(Exception e)
{
[Link](e);
}
}
}
}
class B extends Thread
{
public void run()
{
for(int i=0;i<3;i++)
{
[Link]("HELLO");
try
{
[Link](2000);
}
catch(Exception e)
{
[Link](e);
}
}
}
}

30
class C extends Thread
{
public void run()
{
for(int i=0;i<3;i++)
{
[Link]("WELCOME");
try
{
[Link](3000);
}
catch(Exception e)
{
[Link](e);
}
}
}
}
class Run1
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
Output:

b) Aim: Write a program illustrating isAlive () and join ().


Program:
class Newthread implements Runnable
{
String name;
Thread t;

31
Newthread(String Threadname)
{
name=Threadname;
t=new Thread(this,name);
[Link]("new thread:"+t);
[Link]();
}
public void run()
{
try
{
for(int i=5;i>5;i--)
{
[Link](name+":"+i);
[Link](1000);
}
}
catch(InterruptedException e)
{
[Link](name+"interrupted");
}
[Link](name+"exiting");
}
}
class Demojoin
{
public static void main(String args[])
{
Newthread ob1=new Newthread("one");
Newthread ob2=new Newthread("two");
Newthread ob3=new Newthread("three");
[Link]("thread one is alive:"+[Link]());
[Link]("thread two is alive:"+[Link]());
[Link]("thread three is alive:"+[Link]());
try
{
[Link]("waiting for threads to finish");
[Link]();
[Link]();
[Link]();
}
catch(InterruptedException e)
{
[Link]("main thread interrupted");
}
[Link]("thread one is alive:"+[Link]());

32
[Link]("thread two is alive:"+[Link]());
[Link]("thread three is alive :"+[Link]());
}
}
Output:

c) Aim: Write a Program illustrating Daemon Threads.


Program:
public class DaemonThreadExample1 extends Thread
{
public void run()
{
if([Link]().isDaemon())
{
[Link]("Daemon thread execution");
}
else
{
[Link]("user(normal)thread executing");
}
}
public static void main(String args[])
{
DaemonThreadExample1 t1=new DaemonThreadExample1();
DaemonThreadExample1 t2=new DaemonThreadExample1();
[Link](true);
[Link]();
[Link]();
}
}
Output:

33
Exercise-11

a) Aim: Write a JAVA program Producer Consumer Problem.


Program:
class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
while(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
[Link]("caught");
}
[Link]("got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
while(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
[Link]("caught");
}
this.n=n;
valueSet=true;
[Link]("put:"+n);
notify();

}
}
class P implements Runnable
{
Q q;

34
P(Q q)
{
this.q=q;
new Thread(this,"P").start();
}
public void run()
{
int i=0;
while(true)
{
[Link](i++);
}
}
}
class C implements Runnable
{
Q q;
C(Q q)
{
this.q=q;
new Thread(this,"C").start();
}
public void run()
{
int i=0;
while(true)
{
[Link]();
}
}
}
class PC
{
public static void main(String args[])
{
Q q=new Q();
new P(q);
new C(q);
[Link]("press ctrl-c to stop");
}
}
Output:

35
b) Aim: Write a case study on thread Synchronization after solving the above producer
consumer problem.
THEORY:
Multi-threading replaces event loop programming by dividing your tasks into discrete,
Logical units. Threads also provide a secondary benefit. They do away with polling.
Polling is usually implemented by a loop that is used to check some condition
repeatedly. This wastes CPU time.
For example, Consider the classic queuing problem where one thread is producing some
data and another is consuming it. In a polling system consumer would waste time and
CPU cycles. While it waited for the producer to produce. Once the producer was
finished, It would start polling. Wasting many CPU cycles and waiting for the consumer
to finish etc.
To avoid polling, java includes an elegant inter process communication mechanism via
the wait(), notify()and notifyAll() methods. These methods are implemented as final
methods within object, Can be called only from within a synchronized context.
❖ wait() tells the calling thread to give up the monitor and go to sleep until some
other thread enters the some monitor and call notify().
❖ notify() wakes up a thread that called wait() on the same object.
❖ notifyAll() wakes up all the threads that called wait() on the same object. One
of the threads will be granted access.
These methods are declared within object as shown below. final void wait() throws
InterruptedException ,final void notify(),final void notifyAll().

CASESTUDY REGARDING THE PREVIOUS PRODUCER CONSUMER


BELOW

36
Inside get(), wait() is called. This causes its execution to suspend until the producer
modifies you that some data is ready. When this happens, execution inside get()
resumes.
After the data has been obtained get() calls notify(). This tells producer that it is okay
to put more data in the queue. Inside put(), wait() suspends execution until the consumer
has removed the item from the queue. When execution resumes, the next item of data
is put in the queue and notify() is called. This tells the consumer that it should now
remove it.

37
Exercise-12
a) Aim: Write a JAVA program illustrate class path.
Program:
package pack1;
public class A
{
public void disA()
{
[Link]("class A");
}
}
import pack1.A;
class Test
{
public static void main(String args[])
{
A obj=new A();
[Link]();
}
}
Output:

b) Aim: Write a case study on including in class path in your OS environment of your
package.

THEORY:
Package is a set of collection of classes. It acts as 'container' for classes.
Package are of two types
[Link] API package
[Link] defined package
In packages, classes can be unique compared with classes in other packages. i.e. two
classes in different packages can be have on the same name. They may be referred by
their fully qualified name, comprising the package name and the class name.
Every package name must be unique to make the best use of packages. Duplicate
names will cause run-time errors

38
Since multiple users work on internet, Duplicate package names are unavailable. To
avoid this java designers suggested a package naming convention that ensures
uniqueness.
We use import statement when there are many references to a particular name or
package name too long and un-weirdly.
The import statement is used to search a list of package for a particular order class.
Example:
package
package package1
public class classA
{
public void displayA()
{
[Link]("we are CSE students");

}
}
MAIN PROGRAM:
import [Link]
class Test2
{
public static void main(String args[])
{
classA obj=new classA();
[Link]();
}
}
When we import multiple packages,It is likely that two or more packages contain
classes with identical names.
FINDING PACKAGES AND CLASS PATH:
Packages are mentioned by directories.
How does the java run-time system know where to look for packages that you create?
It is having two parts.
[Link] default, the java run-time system uses the current working directory as its
starting point.
[Link] can learn specify a directory path or paths by setting class path environment
variable.

c) Aim: Write a JAVA program that import and use the defined your package in the
previous Problem.
Program:
package pack1;
public class A
{
public void display()
{

39
[Link]("cse-A");
}
}
import pack1.A;
class T
{
public static void main(String args[])
{
A obj=new A();
[Link]();
}
}
Output:

40

Common questions

Powered by AI

Method overloading occurs when multiple methods in the same class have the same name but different parameter lists, enabling different behaviors for different input types, resolved at compile-time. Conversely, method overriding involves redefining a superclass method in a subclass with the same signature, allowing runtime polymorphism where the JVM determines the appropriate method version based on the object instance at runtime. The document provides examples of method overloading with the 'area' method demonstrating different parameter configurations, and method overriding where the subclass methods modify inherited behavior at runtime.

Encapsulation facilitates data security by restricting direct access to class variables, requiring interaction through well-defined methods, thus protecting data integrity. Using private variables within a class and public getter and setter methods, encapsulation ensures that data can only be modified in controlled ways, preventing unauthorized access or invalid data manipulation. Although specific examples aren't provided, this concept is fundamental to all Java programming practices illustrated.

Java handles exceptions through the try-catch-finally mechanism, where a potential error code segment is enclosed in a 'try' block, specific exceptions are captured in 'catch' blocks, and the 'finally' block contains code that executes regardless of exceptions. For instance, in the example where division by zero is attempted, the 'catch' block handles the ArithmeticException, while the 'finally' block executes additional division that is unrelated to the try-catch scope.

Abstract classes in Java allow the definition of abstract methods which subclasses must implement, enforcing a contract for consistent behavior across varied implementations. This is advantageous in the calculation of shape areas, as seen in the 'Calc' class example, where abstract methods like 'findTriangle', 'findRectangle', etc., require specific calculations defined in the 'Area' subclass. This setup provides a structured yet flexible framework for adding new shapes and calculation methods without altering the abstract class structure.

The creation of packages in Java is crucial for code organization, promoting reuse, and managing namespaces to prevent conflicts. Packages act as containers for classes and interfaces, allowing developers to group related classes, which simplifies project structure and enhances maintainability. They enable unique class identification across different packages, thus supporting large application development by avoiding class name conflicts. The document details the setup of user-defined packages, which is essential for modular programming and facilitating team collaboration by encapsulating code functionalities into distinct, manageable parts.

Merge sort operates by dividing the array into two halves, sorting each half recursively, and then merging the sorted halves to produce the sorted array. Its efficiency comes from the divide-and-conquer approach, which ensures a time complexity of O(n log n) in the worst case, making it more efficient for larger datasets compared to algorithms like bubble sort with O(n^2) complexity.

The 'super' keyword in Java is used to access methods and constructors of a superclass from a subclass. It allows a subclass to invoke a superclass’s constructor and methods, facilitating code reuse and enhancing functionality. For instance, in the given code, class B overrides the 'callMe' method of class A, and within it, calls 'super.callMe()', allowing it to execute the superclass's version of the method alongside its own.

Constructor overloading allows a Java class to define multiple constructors with different parameters, enabling the creation of objects in various states or configurations. For instance, the 'Rectangle' class demonstrates overloading by providing constructors that calculate area differently based on the number and types of inputs (e.g., no parameters, one integer, one double, two integers, and one double with one integer).

Runtime polymorphism, also called dynamic method dispatch, is a process where the call to an overridden method is resolved at runtime based on the object's actual class. It is achieved in Java through method overriding and using a superclass reference to refer to a subclass object. For example, in the provided code, the 'run' method in class 'B' is overridden in class 'S', and when 'obj.run()' is called, the overridden method in class 'S' is executed at runtime, even though 'obj' is of type 'B'.

Polling mechanisms, which rely on loops to continually check a condition, waste CPU resources as they keep the processor engaged unnecessarily when waiting for certain conditions or data. Java addresses this inefficiency with the wait-notify approach, which relies on threads to wait actively for specific changes. Using methods like 'wait()', 'notify()', and 'notifyAll()', Java threads release the CPU while waiting, only resuming operation upon receiving notifications from other threads, ensuring more efficient CPU utilization.

You might also like