Gayathri Lab Record
Gayathri Lab Record
Aim:
Page No: 1
Write a java program to display the default values of all primitive data types.
ID: 21F11A0439
Write code to produce the below output:
2021-2025-ECE-A
Note: Please don't change the package name.
Source Code:
q10815/PrimitiveTypes.java
package q10815;
class PrimitiveTypes {
User 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
Page No: 2
float default value = 0.0
ID: 21F11A0439
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Write a Java code to calculate the Roots
Date:
of a Quadratic equation
Aim:
Page No: 3
Write code to calculate roots of a quadratic equation.
Write a class QuadraticRoots with main method. The method receives three arguments, write code to parse
them into double type.
ID: 21F11A0439
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.
2021-2025-ECE-A
Source Code:
q10851/QuadraticRoots.java
package q10851;
public class QuadraticRoots {
public static void main(String[] args){
User Output
First root is : -0.6047152924789525 Second root is : -1.3952847075210475
Test Case - 2
User Output
Page No: 4
Roots are equal and value is : -1.0
Test Case - 3
ID: 21F11A0439
User Output
Roots are imaginary
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Write a Java program to print the
Date:
speeds of qualifying bikers in a Race
Aim:
Page No: 5
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.
Source Code:
ID: 21F11A0439
Race.java
2021-2025-ECE-A
System.out.println("The speed of the racers >= average speed " + avgSpeed);
System.out.println("The Speed of Qualifying racers : ");
if (racer1 >= avgSpeed) {
System.out.println(racer1);
}
if (racer2 >= avgSpeed) {
System.out.println(racer2);
User Output
The speed of the racers >= average speed 3.8
The Speed of Qualifying racers :
4.0
5.0
6.0
Test Case - 2
User Output
The speed of the racers >= average speed 38.2
The Speed of Qualifying racers :
Page No: 6
54.0
65.0
ID: 21F11A0439
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Write a Java program to Search an
Date:
element using Binary Search
Aim:
Page No: 7
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.
Binary search (or) Half-interval search (or) Logarithmic search is a search algorithm that finds the
ID: 21F11A0439
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.
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.
2021-2025-ECE-A
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.
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.
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.
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 process
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
Cmd Args : 10 8 12 11 9
Search element 9 is not found
Page No: 8
Note: Please don't change the package name.
Source Code:
ID: 21F11A0439
q11045/BinarySearch.java
package q11045;
public class BinarySearch {
public void binarySearch(int[] array, int key) {
int len = array.length, low, high, mid = -1, temp;
boolean flag = false;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
2021-2025-ECE-A
}
}
}
low = 0;
high = len - 1;
while (flag == false && low <= high) {
mid = (low + high) / 2;
q11045/BinarySearchMain.java
package q11045;
public class BinarySearchMain{
public static void main(String[] args){
int[] array = new int[args.length];
int n = args.length-1;
Page No: 9
for (int i = 0; i < n; i++)
{
array[i] = Integer.parseInt(args[i]);
}
ID: 21F11A0439
int key = Integer.parseInt(args[n]);
BinarySearch biSearch = new BinarySearch();
biSearch.binarySearch(array, key);
}
}
2021-2025-ECE-A
User Output
Search element 4 is found at position : 4
Test Case - 2
User Output
Aim:
Page No: 10
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 if
necessary.
ID: 21F11A0439
The working procedure for bubble sort is as follows:
2021-2025-ECE-A
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, and swaps
since 50 > 20.
( 20 50 40 10 80 ) -> ( 20 40 50 10 80 ) // Swap since 50 > 40.
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.
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 in 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 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 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, and swaps
since 50 > 20.
Page No: 11
( 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.
ID: 21F11A0439
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.
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 in 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 order (40
< 50), algorithm does not swap them.
2021-2025-ECE-A
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 :
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 :
( 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 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
Page No: 12
Note: Make sure to use the println() method and not the print() method.
ID: 21F11A0439
Source Code:
q11039/BubbleSorting.java
package q11039;
public class BubbleSorting {
public void bubbleSort(int[] array) {
int temp, len = array.length;
for (int pass = 0; pass < len - 1; pass++) {
for(int compare = 0; compare < len - pass - 1; compare++) {
if (array[compare] > array[compare + 1]) {
temp = array[compare];
array[compare] = array[compare + 1];
2021-2025-ECE-A
array[compare + 1] = temp;
}
}
}
for (int pass = 0; pass < len; pass++) {
System.out.println(array[pass]);
}
q11039/BubbleSortingMain.java
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);
}
}
User Output
9
22
21
20
19
18
17
50
30
20
10
User Output
Test Case - 2
Aim:
Page No: 14
Write code to sort the array elements by using merge sort technique.
ID: 21F11A0439
Note: Please don't change the package name.
Source Code:
q11043/MyMergeSort.java
2021-2025-ECE-A
Narayana Engineering College - Gudur
package q11043;
import java.util.Scanner;
public class MyMergeSort {
private int[] array;
private int[] tempMergArr;
Page No: 15
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();
ID: 21F11A0439
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);
for(int i:inputArr){
System.out.print(i);
System.out.print(" ");
}
}
2021-2025-ECE-A
public void sort(int inputArr[]) {
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex) {
Page No: 16
Execution Results - All test cases have succeeded!
Test Case - 1
ID: 21F11A0439
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
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Write a Java program to Delete and
Date:
Remove characters using StringBuffer class
Aim:
Page No: 17
Write a class JavaStringBufferDelete with a main method to delete characters from a string using StringBuffer
class.
ID: 21F11A0439
13. Consider a string "Hello India" and delete 0 to 6 characters in that and print the result.
14. Consider another string "Hello World", delete characters from position 0 to length of the entire string and
print the result.
15. Consider another string "Hello Java", remove 0th character and then print the result.
q11215/JavaStringBufferDelete.java
package q11215;
2021-2025-ECE-A
public class JavaStringBufferDelete {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("Hello India");
sb1.delete(0, 6);
System.out.println(sb1);
StringBuffer sb2 = new StringBuffer("Hello World");
sb2.delete(0, sb2.length());
User Output
India
ello Java
Exp. Name: Write a Java program to implement a
Date:
Class mechanism
Aim:
Page No: 18
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().
The member function setData() is used to initialize the data members and displayData() is used to display the
ID: 21F11A0439
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:
2021-2025-ECE-A
Name : Saraswathi
Age : 27
Designation : Teacher
Salary : 37250.0
q11115/Employee.java
package q11115;
public class Employee {
private String name;
private int age;
private String designation;
Page No: 19
private double salary;
public void setData(String a1, int a2, String a3, double a4) {
name = a1;
age = a2;
designation = a3;
ID: 21F11A0439
salary = a4;
}
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[]) {
Employee emp = new Employee();
emp.setData(args[0], Integer.parseInt(args[1]), args[2],
Double.parseDouble(args[3]));
2021-2025-ECE-A
emp.displayData();
}
}
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
Exp. Name: Write a Java program to implement a
Date:
Constructor
Aim:
Page No: 20
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().
The member function show() is used to display the given staff data.
ID: 21F11A0439
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
2021-2025-ECE-A
Note: Please don't change the package name.
Source Code:
q11116/Staff.java
User Output
Id : 18
Id : 45
User Output
Name : Akbar
Name : Gayatri
Test Case - 2
Aim:
Page No: 22
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 :
• 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
ID: 21F11A0439
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:
2021-2025-ECE-A
Similarly, if the main() method is passed one argument : 2.34, then the program should print the output as:
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:
q11267/Box.java
package q11267;
public class Box {
private double width;
private double height;
private double depth;
Page No: 23
public Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
ID: 21F11A0439
public Box() {
width = -1;
height = -1;
depth = -1;
}
public Box(double len) {
width = height = depth = len;
}
public double volume() {
return width * height * depth;
} public static void main(String args[]) {
if (args.length == 0) {
2021-2025-ECE-A
Box box = new Box();
System.out.println("Volume of Box() is : " + box.volume());
} else if (args.length == 1) {
double d1 = Double.parseDouble(args[0]);
Box box = new Box(d1);
System.out.println("Volume of Box(" + d1 + ") is : " +
box.volume());
User Output
Volume of Box() is : -1.0
Test Case - 2
User Output
Volume of Box(3.0) is : 27.0
Test Case - 3
User Output
Volume of Box(2.3, 3.5, 6.5) is : 52.324999999999996
Page No: 24
ID: 21F11A0439
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Write a Java program to implement
Date:
Method overloading
Aim:
Page No: 25
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.
Write the main(String[]) method within the class and assume that it will always receive a total of 6 command line
ID: 21F11A0439
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
2021-2025-ECE-A
Source Code:
q11266/Addition.java
package q11266;
public class Addition {
public int add(int a, int b) {
User Output
Page No: 26
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
ID: 21F11A0439
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Write a Java program to implement
Date:
Single Inheritance
Aim:
Page No: 27
Write a Java program to illustrate the single inheritance concept.
ID: 21F11A0439
• 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.
If the input is given as command line arguments to the main() as "101", "45.50", "67.75", "72.25" then the
2021-2025-ECE-A
program should print the output as:
Id : 101
Java marks : 45.5
C marks : 67.75
Cpp marks : 72.25
Total : 185.5
Note: While computing the total marks, add the marks in the following order only javaMarks, cMarks and
cppMarks
Source Code:
q11263/SingleInheritanceDemo.java
package q11263;
public class SingleInheritanceDemo {
public static void main(String args[]) {
Result r= new Result();
r.setMarks(Integer.parseInt(args[0]),Float.parseFloat(args[1]),Float.parseFloat(args[2]),Float.parseFloat
Page No: 28
r.displayMarks();
r.compute();
r.showResult();
}
}
ID: 21F11A0439
class Marks {
int id;
float javaMarks, cMarks, cppMarks;
public void setMarks(int a1, float a2, float a3, float a4) {
id = a1;
javaMarks = a2;
cMarks = a3;
cppMarks = a4;
}
public void displayMarks() {
System.out.println("Id : " + id);
System.out.println("Java marks : " +javaMarks);
2021-2025-ECE-A
System.out.println("C marks : " + cMarks);
System.out.println("Cpp marks : " +cppMarks);
}
}
class Result extends Marks {
private float total, avg;
public void compute () {
User Output
Id : 102
Java marks : 35.6
C marks : 45.0
Cpp marks : 65.5
Total : 146.1
Avg : 48.7
Test Case - 2
User Output
Id : 101
Java marks : 45.5
C marks : 67.75
Cpp marks : 72.25
Page No: 29
Total : 185.5
Avg : 61.833332
Test Case - 3
ID: 21F11A0439
User Output
Id : 103
Java marks : 50.5
C marks : 46.8
Cpp marks : 52.65
Total : 149.95001
Avg : 49.983337
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Write a Java program to implement
Date:
Multilevel Inheritance
Aim:
Page No: 30
Write a Java program to illustrate the multilevel inheritance concept.
ID: 21F11A0439
• 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.
2021-2025-ECE-A
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
q11264/MultilevelInheritanceDemo.java
package q11264;
public class MultilevelInheritanceDemo {
Page No: 31
Result r = new Result();
r.setData(Integer.parseInt(args[0]), args[1]);
r.displayData();
ID: 21F11A0439
r.setMarks(Float.parseFloat(args[2]), Float.parseFloat(args[3]),
Float.parseFloat(args[4]));
r.displayMarks();
r.compute();
r.showResult();
2021-2025-ECE-A
}
class Student {
int id;
String name;
id = a1;
name = a2;
float javaMarks,cMarks,cppMarks ;
javaMarks = a1;
cppMarks = a3;
Page No: 32
public void displayMarks() {
ID: 21F11A0439
System.out.println("Cpp marks : " + cppMarks);
2021-2025-ECE-A
total = javaMarks + cMarks + cppMarks;
User Output
Id : 99
Name : Geetha
Java marks : 56.0
C marks : 75.5
Cpp marks : 66.6
Total : 198.1
Avg : 66.03333
Test Case - 2
User Output
Id : 199
Name : Lakshmi
Page No: 33
Java marks : 55.5
C marks : 78.5
Cpp marks : 78.0
Total : 212.0
ID: 21F11A0439
Avg : 70.666664
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Write a Java program to find Areas of
Date:
different Shapes using abstract class
Aim:
Page No: 34
Write a Java program to illustrate the abstract class concept.
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).
ID: 21F11A0439
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:
2021-2025-ECE-A
Area of circle : 22.890600000000006
Page No: 35
area.rectangleArea(Double.parseDouble(args[0]),
Double.parseDouble(args[1]));
area.squareArea(Double.parseDouble(args[0]));
area.circleArea(Double.parseDouble(args[1]));
}
ID: 21F11A0439
}
// Write all the classes with definitions
abstract class CalcArea {
abstract void triangleArea(double b, double h);
abstract void rectangleArea(double l, double b);
abstract void squareArea(double s);
abstract void circleArea(double r);
}
class FindArea extends CalcArea {
void triangleArea(double b, double h) {
double area = (b*h)/2;
System.out.println("Area of triangle : " + area);
2021-2025-ECE-A
}
void rectangleArea(double l, double b) {
double area = l*b;
System.out.println("Area of rectangle : " + area);
}
void squareArea(double s) {
double area = s*s;
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
Area of triangle : 83.14375000000001
Area of rectangle : 166.28750000000002
Area of circle : 551.26625
Area of square : 157.50250000000003
Aim:
Page No: 37
Write a Java program to illustrate the usage of super keyword.
ID: 21F11A0439
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().
2021-2025-ECE-A
q11273/ExampleOnSuper.java
Page No: 38
}
void eat() {
System.out.println("Eating something");
}
}
ID: 21F11A0439
class Dog extends Animal {
//String color = "Black";
public Dog() {
super();
System.out.println("Dog is created");
}
void eat() {
System.out.println("Eating bread");
}
void bark() {
System.out.println("Barking");
}
2021-2025-ECE-A
void work() {
super.eat();
eat();
bark();
// System.out.println(super.color);
// System.out.println(color);
}
User Output
Animal is created
Dog is created
Eating something
Eating bread
Barking
Exp. Name: Write a Java program to implement
Date:
Interface
Aim:
Page No: 39
Write a Java program that implements an interface.
Create an interface called Car with two abstract methods String getName() and int getMaxSpeed() . Also
declare one default method void applyBreak() which has the code snippet
ID: 21F11A0439
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
2021-2025-ECE-A
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, 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.
q11284/MainApp.java
package q11284;
Page No: 40
interface Car {
String getName();
int getMaxSpeed();
default void applyBreak() {
System.out.println("Applying break on " + getName());
ID: 21F11A0439
}
static Car getFastestCar(Car car1, Car car2) {
return (car1.getMaxSpeed() >= car2.getMaxSpeed()) ? car1 : car2;
}
}
class BMW implements Car {
private String name;
private int maxSpeed;
public BMW(String name, int maxSpeed) {
this.name = name;
this.maxSpeed = maxSpeed;
}
2021-2025-ECE-A
public int getMaxSpeed() {
return maxSpeed;
}
public String getName() {
return name;
}
}
User Output
Page No: 41
Fastest car is : BMW
Test Case - 2
ID: 21F11A0439
User Output
Fastest car is : Maruthi
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: A java program to demonstrate that the
catch block for type Exception A catches the Date:
exception of type Exception B and Exception C.
Page No: 42
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. Write a java
program to demonstrate that the catch block for type Exception A catches the exception of type Exception B and
Exception C.
ID: 21F11A0439
Note: Please don't change the package name.
Source Code:
q29793/TestException.java
2021-2025-ECE-A
Narayana Engineering College - Gudur
package q29793;
import java.lang.*;
@SuppressWarnings("serial")
class ExceptionA extends Exception {
String message;
Page No: 43
public ExceptionA(String message) {
this.message = message;
}
}
@SuppressWarnings("serial")
ID: 21F11A0439
class ExceptionB extends ExceptionA {
//Write constructor of class ExceptionB with super()
public ExceptionB(String message){
super(message);
}
}
@SuppressWarnings("serial")
class ExceptionC extends ExceptionB {
//Write constructor of class ExceptionC with super()
public ExceptionC(String message){
super(message);
2021-2025-ECE-A
}
}
@SuppressWarnings("serial")
public class TestException {
public static void main(String[] args) {
try {
getExceptionB();
User Output
Got exception from Exception B
Got exception from Exception C
Aim:
Page No: 45
Write a JAVA program Illustrating Multiple catch clauses
Source Code:
MultiCatchClause.java
ID: 21F11A0439
import java.util.Scanner;
public class MultiCatchClause {
public static void main(String args[]) {
int arr[]={1,2,3,4,5};
Scanner Scan=new Scanner(System.in);
System.out.println("Enter a index number");
int index=Integer.parseInt(Scan.nextLine());
try {
System.out.println("Number in the array : "+arr[index]);
System.out.println("Division by the number: "+arr[index]/index);
}
catch(ArithmeticException e) {
2021-2025-ECE-A
System.out.println("Division by zero exception occurred");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds exception occurred");
}
catch(Exception e){
System.out.println("Exception occurred");
User Output
Enter a index number
7
Array index out of bounds exception occurred
Test Case - 2
User Output
Enter a index number
0
Number in the array : 1
Division by zero exception occurred
Exp. Name: Write a Java program that implements
Date:
Runtime Polymorphism
Aim:
Page No: 46
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: 21F11A0439
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.
2021-2025-ECE-A
q11277/RuntimePolymorphismDemo.java
Page No: 47
Animal ref3 = new Cow();
Animal ref4 = new Snake();
ref1.whoAmI();
ref2.whoAmI();
ref3.whoAmI();
ID: 21F11A0439
ref4.whoAmI();
}
}
class Animal {
void whoAmI() {
System.out.println("I am a generic animal");
}
}
class Dog extends Animal {
void whoAmI() {
System.out.println("I am a dog");
}
2021-2025-ECE-A
}
class Cow extends Animal {
void whoAmI() {
System.out.println("I am a cow");
}
}
class Snake extends Animal {
User Output
I am a generic animal
I am a dog
I am a cow
I am a snake
Exp. Name: Write a Java program for creation of
Date:
illustrating throw
Aim:
Page No: 48
Write a Java program for creation of illustrating throw.
Write a class ThrowExample contains a method checkEligibilty(int age, int weight) which throws an
ArithmeticException with a message "Student is not eligible for registration" when age < 12 and weight <
ID: 21F11A0439
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:
For example, if the given data is 15 and 41 then the output should be:
2021-2025-ECE-A
Welcome to the Registration process!!
Student Entry is Valid!!
Have a nice day
q11335/ThrowExample.java
package q11335;
public class ThrowExample {
public static void main(String args[]) {
System.out.println("Welcome to the Registration process!!");
try {
Page No: 49
checkEligibilty(Integer.parseInt(args[0]),
Integer.parseInt(args[1])); //Fill the missing code
System.out.println("Have a nice day");
}
catch(ArithmeticException e) { // Fill the missing code
ID: 21F11A0439
System.out.println(e); // Fill the missing code
}
}
static void checkEligibilty(int age, int weight) {
if(age <12 && weight<40)
{
// Write the condition
throw new ArithmeticException("Student is not eligible for
registration");
// Fill the missing code
} else {
System.out.println("Student Entry is Valid!!");
2021-2025-ECE-A
}
}
}
User Output
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
Exp. Name: Write a Java program to illustrate
Date:
Finally block
Aim:
Page No: 50
Write a Java program to handle an ArithmeticException divided by zero by using try, catch and finally
blocks.
Write the main() method with in the class MyFinallyBlock which will receive four arguments and convert the
ID: 21F11A0439
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:
2021-2025-ECE-A
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:
q11330/MyFinallyBlock.java
package q11330;
public class MyFinallyBlock {
public static void main(String args[]) {
int a,b,result1;
float c,d,result2;
Page No: 51
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Float.parseFloat(args[2]);
d=Float.parseFloat(args[3]);
try {
ID: 21F11A0439
result1 = a/b;
System.out.println("Result of integer values division : "+result1);
}
catch(Exception ex) {
System.out.println("Inside the 1st catch block");
}
finally {
System.out.println("Inside the 1st finally block");
}
try {
result2 = c/d;
System.out.println("Result of float values division : "+result2);
2021-2025-ECE-A
}
catch(Exception ex) {
System.out.println("Inside the 2nd catch block");
}
finally {
System.out.println("Inside the 2nd finally block");
}
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
Page No: 52
Result of float values division : Infinity
Inside the 2nd finally block
ID: 21F11A0439
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Write a Java program to handle an
Date:
ArithmeticException - divided by zero
Aim:
Page No: 53
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 arguments
which have to be internally converted to integers.
ID: 21F11A0439
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:
2021-2025-ECE-A
Exception caught : divide by zero occurred
User Output
Result = 4
User Output
Exception caught : divide by zero occurred
Test Case - 2
Aim:
Page No: 55
Write a Java program to illustrate user-defined exceptions.
ID: 21F11A0439
• 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.
2021-2025-ECE-A
Note: Please don't change the package name.
Source Code:
q11337/BankDemo.java
Page No: 56
c.deposit(1000.00);
try {
System.out.println("Withdrawing $700...");
c.withdraw(700.00);
System.out.println("Withdrawing $600...");
ID: 21F11A0439
c.withdraw(600.00);
}
catch (InsufficientFundsException e) {
System.out.println("Sorry, short of $" + e.getAmount() + " in the
account number " + c.getNumber());
}
}
}
class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
this.amount=amount;// initialize
2021-2025-ECE-A
}
public double getAmount() {
return amount;
}
}
class CheckingAccount {
private double balance;
User Output
Page No: 57
Depositing $1000...
Withdrawing $700...
Withdrawing $600...
Sorry, short of $300.0 in the account number 1001
ID: 21F11A0439
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Write a Java program demonstrating
Date:
the usage of Threads
Aim:
Page No: 58
Write a Java program that uses three threads to perform the below actions:
16. First thread should print "Good morning" for every 1 second for 2 times
17. Second thread should print "Hello" for every 1 seconds for 2 times
18. 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
ID: 21F11A0439
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.]
2021-2025-ECE-A
Note: Please don't change the package name.
Source Code:
q11349/ThreadDemo.java
Page No: 59
Thread t3 = new Thread(new Printer("Welcome", 3, 1));
t1.start();
t2.start();
t3.start();
t1.join();
ID: 21F11A0439
t2.join();
t3.join();
System.out.println("All the three threads t1, t2 and t3 have completed
execution.");
}
}
class Printer implements Runnable {
private String message;
private int delay;
private int count;
public Printer(String message,int dealy,int count) {
this.message=message;
2021-2025-ECE-A
this.delay=delay;
this.count=count;
}
public void run() {
for(int i=0;i<count;i++) {
try {
System.out.println(message);
User Output
Good morning
Hello
Welcome
Good morning
Hello
All the three threads t1, t2 and t3 have completed execution.
Exp. Name: Write a Java program to illustrates
Date:
isAlive() and join()
Aim:
Page No: 60
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 Counter class
which implements Runnable interface.
ID: 21F11A0439
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:
The JoinThreadDemo.main() method should perform the below tasks in the given order :
19. Create the first instance of thread as t1 with an instance of Counter class using "Spain" as the
argument.
20. Create the second instance of thread as t2 with an instance of Counter class using "UAE" as the
argument.
21. Print the isAlive() status of t1 as : "t1 before start t1.isAlive() : " + t1.isAlive().
2021-2025-ECE-A
22. Print the isAlive() status of t1 as : "t2 before start t2.isAlive() : " + t2.isAlive().
23. Start t1 and t2 threads respectively.
24. Print a message to the console as : "started t1 and t2 threads".
25. Print the isAlive() status of t1 as : "t1 after start t1.isAlive() : " + t1.isAlive().
26. Invoke the join() method on t2 .
27. Print the isAlive() status of t1 as : "t2 after start t2.isAlive() : " + t2.isAlive().
q11350/JoinThreadDemo.java
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"));
Page No: 61
System.out.println("t1 before start t1.isAlive() : "+t1.isAlive());
System.out.println("t2 before start t2.isAlive() : "+t2.isAlive());
t1.start();
t2.start();
System.out.println("started t1 and t2 threads");
ID: 21F11A0439
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++) {
2021-2025-ECE-A
System.out.println(name + " : " + i);
}
}
}
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
Exp. Name: Write a Java program to illustrate
Date:
Daemon Threads
Aim:
Page No: 62
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.
JVM terminates itself when all user threads finish their execution, even while Daemon threads are running.
ID: 21F11A0439
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 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
2021-2025-ECE-A
DaemonThreadDemo as t1 , t2 and t3 and perform the below tasks in the given order:
28. invoke the setDaemon() method on t1 instance and pass true as the argument to set t1 as a daemon
thread.
29. Invoke start() method on t1 , t2 and t3 respectively.
q11351/DaemonThreadDemo.java
package q11351;
public class DaemonThreadDemo extends Thread {
public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println("This is daemon thread");
} else {
System.out.println("This is not a daemon thread");
}
}
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: 63
This is daemon thread
This is not a daemon thread
This is not a daemon thread
ID: 21F11A0439
2021-2025-ECE-A
Narayana Engineering College - Gudur
Exp. Name: Program that correctly implements
Producer Consumer problem using the concept of Date:
Inter Thread communication.
Page No: 64
Aim:
Write a Java program that correctly implements Producer Consumer problem using the concept of Inter Thread
communication.
Sample Input and Sample Output:
ID: 21F11A0439
PUT:0
GET:0
PUT:1
GET:1
PUT:2
GET:2
PUT:3
GET:3
PUT:4
GET:4
PUT:5
GET:5
2021-2025-ECE-A
Note: Iterate the while-loop in run() method upto 5 times in Producer and Consumer Class.
Source Code:
ProdCons.java
Page No: 65
}
}
class Product {
int n;
boolean isItemReady=false;
ID: 21F11A0439
synchronized int get() {
while(isItemReady == false) {
try {
wait();
}
catch(InterruptedException e) {
System.out.println("InterruptException caught");
}
}
System.out.println("GET:"+n);
isItemReady=false;
notify();
2021-2025-ECE-A
return n;
}
synchronized void put(int n) {
while(isItemReady==true) {
try {
wait();
}
Page No: 66
i++;
}
}
}
ID: 21F11A0439
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
PUT:0
GET:0
PUT:1
GET:1
2021-2025-ECE-A
PUT:2
GET:2
PUT:3
GET:3
PUT:4
GET:4
Page No: 67
Aim:
Write a JAVA program to synchronize the threads by using Synchronize statements and Synchronize block
Source Code:
q125/TestSynchronizedBlock1.java
ID: 21F11A0439
2021-2025-ECE-A
Narayana Engineering College - Gudur
//JAVA program to synchronize the threads by using Synchronize statements and Synchronize
block
//Read input from the user
package q125;
import java.util.*;
Page No: 68
class Table {
void printTable() {
synchronized(this) {
System.out.println("-----Current
Thread:"+Thread.currentThread().getName()+"-------");
ID: 21F11A0439
System.out.println("enter number to print its table:");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
for(int i=1;i<=5;i++) {
System.out.println(n*i);
try {
Thread.sleep(100);
}
catch(Exception e) {
System.out.println(e);
}
}
2021-2025-ECE-A
}
}
}
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) {
this.t=t;
User Output
Page No: 69
-----Current Thread:Thread-0-------
enter number to print its table:
5
5
ID: 21F11A0439
10
15
20
25
-----Current Thread:Thread-1-------
enter number to print its table:
7
7
14
21
28
2021-2025-ECE-A
35
Test Case - 2
User Output
-----Current Thread:Thread-0-------