You are on page 1of 60

S.No: 1 Exp.

Name: Write a Java program to Display Default values of all Primitive data types Date: 2022-04-27

Aim:

Page No:
Write a java program to display the default values of all primitive data types.

Write a class PrimitiveTypes with main(String[ ] args) method.

ID: 208A1A05A6
Write code to produce the below output:

byte default value = 0


short default value = 0
int default value = 0
long default value = 0
boolean default value = false
double default value = 0.0
float default value = 0.0

Note: Please don't change the package name.


Source Code:

q10815/PrimitiveTypes.java

package q10815;
import java.io.*;
class PrimitiveTypes
{
static int I1;
static char C1;
static float F1;
static boolean bo1;
static byte B1;

2020-2024-CSE-A
static double D1;
static short S1;
static long L1;
public static void main(String[] args)
{
System.out.println("byte default value = "+B1);
System.out.println("short default value = "+S1);
RISE Krishna Sai Prakasam Group of Institutions
System.out.println("int default value = "+I1);
System.out.println("long default value = "+L1);
System.out.println("boolean default value = "+bo1);
System.out.println("double default value = "+D1);
System.out.println("float default value = "+F1);
}

Execution Results - All test cases have succeeded!

Test Case - 1
Test Case - 1

User Output

Page No:
byte default value = 0
short default value = 0
int default value = 0
long default value = 0

ID: 208A1A05A6
boolean default value = false
double default value = 0.0
float default value = 0.0

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 2 Exp. Name: Write a Java code to calculate the Roots of a Quadratic equation Date: 2022-05-18

Aim:

Page No:
Write code to calculate roots of a quadratic equation.

Write a class QuadraticRoots with main method. The method receives three arguments, write code

ID: 208A1A05A6
to parse them into double type.

For example:

if the values 2, 5, 3 are passed as arguments, then the output should be First root is : -1.0 Second root is : -1.5
If the values 3, 2, 1 are passed then the output should be Roots are imaginary
Similarly, if the values 2, 4, 2 are passed then the output should be Roots are equal and value is : -1.0

Note: Make sure to use the print() and not the println() method.

Note: Please don't change the package name.


Source Code:

q10851/QuadraticRoots.java

package q10851;
import java.io.*;
import java.lang.Math;
class QuadraticRoots
{
public static void main(String[] args)
{
double a,b,c;
double d,r1,r2,d1;
a=Double.parseDouble(args[0]);
b=Double.parseDouble(args[1]);
c=Double.parseDouble(args[2]);
d=(b*b)-4*a*c;
if(d<0)
{
System.out.println("Roots are imaginary");
}
else if(d==0)
{
r1=-b/(2*a);
System.out.println("Roots are equal and value is : "+r1);
}
else
{
d1=Math.sqrt(d);
r1=(-b+d1)/(2*a);
r2=(-b-d1)/(2*a);
System.out.println("First root is : "+r1+" Second root is : "+r2);

2020-2024-CSE-A
}
}
}

Execution Results - All test cases have succeeded!


RISE Krishna Sai Prakasam Group of Institutions

Test Case - 1

User Output
First root is : -0.6047152924789525 Second root is : -1.3952847075210475

Test Case - 2

User Output
Roots are equal and value is : -1.0

Test Case - 3

User Output
Test Case - 3
Roots are imaginary

ID: 208A1A05A6 Page No:


RISE Krishna Sai Prakasam Group of Institutions 2020-2024-CSE-A
S.No: 3 Exp. Name: Write a Java program to print the speeds of qualifying bikers in a Race Date: 2022-05-27

Aim:

Page No:
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.

ID: 208A1A05A6
To qualify the race, the speed of a racer must be more than or equal to the average speed of all the 5
racers.

Take as input the speed of each racer and print back the speeds of qualifying racers.

Write a class Race with a method main(String[] args) . The main method receives five arguments.
You can write code to parse them into double data type.

For example, if the values 54.55, 53.57, 54, 56.25, 57.30 are passed as arguments to the main()
method, then the output should be
The speed of the racers >= average speed 55.134 : 56.25 57.3 .

Note: Make sure to use the print() method and not the println() method.
Source Code:

Race.java

class Race{
public static void main(String args[]){
double sum,avg;
double a=Double.parseDouble(args[0]);
double b=Double.parseDouble(args[1]);
double c=Double.parseDouble(args[2]);
double d=Double.parseDouble(args[3]);
Double e=Double.parseDouble(args[4]);
sum=a+b+c+d+e;
avg=sum/5;

2020-2024-CSE-A
System.out.print("The speed of the racers >= average speed "+avg+": ");
if(a>avg){
System.out.print(","+a);
}
if(b>avg){
System.out.print(","+b);
} RISE Krishna Sai Prakasam Group of Institutions
if(c>avg){
System.out.print(","+c);
}
if(d>avg){
System.out.print(","+d);
}
if(e>avg){
System.out.print(","+e);
}
}

}
Execution Results - All test cases have succeeded!

Test Case - 1

Page No:
User Output
The speed of the racers >= average speed 54.855999999999995: ,81.6,58.19,79.42

ID: 208A1A05A6
Test Case - 2

User Output
The speed of the racers >= average speed 78.0032: ,96.21,87.26,105.63

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 4 Exp. Name: Write a Java program to Search an element using Binary Search Date: 2022-05-27

Aim:

Page No:
Binary search is faster than linear search, as it uses divide and conquer technique and it works on the
sorted list either in ascending or descending order.

ID: 208A1A05A6
Binary search (or) Half-interval search (or) Logarithmic search is a search algorithm that
finds the position of a key element within a sorted array.

Binary search compares the key element to the middle element of the array; if they are unequal, the
half in which the key element cannot lie is eliminated and the search continues on the remaining half until it
is successful.

The working procedure for binary search is as follows:

1. Let us consider an array of n elements and a key element which is going to be search in the list of
elements.
2. The main principle of binary search has first divided the list of elements into two halves.
3. Compare the key element with the middle element.
4. If the comparison result is true the print the index position where the key element has found and stop
the process.
5. If the key element is greater than the middle element then search the key element in the second half.
6. If the key element is less than the middle element then search the key element in the first half.
7. Repeat the same process for the sub lists depending upon whether key is in the first half or second
half of the list until a match is found (or) until all the elements in that half have been searched.

Let us consider an example of array numbers "50 20 40 10 80", and the key element is to find is 10.

Search - 1 :
First Sort the given array elements by using any one of the sorting technique.
After sorting the elements in the array are 10 20 40 50 80 and initially low =
0, high = 4.

2020-2024-CSE-A
Search - 2 :
Compare 10 with middle element i.e., (low + high) / 2 = (0 + 4) / 2 = 4 / 2 = 2
, a[2] is 40.
Here 10 < 40 so search the element in the left half of the element 40. So low =
0, high = mid - 1 = 2 - 1 = 1.
RISE Krishna Sai Prakasam Group of Institutions

Search - 3 :
Compare 10 with middle element i.e., (low + high) / 2 = (0 + 1) / 2 = 1 / 2 = 0
, a[0] is 10.
Here 10 == 10 so print the index 0 where the element has found and stop the pr
ocess

Write a class BinarySearch with a public method binarySearch that takes two parameters an
array of type int[] and a key of type int . Write a code to search the key element within the
array elements by using binary search technique.

Examples for your understanding:


Cmd Args : 10 1 2 3 4 5 4
Search element 4 is found at position : 4

Page No:
Cmd Args : 10 8 12 11 9
Search element 9 is not found

ID: 208A1A05A6
Note: Please don't change the package name.

Source Code:

q11045/BinarySearch.java

package q11045;
public class BinarySearch
{
public void binarySearch(int[] array,int key){
int beg=0,end=array.length-1;
while(beg <=end){
int mid=beg+(end-1)/2;
if(array[mid]==key){
System.out.println("Search element "+key+" is found at position : "+
mid);
return;
}
if(key>array[mid]){
beg=mid+1;
}
else{
end=mid-1;
}
}
System.out.println("Search element "+key+" is not found");

2020-2024-CSE-A
}
}

q11045/BinarySearchMain.java

package q11045; RISE Krishna Sai Prakasam Group of Institutions


public class BinarySearchMain{
public static void main(String[] args){
int[] array = new int[args.length];
int n = args.length-1;

for (int i = 0; i < n; i++)


{
array[i] = Integer.parseInt(args[i]);
}
int key = Integer.parseInt(args[n]);
BinarySearch biSearch = new BinarySearch();
biSearch.binarySearch(array, key);
}
}
Execution Results - All test cases have succeeded!

Page No:
Test Case - 1

User Output

ID: 208A1A05A6
Search element 4 is found at position : 4

Test Case - 2

User Output
Search element 9 is not found

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 5 Exp. Name: Write a Java program to Sort elements using Bubble Sort Date: 2022-05-27

Aim:

Page No:
Sorting specifies the way to arrange data in a particular order either in ascending or descending.

Bubble sort is an internal sorting technique in which adjacent elements are compared and exchanged

ID: 208A1A05A6
if necessary.

The working procedure for bubble sort is as follows:

1. Let us consider an array of n elements (i.e., a[n]) to be sorted.


2. Compare the first two elements in the array i.e., a[0] and a[1], if a[1] is less than a[0] then
interchange the two values.
3. Next compare a[1] and a[2], if a[2] is less than a[1] then interchange the values.
4. Continue this process till the last two elements are compared and interchanged.
5. Repeat the above steps for n - 1 passes.

Let us consider an example of array numbers "50 20 40 10 80", and sort the array from lowest number to
greatest number using bubble sort.

In each step, elements written in bold are being compared. Number of elements in the array are 5, so 4
passes will be required.

Pass - 1 :
( 50 20 40 10 80 ) -> ( 20 50 40 10 80 ) // Compared the first two elements, an
d swaps since 50 > 20.
( 20 50 40 10 80 ) -> ( 20 40 50 10 80 ) // Swap since 50 > 40.
( 20 40 50 10 80 ) -> ( 20 40 10 50 80 ) // Swap since 50 > 10.
( 20 40 10 50 80 ) -> ( 20 40 10 50 80 ) // Since the elements are already in
order (50 < 80), algorithm does not swap them.

Total number of elements in the given array are 5, so in Pass - 1 total numbers compared are 4. After
completion of Pass - 1 the largest element is moved to the last position of the array.

2020-2024-CSE-A
Now, Pass - 2 can compare the elements of the array from first position to second last position.

Pass - 2 :
( 20 40 10 50 80 ) -> ( 20 40 10 50 80 ) // Since the elements are already i
n order (20 < 50), algorithm does not swap them.
( 20 40 10 50 80 ) -> ( 20 10 40 50 80 ) // Swap since 40 > 10.
( 20 10 40 50 80 ) -> ( 20 10 40 50 80 ) // Since the elements are already in RISE Krishna Sai Prakasam Group of Institutions
order (40 < 50), algorithm does not swap them.

In Pass - 2 total numbers compared are 3. After completion of Pass - 2 the second largest element is
moved to the second last position of the array.

Now, Pass - 3 can compare the elements of the array from first position to third last position.

Pass - 3 :
( 20 10 40 50 80 ) -> ( 10 20 40 50 80 ) // Swap since 20 > 10.
( 10 20 40 50 80 ) -> ( 10 20 40 50 80 ) // Since these elements are already
in order (20 < 40), algorithm does not swap them.

In Pass - 3 total numbers compared are 2. After completion of Pass - 3 the third largest element is moved
to the third last position of the array.
Now, Pass - 4 can compare the first and second elements of the array.

Pass - 4 :

Page No:
( 10 20 40 50 80 ) -> ( 10 20 40 50 80 ) // Since these elements are already
in order (10 < 20), algorithm does not swap them.

In Pass - 4 total numbers compared are 1. After completion of Pass - 4 all the elements of the array are

ID: 208A1A05A6
sorted. So, the result is 10 20 40 50 80.

Write code to sort the array elements by using bubble sort technique.

Write a class BubbleSorting with a method bubbleSort(int[] array) . The method receives an
array of int type.

For example, if the array of elements 11, 15, 12, 10 are passed as arguments to the
bubbleSort(..) method, then the output should be:

10
11
12
15

Note: Make sure to use the println() method and not the print() method.

Note: Please don't change the package name.


Source Code:

q11039/BubbleSorting.java

package q11039;
import java.io.*;
import java.lang.System;
import java.util.Scanner;
public class BubbleSorting

2020-2024-CSE-A
{
public void bubbleSort(int arr[])
{
for(int i=0;i<arr.length;i++)
{
for(int j=i;j<arr.length;j++)
{ RISE Krishna Sai Prakasam Group of Institutions
if(arr[i]>arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}
Page No:
q11039/BubbleSortingMain.java

ID: 208A1A05A6
package q11039;
public class BubbleSortingMain{
public static void main(String[] args) {
int[] array = new int[args.length];
for (int i = 0; i < args.length; i++)
{
array[i] = Integer.parseInt(args[i]);
}
BubbleSorting bSorting = new BubbleSorting();
bSorting.bubbleSort(array);
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
10
20
30
50

Test Case - 2

2020-2024-CSE-A
User Output
9
17
18
19
20 RISE Krishna Sai Prakasam Group of Institutions
21
22
S.No: 6 Exp. Name: Write a Java program to Sort elements using Merge Sort Date: 2022-06-09

Aim:

Page No:
Write code to sort the array elements by using merge sort technique.

Write a class MyMergeSort with main method.

ID: 208A1A05A6
Note: Please don't change the package name.
Source Code:

q11043/MyMergeSort.java

package q11043;
import java.util.Scanner;
public class MyMergeSort {
private int[] array;
private int[] tempMergArr;
private int length;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter no of elements in the array: ");
int n = s.nextInt();
int[] inputArr = new int[n];
System.out.print("Enter elements in the array seperated by space: ");
for(int i = 0; i < n; i++) {
inputArr[i] = s.nextInt();
}
MyMergeSort mms = new MyMergeSort();
mms.sort(inputArr);

2020-2024-CSE-A
for(int i:inputArr){
System.out.print(i);
System.out.print(" ");
}
}
public void sort(int inputArr[]) {
this.array = inputArr; RISE Krishna Sai Prakasam Group of Institutions
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex) {
if(lowerIndex <higherIndex){
int middle=lowerIndex+(higherIndex-lowerIndex)/2;
doMergeSort(lowerIndex,middle);
doMergeSort(middle+1,higherIndex);
MyMergeSort(lowerIndex,middle,higherIndex);
}
}
private void MyMergeSort(int lowerIndex, int middle, int higherIndex) {
for(int i=lowerIndex;i<=higherIndex;i++){
tempMergArr[i]=array[i];
}
int i=lowerIndex;
int j=middle+1;

Page No:
int k=lowerIndex;
while(i<=middle && j<=higherIndex){
if(tempMergArr[i]<=tempMergArr[j]){
array[k]=tempMergArr[i];

ID: 208A1A05A6
i++;
}
else{
array[k]=tempMergArr[j];
j++;
}
k++;
}
while(i<=middle){
array[k]=tempMergArr[i];
k++;
i++;
}
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Enter no of elements in the array: 10
Enter elements in the array seperated by space: 45 23 11 89 77 98 4 28 65 43
4 11 23 28 43 45 65 77 89 98

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
Exp. Name: Write a Java program to Delete and Remove characters using
S.No: 7 Date: 2022-05-27
StringBuffer class

Page No:
Aim:
Write a class JavaStringBufferDelete with a main method to delete characters from a string using
StringBuffer class.

ID: 208A1A05A6
Follow the given instructions.
1. Consider a string "Hello India" and delete 0 to 6 characters in that and print the result.
2. Consider another string "Hello World", delete characters from position 0 to length of the entire string
and print the result.
3. Consider another string "Hello Java", remove 0th character and then print the result.

Note: Please don't change the package name.

Source Code:

q11215/JavaStringBufferDelete.java

package q11215;
class JavaStringBufferDelete{
public static void main(String args[]){
StringBuffer sb1=new StringBuffer("Hello India");
StringBuffer sb2=new StringBuffer("Hello World");
StringBuffer sb3=new StringBuffer("Hello Java");
sb1.delete(0,6);
System.out.println(sb1);
sb2.delete(0,11);
System.out.println(sb2);
sb3.deleteCharAt(0);
System.out.println(sb3);
}

2020-2024-CSE-A
}

Execution Results - All test cases have succeeded!

Test Case - 1
RISE Krishna Sai Prakasam Group of Institutions
User Output
India
ello Java
S.No: 8 Exp. Name: Write a Java program to implement a Class mechanism Date: 2022-05-13

Aim:

Page No:
Write a Java program with a class name Employee which contains the data members name (String), age
(int), designation (String), salary (double) and the methods setData(), displayData().

ID: 208A1A05A6
The member function setData() is used to initialize the data members and displayData() is used to display
the given employee data.

Write the main() method with in the class which will receive four arguments as name, age, designationand
salary.

Create an object to the class Employee within the main(), call setData() with arguments and finally call
the method displayData() to print the output.

If the input is given as command line arguments to the main() as "Saraswathi", "27", "Teacher", "37250"
then the program should print the output as:

Name : Saraswathi
Age : 27
Designation : Teacher
Salary : 37250.0

Note: Please don't change the package name.


Source Code:

q11115/Employee.java

package q11115;
class Employee
{

2020-2024-CSE-A
String name;
int age;
String designation;
double salary;
public void setData(String nm,int ag,String desg,double sal)
{
name=nm; RISE Krishna Sai Prakasam Group of Institutions
age=ag;
designation=desg;
salary=sal;
}
public void displayData()
{
System.out.println("Name : "+name);
System.out.println("Age : "+age);
System.out.println("Designation : "+designation);
System.out.println("Salary : "+salary);
}
public static void main(String[] args)
{
String name=args[0];
int age=Integer.parseInt(args[1]);
String designation=args[2];
double salary=Double.parseDouble(args[3]);
Employee e=new Employee();
e.setData(name,age,designation,salary);

Page No:
e.displayData();
}
}

ID: 208A1A05A6
Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Name : Ram
Age : 25
Designation : Team member
Salary : 25000.0

Test Case - 2

User Output
Name : Ravi
Age : 36
Designation : TeamLead
Salary : 35000.0

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 9 Exp. Name: Write a Java program to implement a Constructor Date: 2022-05-13

Aim:

Page No:
Write a Java program with a class name Staff , contains the data members id (int), name (String) which
are initialized with a parameterized constructor and the method show().

ID: 208A1A05A6
The member function show() is used to display the given staff data.

Write the main() method with in the class which will receive two arguments as id and name.

Create an object to the class Staff with arguments id and name within the main(), and finally call the
method show() to print the output.

If the input is given as command line arguments to the main() as "18", "Gayatri" then the program should
print the output as:

Id : 18
Name : Gayatri

Note: Please don't change the package name.


Source Code:

q11116/Staff.java

package q11116;
import java.io.*;
import java.lang.*;
class Staff
{
int id;
String name;

2020-2024-CSE-A
Staff(int sid,String sname)
{
id=sid;
name=sname;
}
public void show()
{ RISE Krishna Sai Prakasam Group of Institutions
System.out.println("Id : "+id);
System.out.println("Name : "+name);
}
public static void main(String args[])
{
int id=Integer.parseInt(args[0]);
//String n=args[1];
Staff s = new Staff(id,args[1]);
s.show();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output

Page No:
Id : 18
Name : Gayatri

ID: 208A1A05A6
Test Case - 2

User Output
Id : 45
Name : Akbar

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 10 Exp. Name: Write a Java program to implement Constructor overloading Date: 2022-06-11

Aim:

Page No:
Write a class Box which contains the data members width, height and depth all of type double.

Write the implementation for the below 3 overloaded constructors in the class Box :

ID: 208A1A05A6
Box() - default constructor which initializes all the members with -1
Box(length) - parameterized constructor with one argument and initialize all the members with the
value in length
the members with the corresponding arguments
Box(width, height, depth) - parameterized constructor with three arguments and initialize

Write a method public double volume() in the class Box to find out the volume of the given box.

Write the main method within the Box class and assume that it will receive either zero arguments, or one
argument or three arguments.

For example, if the main() method is passed zero arguments then the program should print the output as:

Volume of Box() is : -1.0

Similarly, if the main() method is passed one argument : 2.34, then the program should print the output as:

Volume of Box(2.34) is : 12.812903999999998

then the program should print the output as: Likewise, if the main() method is passed three arguments :
2.34, 3.45, 1.59, then the program should print the output as:

Volume of Box(2.34, 3.45, 1.59) is : 12.836070000000001

Note: Please don't change the package name.

Source Code:

2020-2024-CSE-A
q11267/Box.java

package q11267;
import java.io.*;
class Box{
double width,height,depth; RISE Krishna Sai Prakasam Group of Institutions
Box(){
width=-1;
height=-1;
depth=-1;
}
Box(double len){
width=len;
height=len;
depth=len;
}
Box(double len,double wid,double hei){
width=len;
height=wid;
depth=hei;
}
public double volume(){
return width*height*depth;
}

Page No:
public void display(){
if(depth==-1 && width==-1 && height==-1){
System.out.println("Volume of Box() is : "+volume());
}

ID: 208A1A05A6
else if(width!=-1 && width==height && width==depth){
System.out.println("Volume of Box("+height+") is : "+volume());
}
else{
System.out.println("Volume of Box("+width+", "+height+", "+depth+") is
: "+volume());
}
}
public static void main(String args[]){
double []arr=new double[3];
for(int i=0;i<args.length;i++){
arr[i]=Double.parseDouble(args[i]);
}
if(arr[0]==0){
Box b=new Box();
b.display();
}
else if(arr[1]==0){
Box b=new Box(arr[0]);
b.display();
}
else{
Box b=new Box(arr[0],arr[1],arr[2]);
b.display();
}
}

2020-2024-CSE-A
}

Execution Results - All test cases have succeeded!

Test Case - 1
RISE Krishna Sai Prakasam Group of Institutions
User Output
Volume of Box() is : -1.0

Test Case - 2

User Output
Volume of Box(3.0) is : 27.0
S.No: 11 Exp. Name: Write a Java program to implement Method overloading Date: 2022-05-13

Aim:

Page No:
Write a Java program with a class name Addition with the methods add(int, int) ,
add(int, float) , add(float, float) and add(float, double, double) to add values of
different argument types.

ID: 208A1A05A6
Write the main(String[]) method within the class and assume that it will always receive a total of 6
command line arguments at least, such that the first 2 are int, next 2 are float and the last 2 are of type
double.

If the main() is provided with arguments : 1, 2, 1.5f, 2.5f, 1.0, 2.0 then the program should print the output
as:

Sum of 1 and 2 : 3
Sum of 1.5 and 2.5 : 4.0
Sum of 2 and 2.5 : 4.5
Sum of 1.5, 1.0 and 2.0 : 4.5

Note: Please don't change the package name.


Source Code:

q11266/Addition.java

package q11266;
class Addition
{ int a,b;
float c,d;
double e,f;
public int add(int a,int b)
{

2020-2024-CSE-A
return a+b;
}
public float add(int b,float d)
{
return b+d;
}
public float add(float c,float d) RISE Krishna Sai Prakasam Group of Institutions
{
return c+d;
}
public double add(float c,double e,double f)
{
return c+e+f;
}
public void display(int a,int b)
{
System.out.println("Sum of "+a+" and "+b+" : "+add(a,b));
}
public void display(float c,float d)
{
System.out.println("Sum of "+c+" and "+d+" : "+add(c,d));
}
public void display(int b,float d)
{
System.out.println("Sum of "+b+" and "+d+" : "+add(b,d));
}

Page No:
public void display(float c,double e,double f)
{
System.out.println("Sum of "+c+", "+e+" and "+f+" : "+add(c,e,f));
}

ID: 208A1A05A6
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
float c=Float.parseFloat(args[2]);
float d=Float.parseFloat(args[3]);
double e=Double.parseDouble(args[4]);
double f=Double.parseDouble(args[5]);
Addition h=new Addition();
h.add(a,b);
h.add(c,d);
h.add(b,d);
h.add(c,e,f);
h.display(a,b);
h.display(c,d);
h.display(b,d);
h.display(c,e,f);
}

Execution Results - All test cases have succeeded!

Test Case - 1

2020-2024-CSE-A
User Output
Sum of 2 and 1 : 3
Sum of 5.0 and 3.6 : 8.6
Sum of 1 and 3.6 : 4.6
Sum of 5.0, 9.2 and 5.26 : 19.46
RISE Krishna Sai Prakasam Group of Institutions
S.No: 12 Exp. Name: Write a Java program to implement Single Inheritance Date: 2022-05-27

Aim:

Page No:
Write a Java program to illustrate the single inheritance concept.

Create a class Marks

ID: 208A1A05A6
contains the data members id of int data type, javaMarks, cMarks and cppMarks of float data type
write a method setMarks() to initialize the data members
write a method displayMarks() which will display the given data

Create another class Result which is derived from the class Marks
contains the data members total and avg of float data type
write a method compute() to find total and average of the given marks
write a method showResult() which will display the total and avg marks

Write a class SingleInheritanceDemo with main() method it receives four arguments as id, javaMarks,
cMarks and cppMarks.

Create object only to the class Result to access the methods.

If the input is given as command line arguments to the main() as "101", "45.50", "67.75", "72.25" then the
program should print the output as:

Id : 101
Java marks : 45.5
C marks : 67.75
Cpp marks : 72.25
Total : 185.5
Avg : 61.833332

Note: While computing the total marks add the marks in the following order only javaMarks, cMarks and
cppMarks

Source Code:

2020-2024-CSE-A
q11263/SingleInheritanceDemo.java

package q11263;
class Marks{
int id;
float javam,cm,cpm; RISE Krishna Sai Prakasam Group of Institutions
public void setMarks(int i,float j,float c,float cp){
id=i;
javam=j;
cm=c;
cpm=cp;
}
public void displayMarks(){
System.out.println("Id : "+id);
System.out.println("Java marks : "+javam);
System.out.println("C marks : "+cm);
System.out.println("Cpp marks : "+cpm);
}
}
class Result extends Marks{
float tot,avg;
public void compute()
{
tot=super.javam+super.cm+super.cpm;

Page No:
avg=tot/3;
}
public void showResult()
{

ID: 208A1A05A6
System.out.println("Total : "+tot);
System.out.println("Avg : "+avg);
}
}
class SingleInheritanceDemo{
public static void main(String args[]){
int id=Integer.parseInt(args[0]);
float javam=Float.parseFloat(args[1]);
float cm=Float.parseFloat(args[2]);
float cpm=Float.parseFloat(args[3]);
Result r=new Result();
r.setMarks(id, javam, cm, cpm);
r.displayMarks();
r.compute();
r.showResult();
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Id : 102

2020-2024-CSE-A
Java marks : 35.6
C marks : 45.0
Cpp marks : 65.5
Total : 146.1
Avg : 48.7

RISE Krishna Sai Prakasam Group of Institutions


Test Case - 2

User Output
Id : 101
Java marks : 45.5
C marks : 67.75
Cpp marks : 72.25
Total : 185.5
Avg : 61.833332

Test Case - 3

User Output
Id : 103
Test Case - 3
Java marks : 50.5
C marks : 46.8

Page No:
Cpp marks : 52.65
Total : 149.95001
Avg : 49.983337

ID: 208A1A05A6
2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 13 Exp. Name: Write a Java program to implement Multilevel Inheritance Date: 2022-05-28

Aim:

Page No:
Write a Java program to illustrate the multilevel inheritance concept.

Create a class Student

ID: 208A1A05A6
contains the data members id of int data type and name of string type
write a method setData() to initialize the data members
write a method displayData() which will display the given id and name

Create a class Marks which is derived from the class Student


contains the data members javaMarks, cMarks and cppMarks of float data type
write a method setMarks() to initialize the data members
write a method displayMarks() which will display the given data

Create another class Result which is derived from the class Marks
contains the data members total and avg of float data type
write a method compute() to find total and average of the given marks
write a method showResult() which will display the total and avg marks

Write a class MultilevelInheritanceDemo with the main() method which will receive five arguments
as id, name, javaMarks, cMarks and cppMarks.

Create object only to the class Result to access the methods.

If the input is given as command line arguments to the main() as "99", "Lakshmi", "55.5", "78.5", "72" then
the program should print the output as:

Id : 99
Name : Lakshmi
Java marks : 55.5
C marks : 78.5
Cpp marks : 72.0
Total : 206.0
Avg : 68.666664

2020-2024-CSE-A
Note: Please don't change the package name.

Source Code:
RISE Krishna Sai Prakasam Group of Institutions
q11264/MultilevelInheritanceDemo.java

package q11264;
class Student{
int id;
String name;
public void setData(int i,String nm){
id=i;
name=nm;
}
public void displayData(){
System.out.println("Id : "+id);
System.out.println("Name : "+name);
}
}
class Marks extends Student{
float javam,cm,cpm;
public void setMarks(float jvm,float c,float cp){
javam=jvm;

Page No:
cm=c;
cpm=cp;
}
public void displayMarks(){

ID: 208A1A05A6
System.out.println("Java marks : "+javam);
System.out.println("C marks : "+cm);
System.out.println("Cpp marks : "+cpm);
}
}
class Result extends Marks{
float total,avg;
public void compute(){
total=javam+cm+cpm;
avg=total/3;
}
public void showResult(){
System.out.println("Total : "+total);
System.out.println("Avg : "+avg);
}
}
class MultilevelInheritanceDemo{
public static void main(String args[]){
int id=Integer.parseInt(args[0]);
String name=args[1];
float javam=Float.parseFloat(args[2]);
float cm=Float.parseFloat(args[3]);
float cpm=Float.parseFloat(args[4]);
Result r= new Result();
r.setData(id,name);
r.displayData();

2020-2024-CSE-A
r.setMarks(javam,cm,cpm);
r.displayMarks();
r.compute();
r.showResult();

}
}
RISE Krishna Sai Prakasam Group of Institutions

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Id : 99
Name : Geetha
Java marks : 56.0
C marks : 75.5
Cpp marks : 66.6
Test Case - 1
Total : 198.1
Avg : 66.03333

Page No:
Test Case - 2

User Output

ID: 208A1A05A6
Id : 199
Name : Lakshmi
Java marks : 55.5
C marks : 78.5
Cpp marks : 78.0
Total : 212.0
Avg : 70.666664

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
Exp. Name: Write a Java program to find Areas of different Shapes using abstract
S.No: 14 Date: 2022-06-09
class

Page No:
Aim:
Write a Java program to illustrate the abstract class concept.

ID: 208A1A05A6
Create an abstract class CalcArea and declare the methods triangleArea(double b, double h),
rectangleArea(double l, double b), squareArea(double s), circleArea(double r).

Create a class FindArea which extends the abstract class CalcArea used to find areas of triangle,
rectangle, square, circle.

Write a class Area with the main() method which will receive two arguments and convert them to double
type.

If the input is given as command line arguments to the main() as "1.2","2.7" then the program should print
the output as:

Area of triangle : 1.62


Area of rectangle : 3.24
Area of square : 1.44
Area of circle : 22.890600000000006

Note: Please don't change the package name.

Source Code:

q11286/Area.java

package q11286;
import static java.lang.System.*;
abstract class CalcArea{

2020-2024-CSE-A
abstract void triangleArea(double d,double h);
abstract void rectangleArea(double l,double b);
abstract void squareArea(double s);
abstract void circleArea(double r);
}
class FindArea extends Area{
void triangleArea(double b,double h){
RISE Krishna Sai Prakasam Group of Institutions
double area=(b*h)/2;
System.out.println("Area of triangle : "+area);
}
void rectangleArea(double l,double w){
double area=l*w;
System.out.println("Area of rectangle : "+area);
}
void squareArea(double s){
double area=s*s;
System.out.println("Area of square : "+area);
}
void circleArea(double r){
double area=3.14*r*r;
System.out.println("Area of circle : "+area);
}
}

public class Area {


public static void main(String args[]) {

Page No:
double l,w,b,h,r,s;
l=Double.parseDouble(args[0]);
h=Double.parseDouble(args[1]);
b=Double.parseDouble(args[0]);

ID: 208A1A05A6
w=Double.parseDouble(args[1]);
r=Double.parseDouble(args[1]);
s=Double.parseDouble(args[0]);
FindArea area=new FindArea();
area.triangleArea(b,h);
area.rectangleArea(l,w);
area.squareArea(s);
area.circleArea(r);
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Area of triangle : 7.529400000000001
Area of rectangle : 15.058800000000002
Area of square : 12.6736
Area of circle : 56.18370600000001

Test Case - 2

User Output

2020-2024-CSE-A
Area of triangle : 83.14375000000001
Area of rectangle : 166.28750000000002
Area of square : 157.50250000000003
Area of circle : 551.26625

Test Case - 3 RISE Krishna Sai Prakasam Group of Institutions

User Output
Area of triangle : 4.0
Area of rectangle : 8.0
Area of square : 4.0
Area of circle : 50.24
S.No: 15 Exp. Name: Write a Java program to illustrate super keyword Date: 2022-05-02

Aim:

Page No:
Write a Java program to illustrate the usage of super keyword.

Create a class called Animal with the below members:

ID: 208A1A05A6
a constructor which prints Animal is created
a method called eat() which will print Eating something and returns nothing.

Create another class called Dog which is derived from the class Animal , and has the below members:
a constructor which calls super() and then prints Dog is created
a method eat() which will print Eating bread and returns nothing
a method bark() which will print Barking and returns nothing
a method work() which will call eat() of the superclass first and then the eat() method in the current
class, followed by the bark() method in the current class.

Write a class ExampleOnSuper with the main() method, create an object to Dog which calls the method
work().

Note: Please don't change the package name.


Source Code:

q11273/ExampleOnSuper.java

package q11273;
import static java.lang.System.*;
class Animal
{
public Animal()
{
out.println("Animal is created");

}
void eat()

2020-2024-CSE-A
{
out.println("Eating something");
}

}
class Dog extends Animal
{ RISE Krishna Sai Prakasam Group of Institutions
public Dog()
{
super();
out.println("Dog is created");
}
void eat()
{
out.println("Eating bread");
}
void bark()
{
out.println("Barking");

}
void work()
{
super.eat();
eat();

Page No:
bark();
}
}
public class ExampleOnSuper {

ID: 208A1A05A6
public static void main(String args[]) {
Dog d = new Dog();
d.work();
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Animal is created
Dog is created
Eating something
Eating bread
Barking

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 16 Exp. Name: Write a Java program to implement Interface Date: 2022-06-09

Aim:

Page No:
Write a Java program that implements an interface.

Create an interface called Car with two abstract methods String getName() and

ID: 208A1A05A6
int getMaxSpeed() . Also declare one default method void applyBreak() which has the code
snippet

System.out.println("Applying break on " + getName());

In the same interface include a static method Car getFastestCar(Car car1, Car car2) , which
returns car1 if the maxSpeed of car1 is greater than or equal to that of car2, else should return car2.

Create a class called BMW which implements the interface Car and provides the implementation for the
abstract methods getName() and getMaxSpeed() (make sure to declare the appropriate fields to store
name and maxSpeed and also the constructor to initialize them).

Similarly, create a class called Audi which implements the interface Car and provides the
implementation for the abstract methods getName() and getMaxSpeed() (make sure to declare the
appropriate fields to store name and maxSpeed and also the constructor to initialize them).

Create a public class called MainApp with the main() method.


Take the input from the command line arguments. Create objects for the classes BMW and Audi then
print the fastest car.

Note:
Java 8 introduced a new feature called default methods or defender methods, which allow
developers to add new methods to the interfaces without breaking the existing implementation of these
interface. These default methods can also be overridden in the implementing classes or made abstract in
the extending interfaces. If they are not overridden, their implementation will be shared by all the
implementing classes or sub interfaces.

2020-2024-CSE-A
Below is the syntax for declaring a default method in an interface :

public default void methodName() {


System.out.println("This is a default method in interface");
}

RISE Krishna Sai Prakasam Group of Institutions


Similarly, Java 8 also introduced static methods inside interfaces, which act as regular static methods
in classes. These allow developers group the utility functions along with the interfaces instead of defining
them in a separate helper class.

Below is the syntax for declaring a static method in an interface :

public static void methodName() {


System.out.println("This is a static method in interface");
}

Note: Please don't change the package name.


Source Code:
q11284/MainApp.java

package q11284;

Page No:
interface Car
{
String getName();
int getMaxSpeed();

ID: 208A1A05A6
default void applyBreak()
{
System.out.println("Applying break on "+getName());
}
public static Car getFastestCar(Car car1,Car car2)
{
return car1.getMaxSpeed()>car2.getMaxSpeed()?car1:car2;
}
}
class BMW implements Car
{
protected int maxSpeed;
protected String name;
BMW(int speed,String name)
{
this.maxSpeed=speed;
this.name=name;
}
public String getName(){
return name;
}
public int getMaxSpeed(){
return maxSpeed;
}

}
class Audi implements Car

2020-2024-CSE-A
{
protected String name;
protected int maxSpeed;
Audi(int speed,String name)
{
this.maxSpeed=speed;
this.name=name; RISE Krishna Sai Prakasam Group of Institutions
}
public String getName(){
return name;
}
public int getMaxSpeed(){
return maxSpeed;
}
}
public class MainApp {
public static void main(String args[])
{
BMW b=new BMW(Integer.parseInt(args[1]),args[0]);
Audi a=new Audi(Integer.parseInt(args[3]),args[2]);
System.out.println("Fastest car is : "+Car.getFastestCar(b, a).getName());
}
}

Page No:
Execution Results - All test cases have succeeded!

Test Case - 1

ID: 208A1A05A6
User Output
Fastest car is : BMW

Test Case - 2

User Output
Fastest car is : Maruthi

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
Exp. Name: A java program to demonstrate that the catch block for type Exception A
S.No: 17 Date: 2022-06-09
catches the exception of type Exception B and Exception C.

Page No:
Aim:
Use inheritance to create an exception superclass called Exception A and exception subclasses Exception
B and Exception C, where Exception B inherits from Exception A and Exception C inherits from Exception B.

ID: 208A1A05A6
Write a java program to demonstrate that the catch block for type Exception A catches the exception of
type Exception B and Exception C.

Note: Please don't change the package name.

Source Code:

q29793/TestException.java

package q29793;
import java.lang.*;
@SuppressWarnings("serial")
class ExceptionA extends Exception {
String message;
public ExceptionA(String message) {
this.message = message;
}
}
@SuppressWarnings("serial")
class ExceptionB extends ExceptionA {
ExceptionB(String message){
super(message);
}
}
@SuppressWarnings("serial")
class ExceptionC extends ExceptionB {

2020-2024-CSE-A
ExceptionC(String message){
super(message);
}
}
@SuppressWarnings("serial")
public class TestException {
public static void main(String[] args) { RISE Krishna Sai Prakasam Group of Institutions
try {
getExceptionB();
}
catch(ExceptionA ea) {
System.out.println("Got exception from Exception B");
}
try {
getExceptionC();
}
catch(ExceptionA ea) {
System.out.println("Got exception from Exception C");
}
}
public static void getExceptionB() throws ExceptionB {
throw new ExceptionB("Exception B");
}
public static void getExceptionC() throws ExceptionC {
throw new ExceptionC("Exception C");
}

Page No:
}

ID: 208A1A05A6
Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Got exception from Exception B
Got exception from Exception C

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 18 Exp. Name: Write a Java program to illustrate Multiple catch blocks Date: 2022-06-09

Aim:

Page No:
Write a Java program to illustrate multiple catch blocks in exception handling.

Write a method multiCatch(int[] arr, int index) in the class MultiCatchBlocks where arr contains

ID: 208A1A05A6
integer array values and index contains an integer value.

Write the code in try block to print the value of arr[index] and also print the division value of arr[index] by
index.

Write the catch blocks for


1. ArithmeticException will print "Division by zero exception occurred"
2. ArrayIndexOutOfBoundsException will print "Array index out of bounds exception occurred".
3. Exception (which catches all exceptions) will print "Exception occurred"

Note: Please don't change the package name.


Source Code:

q11331/MultiCatchBlocks.java

package q11331;
public class MultiCatchBlocks {
public void multiCatch(int arr[],int index){
try{
System.out.println(arr[index]);
System.out.println(arr[index]/index);
}
catch(ArithmeticException ae){
System.out.println("Division by zero exception occurred");
}

2020-2024-CSE-A
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index out of bounds exception occurred");
}
catch(Exception e){
System.out.println("Exception occured");
}
}
RISE Krishna Sai Prakasam Group of Institutions
}

q11331/MultiCatchBlocksMain.java

package q11331;
import java.util.Scanner;
public class MultiCatchBlocksMain {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter no of elements in the array:");
int n = s.nextInt();
int[] arr = new int[n];
System.out.println("Enter elements in the array seperated by space:");
for(int i = 0; i < n; i++)
{
arr[i] = s.nextInt();
}

Page No:
System.out.println("Enter the index element:");
int x = s.nextInt();

MultiCatchBlocks mb = new MultiCatchBlocks();

ID: 208A1A05A6
mb.multiCatch(arr, x);
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Enter no of elements in the array: 3
Enter elements in the array seperated by space: 1 2 3
Enter the index element: 3
Array index out of bounds exception occurred

Test Case - 2

User Output
Enter no of elements in the array: 3
Enter elements in the array seperated by space: 6 5 4
Enter the index element: 1
5
5

2020-2024-CSE-A
Test Case - 3

User Output
Enter no of elements in the array: 3
Enter elements in the array seperated by space: 6 8 4
Enter the index element: 0
6 RISE Krishna Sai Prakasam Group of Institutions

Division by zero exception occurred

Test Case - 4

User Output
Enter no of elements in the array: 4
Enter elements in the array seperated by space: 1
2 2
3 3
4 4
Enter the index element: 0
1
Division by zero exception occurred
Test Case - 5

User Output

Page No:
Enter no of elements in the array: 4
Enter elements in the array seperated by space: 1
2 2
3 3

ID: 208A1A05A6
4 4
Enter the index element: 5
Array index out of bounds exception occurred

Test Case - 6

User Output
Enter no of elements in the array: 5
Enter elements in the array seperated by space: 1
2 2
3 3
4 4
5 5
Enter the index element: 2
3
1

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 19 Exp. Name: Write a Java program that implements Runtime Polymorphism Date: 2022-05-19

Aim:

Page No:
Write a Java program that implements runtime polymorphism.

Create a class Animal with one method whoAmI() which will print I am a generic animal.

ID: 208A1A05A6
Create another class Dog which extends Animal , which will print I am a dog.

Create another class Cow which extends Animal , which will print I am a cow.

Create another class Snake which extends Animal , which will print I am a snake.

Write a class RuntimePolymorphismDemo with the main() method, create objects to all the classes
Animal , Dog , Cow , Snake and call whoAmI() with each object.

Note: Please don't change the package name.


Source Code:

q11277/RuntimePolymorphismDemo.java

package q11277;
public class RuntimePolymorphismDemo {
public static void main(String[] args) {
Animal ref1 = new Animal();
Animal ref2 = new Dog();
Animal ref3 = new Cow();
Animal ref4 = new Snake();
ref1.whoAmI();
ref2.whoAmI();
ref3.whoAmI();
ref4.whoAmI();
}

2020-2024-CSE-A
}

class Animal{
public void whoAmI(){
System.out.println("I am a generic animal");
}
} RISE Krishna Sai Prakasam Group of Institutions
class Dog extends Animal{
public void whoAmI(){
System.out.println("I am a dog");
}
}
class Cow extends Animal{
public void whoAmI(){
System.out.println("I am a cow");
}
}
class Snake extends Animal{
public void whoAmI(){
System.out.println("I am a snake");
}
}

Page No:
Execution Results - All test cases have succeeded!

Test Case - 1

ID: 208A1A05A6
User Output
I am a generic animal
I am a dog
I am a cow
I am a snake

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 20 Exp. Name: Write a Java program for creation of illustrating throw Date: 2022-06-09

Aim:

Page No:
Write a Java program for creation of illustrating throw.

Write a class ThrowExample contains a method checkEligibilty(int age, int weight) which throws an

ID: 208A1A05A6
ArithmeticException with a message "Student is not eligible for registration" when age < 12 and weight <
40, otherwise it prints "Student Entry is Valid!!".

Write the main() method in the same class which will receive two arguments as age and weight, convert
them into integers.

For example, if the given data is 9 and 35 then the output should be:

Welcome to the Registration process!!


java.lang.ArithmeticException: Student is not eligible for registration

For example, if the given data is 15 and 41 then the output should be:

Welcome to the Registration process!!


Student Entry is Valid!!
Have a nice day

Note: Please don't change the package name.


Source Code:

q11335/ThrowExample.java

package q11335;
public class ThrowExample {
public static void main(String args[]) {

2020-2024-CSE-A
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
System.out.println("Welcome to the Registration process!!");
try {
checkEligibilty(a,b);
System.out.println("Have a nice day");
}
RISE Krishna Sai Prakasam Group of Institutions
catch(ArithmeticException ae) {
System.out.println("java.lang.ArithmeticException: Student is not eligi
ble for registration");
}
}
static void checkEligibilty(int age, int weight) {
if(age<12 && weight<40) {
throw new ArithmeticException("Student is not eligible for registratio
n");
}
else {
System.out.println("Student Entry is Valid!!");
}
}
}
Execution Results - All test cases have succeeded!

Page No:
Test Case - 1

User Output

ID: 208A1A05A6
Welcome to the Registration process!!
java.lang.ArithmeticException: Student is not eligible for registration

Test Case - 2

User Output
Welcome to the Registration process!!
Student Entry is Valid!!
Have a nice day

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 21 Exp. Name: Write a Java program to illustrate Finally block Date: 2022-06-09

Aim:

Page No:
Write a Java program to handle an ArithmeticException divided by zero by using try, catch and finally
blocks.

ID: 208A1A05A6
Write the main() method with in the class MyFinallyBlock which will receive four arguments and
convert the first two into integers, the last two into float values.

Write the try, catch and finally blocks separately for finding division of two integers and two float values.

If the input is given as command line arguments to the main() as "10", "4", "10", "4" then the program
should print the output as:

Result of integer values division : 2


Inside the 1st finally block
Result of float values division : 2.5
Inside the 2nd finally block

If the input is given as command line arguments to the main() as "5", "0", "3.8", "0.0" then the program
should print the output as:

Inside the 1st catch block


Inside the 1st finally block
Result of float values division : Infinity
Inside the 2nd finally block

Note: Please don't change the package name.


Source Code:

q11330/MyFinallyBlock.java

2020-2024-CSE-A
package q11330;
public class MyFinallyBlock {
public static void main(String args[]){
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
float c=Float.parseFloat(args[2]);
RISE Krishna Sai Prakasam Group of Institutions
float d=Float.parseFloat(args[3]);
try{
System.out.println("Result of integer values division : "+(a/b));
}
catch(ArithmeticException ae){
System.out.println("Inside the 1st catch block");
}
finally{
System.out.println("Inside the 1st finally block");
}
try{
System.out.println("Result of float values division : "+(c/d));
}
catch(ArithmeticException ae){
System.out.println("Inside the 2nd catch block");
}
finally{
System.out.println("Inside the 2nd finally block");
}

Page No:
}
}

ID: 208A1A05A6
Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Result of integer values division : 2
Inside the 1st finally block
Result of float values division : 0.8333333
Inside the 2nd finally block

Test Case - 2

User Output
Inside the 1st catch block
Inside the 1st finally block
Result of float values division : 2.8666668
Inside the 2nd finally block

Test Case - 3

User Output
Inside the 1st catch block
Inside the 1st finally block
Result of float values division : Infinity

2020-2024-CSE-A
Inside the 2nd finally block

RISE Krishna Sai Prakasam Group of Institutions


S.No: 22 Exp. Name: Write a Java program to handle an ArithmeticException - divided by zero Date: 2022-06-02

Aim:

Page No:
Write a Java program to handle an ArithmeticException divide by zero using exception handling.

Write a class called Division with a main() method. Assume that the main() method will receive two

ID: 208A1A05A6
arguments which have to be internally converted to integers.

Write code in the main() method to divide the first argument by the second (as integers) and print the result
(i.e the quotient).

If the command line arguments to the main() method are "12", "3", then the program should print the output
as:

Result = 4

If the command line arguments to the main() method are "55", "0", then the program should print the
output as:

Exception caught : divide by zero occurred

Note: Please don't change the package name.


Source Code:

q11329/Division.java

package q11329;
class Division{
public static void main(String args[]){
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);

2020-2024-CSE-A
int c;
try{
c=a/b;
System.out.println("Result = "+c);
}
catch(ArithmeticException e){
System.out.println("Exception caught : divide by zero occurred");
RISE Krishna Sai Prakasam Group of Institutions

}
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Result = 4
User Output
Test Case - 2

Exception caught : divide by zero occurred

ID: 208A1A05A6 Page No:


RISE Krishna Sai Prakasam Group of Institutions 2020-2024-CSE-A
S.No: 23 Exp. Name: Write a Java program to illustrate User-defined Exceptions Date: 2022-06-09

Aim:

Page No:
Write a Java program to illustrate user-defined exceptions.

Write the class InsufficientFundsException with

ID: 208A1A05A6
private double member amount
a parameterized constructor to initialize the amount
a method getAmount() to return amount.

Write another class CheckingAccount with


two private members balance and accountNumber
a parameterized constructor to initialize the accountNumber
method deposit() to add amount to the balance
method withdraw() to debit amount from balance if sufficient balance is available, otherwise throw
an exception InsufficientFundsException() with how much amount needed extra
method getBalance() to return balance.
method getNumber() to return accountNumber.

Note: Please don't change the package name.

Source Code:

q11337/BankDemo.java

package q11337;
public class BankDemo {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(1001);
System.out.println("Depositing $1000...");
c.deposit(1000.00);
try {
System.out.println("Withdrawing $700...");

2020-2024-CSE-A
c.withdraw(700.00);
System.out.println("Withdrawing $600...");
c.withdraw(600.00);
}
catch (InsufficientFundsException e) {
System.out.println("Sorry, short of $" + e.getAmount() + " in the accou
nt number " + c.getNumber()); RISE Krishna Sai Prakasam Group of Institutions
}
}
}
class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
this.amount=amount;
}
public double getAmount() {
return amount;
}
}
class CheckingAccount {
private double balance;
private int accountNumber;
public CheckingAccount(int number) {
accountNumber=number;
}

Page No:
public void deposit(double amount) {
balance+=amount;
}
public void withdraw(double amount) throws InsufficientFundsException {

ID: 208A1A05A6
if(amount<balance) {
balance-=amount;
} else {
throw new InsufficientFundsException(balance);
}
}
public double getBalance() {
return balance;
}
public int getNumber() {
return accountNumber;
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Depositing $1000...
Withdrawing $700...
Withdrawing $600...
Sorry, short of $300.0 in the account number 1001

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 24 Exp. Name: Write a Java program demonstrating the usage of Threads Date: 2022-06-13

Aim:

Page No:
Write a Java program that uses three threads to perform the below actions:
1. First thread should print "Good morning" for every 1 second for 2 times
2. Second thread should print "Hello" for every 1 seconds for 2 times

ID: 208A1A05A6
3. Third thread should print "Welcome" for every 3 seconds for 1 times

Write appropriate constructor in the Printer class which implements Runnable interface to take three
arguments : message, delay and count of types String, int and int respectively.

Write code in the Printer.run() method to print the message with appropriate delay and for number
of times mentioned in count.

Write a class called ThreadDemo with the main() method which instantiates and executes three
instances of the above mentioned Printer class as threads to produce the desired output.

[Note: If you want to sleep for 2 seconds you should call Thread.sleep(2000); as the
Thread.sleep(...) method takes milliseconds as argument.]

Note: Please don't change the package name.


Source Code:

q11349/ThreadDemo.java

package q11349;
public class ThreadDemo {
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new Printer("Good morning", 1, 2));
Thread t2 = new Thread(new Printer("Hello", 1, 2));
Thread t3 = new Thread(new Printer("Welcome", 3, 1));
t1.start();
t2.start();

2020-2024-CSE-A
t3.start();
t1.join();
t2.join();
t3.join();
System.out.println("All the three threads t1, t2 and t3 have completed exe
cution.");
} RISE Krishna Sai Prakasam Group of Institutions
}
class Printer implements Runnable {
String msg;
int de,ti;
public Printer(String msg,int d,int t)
{
this.msg=msg;
de=d;
ti=t;
}
public void run()
{
try
{
for(int i=1;i<=ti;i++)
{
System.out.println(msg);
Thread.sleep(de*1000);
}

Page No:
}
catch(Exception e)
{
e.printStackTrace();

ID: 208A1A05A6
}
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Good morning
Hello
Welcome
Good morning
Hello
All the three threads t1, t2 and t3 have completed execution.

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 25 Exp. Name: Write a Java program to illustrates isAlive() and join() Date: 2022-06-09

Aim:

Page No:
Write a Java program to demonstrate the usage of isAlive() and join() methods in threads.

Write a class JoinThreadDemo with a main() method that creates and executes two instances of

ID: 208A1A05A6
Counter class which implements Runnable interface.

Let the Counter class take a String argument name and let its run() method print that message for 10
times along with the current count as given below:

System.out.println(name + " : " + i);

The JoinThreadDemo.main() method should perform the below tasks in the given order :
1. Create the first instance of thread as t1 with an instance of Counter class using "Spain" as the
argument.
2. Create the second instance of thread as t2 with an instance of Counter class using "UAE" as
the argument.
3. Print the isAlive() status of t1 as : "t1 before start t1.isAlive() : " + t1.isAlive().
4. Print the isAlive() status of t1 as : "t2 before start t2.isAlive() : " + t2.isAlive().
5. Start t1 and t2 threads respectively.
6. Print a message to the console as : "started t1 and t2 threads".
7. Print the isAlive() status of t1 as : "t1 after start t1.isAlive() : " + t1.isAlive().
8. Invoke the join() method on t2 .
9. Print the isAlive() status of t1 as : "t2 after start t2.isAlive() : " + t2.isAlive().

Note: Please don't change the package name.


Source Code:

q11350/JoinThreadDemo.java

2020-2024-CSE-A
package q11350;
public class JoinThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread t1 =new Thread(new Counter("Spain"));
Thread t2 =new Thread(new Counter("UAE"));
System.out.println("t1 before start t1.isAlive() : "+t1.isAlive());
System.out.println("t2 before start t2.isAlive() : "+t2.isAlive()); RISE Krishna Sai Prakasam Group of Institutions
t1.start();
t2.start();
System.out.println("started t1 and t2 threads");
System.out.println("t1 after start t1.isAlive() : "+t1.isAlive());
t2.join();
System.out.println("t2 after start t2.isAlive() : "+t2.isAlive());
}
}
class Counter implements Runnable {
private String name;
public Counter(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(name + " : " + i);
}
}

Page No:
}

ID: 208A1A05A6
Execution Results - All test cases have succeeded!

Test Case - 1

User Output
t1 before start t1.isAlive() : false
t2 before start t2.isAlive() : false
started t1 and t2 threads
t1 after start t1.isAlive() : true
UAE : 0
UAE : 1
UAE : 2
t2 after start t2.isAlive() : false
Spain : 0
Spain : 1
Spain : 2

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
S.No: 26 Exp. Name: Write a Java program to illustrate Daemon Threads Date: 2022-06-09

Aim:

Page No:
Daemon thread is a low priority thread (in the context of JVM) that runs in background to perform tasks
such as garbage collection etc., they do not prevent the JVM from exiting when all the user threads finish
their execution.

ID: 208A1A05A6
JVM terminates itself when all user threads finish their execution, even while Daemon threads are running.

The code Thread.currentThread().isDaemon() will return true , if the current thread is a daemon
thread and false if it is not a daemon thread.

Write a Java program to illustrate daemon threads.

Write a class DeamonThreadDemo which extends the Thread class. Override its run() method to check
whether the current thread is either daemon or user thread and print "This is daemon thread" and "This is
not a daemon thread" respectively.

Write the main() method in the class DeamonThreadDemo , which create three instances of class
DaemonThreadDemo as t1 , t2 and t3 and perform the below tasks in the given order:
1. invoke the setDaemon() method on t1 instance and pass true as the argument to set t1 as a
daemon thread.
2. Invoke start() method on t1 , t2 and t3 respectively.

Note: Please don't change the package name.


Source Code:

q11351/DaemonThreadDemo.java

package q11351;
public class DaemonThreadDemo extends Thread {

2020-2024-CSE-A
public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println("This is daemon thread");
} else {
System.out.println("This is not a daemon thread");
}
} RISE Krishna Sai Prakasam Group of Institutions
public static void main(String[] args) {
DaemonThreadDemo t1 = new DaemonThreadDemo();
DaemonThreadDemo t2 = new DaemonThreadDemo();
DaemonThreadDemo t3 = new DaemonThreadDemo();
t1.setDaemon(true);
t1.start();
t2.start();
t3.start();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output

Page No:
This is daemon thread
This is not a daemon thread
This is not a daemon thread

ID: 208A1A05A6
2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions
Exp. Name: Program that correctly implements Producer Consumer problem using
S.No: 27 Date: 2022-06-13
the concept of Inter Thread communication.

Page No:
Aim:
Write a Java program that correctly implements Producer Consumer problem using the concept of Inter
Thread communication.

ID: 208A1A05A6
Sample Input and Sample Output:

PUT:0
GET:0
PUT:1
GET:1
PUT:2
GET:2
PUT:3
GET:3
PUT:4
GET:4
PUT:5
GET:5

Note: Iterate the while-loop in run() method upto 5 times in Producer and Consumer Class.
Source Code:

ProdCons.java

import java.io.*;
import java.lang.*;
class Thread1{
int num;
boolean vs=false;
synchronized int get(){
if(!vs)

2020-2024-CSE-A
try{
wait();
}
catch(Exception e){
System.out.println("Exception occured : "+e);
}
System.out.println("GET:"+num);
RISE Krishna Sai Prakasam Group of Institutions
try{
Thread.sleep(5);
}
catch(Exception e){
System.out.println("Exception occured : "+e);
}
vs=false;
notify();
return num;
}
synchronized int put(int num){
if(vs)
try{
wait();
}
catch (Exception e){

}
this.num=num;

Page No:
vs=true;
System.out.println("PUT:"+num);
try{
Thread.sleep(5);

ID: 208A1A05A6
}
catch(Exception e){
System.out.println("Exception occured: "+e);

}
notify();
return num;
}
}
class Producer implements Runnable{
Thread1 t;
Producer(Thread1 t){
this.t=t;
new Thread(this,"Producer").start();
}
public void run(){
int x=0;
int i=0;
while(x<6){
t.put(i++);
x++;
}
}
}
class Consumer implements Runnable{
Thread1 t;

2020-2024-CSE-A
Consumer(Thread1 t){
this.t=t;
new Thread(this,"Consumer").start();
}
public void run(){
int x=0;
while(x<6){
t.get(); RISE Krishna Sai Prakasam Group of Institutions

x++;
}
}
}
class ProdCons{
public static void main(String args[]){
Thread1 t=new Thread1();
new Producer(t);
new Consumer(t);
}
}
Execution Results - All test cases have succeeded!

Test Case - 1

Page No:
User Output
PUT:0
GET:0

ID: 208A1A05A6
PUT:1
GET:1
PUT:2
GET:2
PUT:3
GET:3
PUT:4
GET:4
PUT:5
GET:5

2020-2024-CSE-A
RISE Krishna Sai Prakasam Group of Institutions

You might also like