0% found this document useful (0 votes)
5 views76 pages

Java Programs for Data Types and Algorithms

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

Java Programs for Data Types and Algorithms

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

Date: 2025-07-

Page No: 1
[Link]: 1 Exp. Name: Primitive data types
30

Aim:

0 G 5 0 A 1 Q B 4 2 : DI
Write a Java program that demonstrates the use of all primitive data types. Your program
should prompt the user to input values for each primitive data type (byte, short, int, long,
float, double, char, boolean) and then print out those values.
Source Code:

[Link]

import [Link];
class PrimitiveDataTypes{
public static void main(String args[]){
Scanner sc=new Scanner([Link]);
[Link]("Byte value: ");

C- E S C- 8 2 0 2- 4 2 0 2
int a=[Link]();
[Link]("short value: ");
short s=[Link]();
[Link]("int value: ");
int i=[Link]();
[Link]("long value: ");
long l=[Link]();

Vasireddy Venkatadri Institute of Technology


[Link]("float value: ");
float f=[Link]();
[Link]("double value: ");
double d=[Link]();
[Link]("char value: ");
char c=[Link]().charAt(0);
[Link]("boolean value (true/false): ");
boolean b=[Link]();
[Link]("byteVar: "+a+"\nshortVar:
"+s+"\nintVar: "+i+"\nlongVar: "+l+"\nfloatVar: "+f+"\ndoubleVar:
"+d+"\ncharVar: "+c+"\nbooleanVar: "+b);
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output
Byte value:
127

Page No: 2
short value:
32767
int value:
2147483647

0 G 5 0 A 1 Q B 4 2 : DI
long value:
9223372036854775807
float value:
123.456
double value:
9876.54321
char value:
Z
boolean value (true/false):

C- E S C- 8 2 0 2- 4 2 0 2
true
byteVar: 127
shortVar: 32767
intVar: 2147483647
longVar: 9223372036854775807
floatVar: 123.456

Vasireddy Venkatadri Institute of Technology


doubleVar: 9876.54321
charVar: Z
booleanVar: true
Exp. Name: Roots of the quadratic Date: 2025-10-
[Link]: 2

Page No: 3
equation 22

Aim:
Write a Java Program to find Roots of a Quadratic Equation.

0 G 5 0 A 1 Q B 4 2 : DI
Refer to the displayed sample test cases to strictly match the input and output layout.
Source Code:

q27331/[Link]

C- E S C- 8 2 0 2- 4 2 0 2
Vasireddy Venkatadri Institute of Technology
package q27331;

Page No: 4
import [Link];
public class QuadraticEquation{
public static void main(String[] args){
Scanner s = new Scanner([Link]);
[Link]("Coefficient a: ");

0 G 5 0 A 1 Q B 4 2 : DI
double a = [Link]();
[Link]("Coefficient b: ");
double b = [Link]();
[Link]("Coefficient c: ");
double c = [Link]();
double dis = b * b - 4 * a * c;
if(dis>0)
{
double root1 = (-b + [Link](dis)) / (2
* a);
double root2 = (-b - [Link](dis)) / (2

C- E S C- 8 2 0 2- 4 2 0 2
* a);
[Link]("The roots are real
and distinct");
[Link]("Root1: "+root1);
[Link](" Root2: "+root2);
}
else if(dis ==0)

Vasireddy Venkatadri Institute of Technology


{
double root = -b / (2 * a);
[Link]("The roots are real
and equal");
[Link]("Root: "+root);
}
else
{
double real = -b / (2 *a);
double imag = [Link](-dis) / (2 *a);
[Link]("The roots are
imaginary");
}
[Link]();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 5
User Output

Coefficient a:
1

0 G 5 0 A 1 Q B 4 2 : DI
Coefficient b:
6
Coefficient c:
9
The roots are real and equal
Root: -3.0

Test Case - 2

User Output

C- E S C- 8 2 0 2- 4 2 0 2
Coefficient a:
1
Coefficient b:
5
Coefficient c:
8

Vasireddy Venkatadri Institute of Technology


The roots are imaginary

Test Case - 3

User Output

Coefficient a:
2
Coefficient b:
6
Coefficient c:
1
The roots are real and distinct
Root1: -0.17712434446770464 Root2: -2.8228756555322954

Test Case - 4

User Output
Coefficient b:
6

Page No: 6
Coefficient c:
4
The roots are real and distinct
Root1: -1.0 Root2: -2.0

0 G 5 0 A 1 Q B 4 2 : DI
C- E S C- 8 2 0 2- 4 2 0 2
Vasireddy Venkatadri Institute of Technology
Date: 2025-10-
[Link]: 3 Exp. Name: Binary Search

Page No: 7
22

Aim:
Write a program to check whether the given element is present or not in the array of

0 G 5 0 A 1 Q B 4 2 : DI
elements using the binary search Technique

Input Format:
• The first line of input contains an integer N representing the no. of elements of
the array
• The second line input contains the array of N integers separated by a space
• The last line of input contains the key element to be searched

Output Format:
• If the element is found, print the index.
• If the element is not found, print "Not found".

C- E S C- 8 2 0 2- 4 2 0 2
Sample Test Case:
Input:
7
1 2 3 4 3 5 6
3
Output:

Vasireddy Venkatadri Institute of Technology


2

Note:
• If two duplicate elements are present, then it should print the first element's index
value.
• Refer to the visible test cases for better understanding.
Source Code:

q17128/[Link]
package q17128;

Page No: 8
import [Link];
public class CTJ17128
{
public static void main(String args[])
{

0 G 5 0 A 1 Q B 4 2 : DI
Scanner sc=new Scanner([Link]);
int N=[Link]();
int arr[]=new int[N];
for(int i=0;i<N;i++)
{
arr[i]=[Link]();
}
int key=[Link]();
int index=binarysearch(arr,key);
if(index!=-1)
[Link](index);

C- E S C- 8 2 0 2- 4 2 0 2
else
[Link]("Not found");
[Link]();
}
public static int binarysearch(int[] arr, int
key)
{

Vasireddy Venkatadri Institute of Technology


int left=0;
int right=[Link]-1;
while(left<=right)
{
int mid=left+(right-left)/2;
if(arr[mid]==key)
{
return mid;
}
else if(arr[mid]<key)
{
left=mid+1;
}
else
right=mid-1;
}
return -1;
}
}
Execution Results - All test cases have succeeded!

Page No: 9
Test Case - 1

User Output

0 G 5 0 A 1 Q B 4 2 : DI
1234356
3
2

Test Case - 2

User Output

10
1 2 3 4 5 6 7 8 9 19

C- E S C- 8 2 0 2- 4 2 0 2
20
Not found

Vasireddy Venkatadri Institute of Technology


Date: 2025-10-
[Link]: 4 Exp. Name: Bubble Sort Technique

Page No: 10
22

Aim:
Write a Java program to sort an array of integers using the bubble sort algorithm. The

0 G 5 0 A 1 Q B 4 2 : DI
program should read the number of elements and the array elements from the user, then
display the sorted array in ascending order.

Input Format:
• The first line contains an integer n representing the number of elements in the
array.
• The second line contains n space-separated integers representing the array
elements.

Output Format:
• Print the sorted array elements in ascending order, separated by a space:

C- E S C- 8 2 0 2- 4 2 0 2
<int1> <int2> <int3> ...

Note:
• Refer to the visible test cases to strictly match the input/output layout.
Source Code:

q32083/[Link]

Vasireddy Venkatadri Institute of Technology


package q32083;

Page No: 11
import [Link];

public class BubbleSort {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

0 G 5 0 A 1 Q B 4 2 : DI
int n = [Link]();

int[] arr = new int[n];


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

bubbleSort(arr);

for (int num : arr) {

C- E S C- 8 2 0 2- 4 2 0 2
[Link](num + " ");
}

[Link]();
}

public static void bubbleSort(int[] arr) {

Vasireddy Venkatadri Institute of Technology


int n=[Link];
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
{

if(arr[j]>arr[j+1])
{

int temp=arr[j];

arr[j]=arr[j+1];

arr[j+1]=temp;
}
}
}

//Type your content here


Page No: 12
}

0 G 5 0 A 1 Q B 4 2 : DI
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output

C- E S C- 8 2 0 2- 4 2 0 2
12 35 69 48 51
12 35 48 51 69

Test Case - 2

User Output

Vasireddy Venkatadri Institute of Technology


3
5 -1 25
-1 5 25
Exp. Name: Removing duplicate
Date: 2025-10-

Page No: 13
[Link]: 5 characters from a glitchy message by
22
using StringBuffer constructor

Aim:

0 G 5 0 A 1 Q B 4 2 : DI
A group of friends sent a message to Jaya, but due to a technical glitch, the message
contained duplicate characters. To overcome this kind of problem she decided to craft a
Java program using a StringBuffer constructor that takes the glitchy message as input
and returns a new string with all duplicate characters removed.

How can Jaya craft this program?

Input Format:
The input line reads a string representing the glitchy message.

Output Format:

C- E S C- 8 2 0 2- 4 2 0 2
The output is a string after removing the duplicate characters (Including special
characters, space).

Note: Use println() to print the output statements.


Source Code:

q22135/[Link]

Vasireddy Venkatadri Institute of Technology


package q22135;

Page No: 14
import [Link];
public class Main
{
public static void main(String args[])
{

0 G 5 0 A 1 Q B 4 2 : DI
Scanner sc=new Scanner([Link]);
String st=[Link]();
StringBuffer sb=new StringBuffer();
for(int i=0;i<[Link]();i++)
{
char ch=[Link](i);
if([Link]([Link](ch))==-1)
{
[Link](ch);
}
}

C- E S C- 8 2 0 2- 4 2 0 2
[Link]([Link]());
[Link]();
}
}
// write your code here

Vasireddy Venkatadri Institute of Technology


Execution Results - All test cases have succeeded!

Test Case - 1

User Output

abcdef
abcdef

Test Case - 2

User Output

aabbcc
a bc
Date: 2025-10-
[Link]: 6 Exp. Name: Constructor Overloading

Page No: 15
22

Aim:
Write a Java program that demonstrates constructor overloading in a class named Book.

0 G 5 0 A 1 Q B 4 2 : DI
The Book class should have the following attributes:
• title - String
• author - String
• pageCount - int

Implement the following constructors in the Book class:


1. A default constructor that initializes the title and author to "Unknown Title" and
"Unknown Author," respectively, and sets pageCount to 0.
2. A constructor that takes title and author as parameters and initializes the
corresponding attributes. The pageCount should be set to 0.
3. A constructor that takes title, author, and pageCount as parameters and initializes the

C- E S C- 8 2 0 2- 4 2 0 2
corresponding attributes.

Additionally, include a method named displayBookDetails that prints the details of the
book, including the title, author, and pageCount.

Sample Input and Output format:


Details for Book 1:

Vasireddy Venkatadri Institute of Technology


Title: Introduction to Java Programming
Author: John Smith
Details for Book 2:
Title: Data Structures and Algorithms
Author: Alice Johnson
Page Count: 350
Book 1:
Title: Introduction to Java Programming
Author: John Smith
Page Count: 0
Book 2:
Title: Data Structures and Algorithms
Author: Alice Johnson
Page Count: 350
Source Code:

[Link]
import [Link];

Page No: 16
public class Book {
public String title;
public String author;
public int pageCount;

0 G 5 0 A 1 Q B 4 2 : DI
public Book(String title,String author)
{
[Link]=title;
[Link]=author;
[Link]=pageCount;
}
public Book(String title,String author,int pageCount)
{
[Link]=title;
[Link]=author;
[Link]=pageCount;

C- E S C- 8 2 0 2- 4 2 0 2
}
public void displayBookDetails()
{
[Link]("Title: "+[Link]);
[Link]("Author: "+[Link]);
[Link]("Page Count:
"+[Link]);

Vasireddy Venkatadri Institute of Technology


}

//write your code here..

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Taking user inputs for Book 1


[Link]("Details for Book 1:");
[Link]("Title: ");
String title1 = [Link]();
[Link]("Author: ");
String author1 = [Link]();

// Creating Book 1 using the constructor with title and


author parameters
Book book1 = new Book(title1, author1);
Page No: 17
// Taking user inputs for Book 2
[Link]("Details for Book 2:");
[Link]("Title: ");
String title2 = [Link]();
[Link]("Author: ");

0 G 5 0 A 1 Q B 4 2 : DI
String author2 = [Link]();
[Link]("Page Count: ");
int pageCount2 = [Link]();

// Creating Book 2 using the constructor with all


parameters
Book book2 = new Book(title2, author2, pageCount2);

// Displaying details of each book


[Link]("Book 1:");
[Link]();

C- E S C- 8 2 0 2- 4 2 0 2
[Link]("Book 2:");
[Link]();

// Close the scanner


[Link]();
}

Vasireddy Venkatadri Institute of Technology


}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output

Details for Book 1:


Title:
Introduction to Java Programming
Author:
John Smith
Details for Book 2:
Title:
Data Structures and Algorithms
Author:
Alice Johnson
Page Count:
350
Book 1:

Page No: 18
Title: Introduction to Java Programming
Author: John Smith
Page Count: 0
Book 2:

0 G 5 0 A 1 Q B 4 2 : DI
Title: Data Structures and Algorithms
Author: Alice Johnson
Page Count: 350

Test Case - 2

User Output

Details for Book 1:


Title:

C- E S C- 8 2 0 2- 4 2 0 2
Programming Basics
Author:
Jane Doe
Details for Book 2:
Title:
Advanced Java Concepts

Vasireddy Venkatadri Institute of Technology


Author:
Bob Williams
Page Count:
500
Book 1:
Title: Programming Basics
Author: Jane Doe
Page Count: 0
Book 2:
Title: Advanced Java Concepts
Author: Bob Williams
Page Count: 500
Exp. Name: Implementing Method Date: 2025-10-
[Link]: 7

Page No: 19
overloading 22

Aim:
Write a Java program with a class name OverloadArea with overload methods area(float)

0 G 5 0 A 1 Q B 4 2 : DI
and area(float, float) to find area of square and rectangle.

Write the main method within the class and assume that it will receive a total of 2
command line arguments of type float.

If the main() is provided with arguments : 1.34, 1.98 then the program should print the
output as:
Area of square for side in meters 1.34 : 1.7956
Area of rectangle for length and breadth in meters 1.34, 1.98 : 2.6532001
Source Code:

C- E S C- 8 2 0 2- 4 2 0 2
[Link]

// Type Content here...


public class OverloadArea
{
public static float area(float side)
{

Vasireddy Venkatadri Institute of Technology


return (side*side);
}
public static float area(float len, float bre)
{
return (len*bre);
}
public static void main(String args[])
{
float f1=[Link](args[0]);
float f2=[Link](args[1]);
float f3=area(f1);
float f4=area(f1,f2);
[Link]("Area of square for
side in meters "+[Link]("%.2f",f1)+":
"+[Link]("%.4f",f3));
[Link]("Area of rectangle for
length and breadth in meters "+[Link]("%.2f",f1) +",
"+[Link]("%.2f",f2) +": "+[Link]("%.7f",f4));
}
}
Execution Results - All test cases have succeeded!

Page No: 20
Test Case - 1

User Output

Area of square for side in meters 1.34: 1.7956

0 G 5 0 A 1 Q B 4 2 : DI
Area of rectangle for length and breadth in meters 1.34, 1.98:
2.6532001

Test Case - 2

User Output

Area of square for side in meters 2.30: 5.2900


Area of rectangle for length and breadth in meters 2.30, 2.80:
6.4399996

C- E S C- 8 2 0 2- 4 2 0 2
Vasireddy Venkatadri Institute of Technology
Date: 2025-10-
[Link]: 8 Exp. Name: Basics of Class and Object

Page No: 21
22

Aim:
The Spy Academy is implementing a new system to manage information about their

0 G 5 0 A 1 Q B 4 2 : DI
agents. As part of this system, they need to create a class to represent an agent. Imagine
yourself as the chief developer, and your task is to design a basic class named Agent.

Task:
1. Design a class named Agent with the following attributes:
• name (String)
• age (int)
• codename (String)
• isUndercover (boolean)
2. Implement a method named introduce() that prints a message introducing the agent,
including their name, age, and codename.

C- E S C- 8 2 0 2- 4 2 0 2
Additional Instructions:
• In the main method, create an instance of the Agent class named topAgent.
• Use user input within the main method to set the attributes of topAgent (name,
age, codename, and isUndercover).
• Invoke the introduce() method on topAgent to introduce this top agent to the
team.

Vasireddy Venkatadri Institute of Technology


Note:
• Partial code is given fill in the remaining code.
Source Code:

q22852/[Link]
package q22852;

Page No: 22
import [Link];

// create class Agent and Attributes


class Agent {
// Attributes

0 G 5 0 A 1 Q B 4 2 : DI
String name;
int age;
String codename;
boolean isUndercover;

// create Method to introduce the agent

void introduce(){
[Link]("Hello, I am Agent " + codename +
"."); // write your code here

C- E S C- 8 2 0 2- 4 2 0 2
[Link]("My real name is " + name + "."); //
write your code here
[Link]("I am " + age + " years old."); //
write your code here
}
}

Vasireddy Venkatadri Institute of Technology


public class SpySystem {
public static void main(String[] args) {
// Create an instance of Agent
Agent topAgent=new Agent();
Scanner scanner = new Scanner([Link]);
[Link]("name: ");
[Link] = [Link]();
[Link]("age: ");
[Link] = [Link]();
[Link]();
[Link]("codename: ");
[Link] = [Link]();
[Link]("undercover? (true/false): ");
[Link] = [Link]();
[Link]();

// Introducing the topAgent

[Link]();
}
}
Execution Results - All test cases have succeeded!

Page No: 23
Test Case - 1

User Output

name:

0 G 5 0 A 1 Q B 4 2 : DI
Alice
age:
27
codename:
007
undercover? (true/false):
true
Hello, I am Agent 007.
My real name is Alice.

C- E S C- 8 2 0 2- 4 2 0 2
I am 27 years old.

Test Case - 2

User Output

name:

Vasireddy Venkatadri Institute of Technology


Bob
age:
25
codename:
117
undercover? (true/false):
false
Hello, I am Agent 117.
My real name is Bob.
I am 25 years old.
Exp. Name: Constructor Overloading and Date: 2025-10-
[Link]: 9

Page No: 24
Default Constructor 22

Aim:
You are given a Java program that demonstrates the concept of constructor overloading.

0 G 5 0 A 1 Q B 4 2 : DI
The class Test contains:
1. Two private integer variables i and j.
2. Three overloaded constructors:
• A default constructor that sets both i and j to 0.
• A constructor with one parameter that sets i to the given value and j to 0.
• A constructor with two parameters that sets both i and j using the given values.
• Implement a method display() that prints the values of i and j.
3. The program creates three objects of the Test class
• obj1 - created using the default constructor.
• obj2 - created using the constructor with one input value for i.

C- E S C- 8 2 0 2- 4 2 0 2
• obj3 - created using the constructor with two input values for i and j.

Input Format:
• First, obj1 uses the default constructor - no input.
• After displaying obj1, read an integer from the user - this is used for i in obj2.
• After displaying obj2, read two integers - these are used for i and j in obj3.

Vasireddy Venkatadri Institute of Technology


Output Format:
• The program displays the values of i and j for each object in the following format:
Displaying values for obj1:
Value of i: 0
Value of j: 0
Enter a value for i:<i_value>
Displaying values for obj2:
Value of i: <value>
Value of j: 0
Enter a value for i:<i_value>
Enter a value for j:<j_value>
Displaying values for obj3:
Value of i: <i_value>
Value of j: <j_value>

Sample Input:
10
40
50
Sample Output:
Displaying·values·for·obj1:
Value of i: 0

Page No: 25
Value of j: 0
Enter a value for i: 10
Displaying values for obj2:
Value of i: 10
Value of j: 0
Enter a value for i: 40

0 G 5 0 A 1 Q B 4 2 : DI
Enter a value for j: 50
Displaying values for obj3:
Value of i: 40
Value of j: 50

Note:
• Input and output are combined in the test cases. Please ensure your program
takes input and displays output simultaneously, in the same sequence as shown in
the sample interaction.
• Refer to the visible test cases to strictly match the input/output layout.
Source Code:

C- E S C- 8 2 0 2- 4 2 0 2
q21947/[Link]

Vasireddy Venkatadri Institute of Technology


package q21947;

Page No: 26
import [Link];
class Test {
// Private instance variables
private int i;
private int j;

0 G 5 0 A 1 Q B 4 2 : DI
// Default constructor
Test()
{
i=0;j=0;
}
// Parameterized constructor with one parameter
Test(int x)
{
i=x;
j=0;
}

C- E S C- 8 2 0 2- 4 2 0 2
// Parameterized constructor with two parameters
Test(int x, int y)
{
i=x;
j=y;

Vasireddy Venkatadri Institute of Technology


}

// Display function to print the values of i and j


void display()
{
[Link]("Value of i: "+i);
[Link]("Value of j: "+j);
}

}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Test obj1 = new Test();
[Link]("Displaying values for obj1:");
[Link]();
[Link]("Enter a value for i: ");
int value1 = [Link]();
Test obj2 = new Test(value1);
[Link]("Displaying values for obj2:");
[Link]();

Page No: 27
[Link]("Enter a value for i: ");
int value2 = [Link]();
[Link]("Enter a value for j: ");
int value3 = [Link]();
Test obj3 = new Test(value2, value3);

0 G 5 0 A 1 Q B 4 2 : DI
[Link]("Displaying values for obj3:");
[Link]();
[Link]();
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

C- E S C- 8 2 0 2- 4 2 0 2
User Output

Displaying values for obj1:


Value of i: 0
Value of j: 0
Enter a value for i:

Vasireddy Venkatadri Institute of Technology


10
Displaying values for obj2:
Value of i: 10
Value of j: 0
Enter a value for i:
40
Enter a value for j:
50
Displaying values for obj3:
Value of i: 40
Value of j: 50

Test Case - 2

User Output

Displaying values for obj1:


Value of i: 0
Value of j: 0
Enter a value for i:
Displaying values for obj2:
Value of i: 10

Page No: 28
Value of j: 0
Enter a value for i:
20
Enter a value for j:

0 G 5 0 A 1 Q B 4 2 : DI
30
Displaying values for obj3:
Value of i: 20
Value of j: 30

C- E S C- 8 2 0 2- 4 2 0 2
Vasireddy Venkatadri Institute of Technology
Exp. Name: Number and Square - Single Date: 2025-10-
[Link]: 10

Page No: 29
Inheritance 22

Aim:
Create a class named NumberIn with the following attributes:

0 G 5 0 A 1 Q B 4 2 : DI
• An int variable num.
• A method inputNum() that takes user input for the number.

Create a class named SquareOut that inherits from NumberIn and has the following
characteristics:
• A method displaySquare() that prints the square of the entered number to the
console.

Note: The main class has been provided to you in the editor.
Source Code:

C- E S C- 8 2 0 2- 4 2 0 2
q23112/[Link]

package q23112;
import [Link];

// write your code here..


class NumberIn{

Vasireddy Venkatadri Institute of Technology


protected int num;
public void inputNum(){
[Link]("Enter number: ");
Scanner sc=new Scanner([Link]);
num =[Link]();
}
}
class SquareOut extends NumberIn{
public void displaySquare(){
int square = num*num;
[Link](+square);;
}
}
public class MainFunction {
public static void main(String[] args) {
SquareOut squareout = new SquareOut();
[Link]();
[Link]();
}
}
Execution Results - All test cases have succeeded!

Page No: 30
Test Case - 1

User Output

Enter number:

0 G 5 0 A 1 Q B 4 2 : DI
9
81

Test Case - 2

User Output

Enter number:
15
225

C- E S C- 8 2 0 2- 4 2 0 2
Vasireddy Venkatadri Institute of Technology
Date: 2025-11-
[Link]: 11 Exp. Name: Multilevel Inheritance in Java

Page No: 31
04

Aim:
Write a Java program to show multilevel inheritance to manage student information and

0 G 5 0 A 1 Q B 4 2 : DI
calculate their marks. The program should include the following functionalities:
Student Class:
This class should contain two attributes:
• id (int): Represents the student's ID.
• name (String): Represents the student's name.
Methods:
• setData(int id, String name): To set the student's ID and name.
• displayData(): To display the student's ID and name.
Marks Class (inherits from Student):
This class should contain the following marks:
• javaMarks (float): Marks obtained in Java.

C- E S C- 8 2 0 2- 4 2 0 2
• cMarks (float): Marks obtained in C.
• cppMarks (float): Marks obtained in C++.
Methods:
• setMarks(float javaMarks, float cMarks, float cppMarks): To set the marks for
Java, C, and C++.
• displayMarks(): To display the marks for Java, C, and C++.
Result Class (inherits from Marks):

Vasireddy Venkatadri Institute of Technology


This class should calculate the total and average of the marks.
Methods:
• compute(): To calculate the total and average marks.
• showResult(): To display the total and average marks.

Input Format:
The program should prompt the user for the following inputs:
• Student ID (integer)
• Student Name (string)
• Java Marks (float)
• C Marks (float)
• C++ Marks (float)

Output Format:
The program should output the following:
• Student ID in the format "Id : <id>"
• Student Name in the format "Name : <name>"
• Java Marks in the format "Java marks : <java marks>"
• C Marks in the format "C marks : <c marks>"
• C++ Marks in the format "Cpp marks : <cpp marks>"
• Total Marks in the format "Total : <total>"
• Average Marks in the format "Avg : <avg>"
Source Code:

[Link]

Vasireddy Venkatadri Institute of Technology C- E S C- 8 2 0 2- 4 2 0 2 0 G 5 0 A 1 Q B 4 2 : DI Page No: 32


import [Link];

Page No: 33
class Student
{
int id;
String name;
void setData(int no,String name1)

0 G 5 0 A 1 Q B 4 2 : DI
{
id=no;
name=name1;
}
void displayData()
{
[Link]("Id : "+id);
[Link]("Name : "+name);
}
}
class Marks extends Student{

C- E S C- 8 2 0 2- 4 2 0 2
float javam,cm,cppm;
void setMarks(float java,float c,float cpp)
{
javam=java;
cm=c;
cppm=cpp;
}

Vasireddy Venkatadri Institute of Technology


void displayMarks()
{
[Link]("Java marks : "+javam);
[Link]("C marks : "+cm);
[Link]("Cpp marks : "+cppm);
}
}
class Result extends Marks
{
float total,avg;
void compute()
{
total=javam+cm+cppm;
avg=total/3;;
}
void showResult()
{
[Link]("Total : "+total);
[Link]("Avg : "+avg);
}
}
public class MultilevelInheritance{
public static void main(String args[]) {

Page No: 34
Scanner s=new Scanner([Link]);
Scanner sc=new Scanner([Link]);
Result r = new Result();
[Link]("Id: ");
int id=[Link]();

0 G 5 0 A 1 Q B 4 2 : DI
[Link]("Name: ");
String name = [Link]();
[Link](id, name);
[Link]("Java marks: ");
float jv=[Link]();
[Link]("C marks: ");
float c=[Link]();
[Link]("CPP marks: ");
float cpp=[Link]();
[Link]();
[Link](jv,c,cpp);

C- E S C- 8 2 0 2- 4 2 0 2
[Link]();
[Link]();
[Link]();
}
}

Vasireddy Venkatadri Institute of Technology


Execution Results - All test cases have succeeded!

Test Case - 1

User Output

Id:
1001
Name:
Yamuna
Java marks:
75.5
C marks:
96.5
CPP marks:
87
Id : 1001
Name : Yamuna
C marks : 96.5
Cpp marks : 87.0

Page No: 35
Total : 259.0
Avg : 86.333336

Test Case - 2

0 G 5 0 A 1 Q B 4 2 : DI
User Output

Id:
1000
Name:
Ganga
Java marks:
77
C marks:

C- E S C- 8 2 0 2- 4 2 0 2
85.5
CPP marks:
96.5
Id : 1000
Name : Ganga
Java marks : 77.0

Vasireddy Venkatadri Institute of Technology


C marks : 85.5
Cpp marks : 96.5
Total : 259.0
Avg : 86.333336
Exp. Name: Areas of Shapes Using Date: 2025-10-
[Link]: 12

Page No: 36
Abstract Class 22

Aim:
Create an abstract class called Shape.

0 G 5 0 A 1 Q B 4 2 : DI
• Declare two abstract methods of type double: calculateArea() and
calculatePerimeter(). These methods will be implemented by subclasses.
• Implement a concrete method named displayDetails() that displays information
about the shape, including its area and perimeter.

Next, create a subclass called Circle that extends the Shape class:
• Implement the calculateArea() method in this subclass. It should calculate and
return the area of the circle.
• Implement the calculatePerimeter() method in this subclass. It should calculate
and return the perimeter of the circle.

C- E S C- 8 2 0 2- 4 2 0 2
Note: The main method is already provided
Source Code:

[Link]

Vasireddy Venkatadri Institute of Technology


import [Link];

Page No: 37
abstract class Shape {

double radius;
abstract double calculateArea();
abstract double calculatePerimeter();

0 G 5 0 A 1 Q B 4 2 : DI
public void displayDetails(){
[Link]("Shape details:");
[Link]("Area: " +calculateArea());
[Link]("Perimeter: "+
calculatePerimeter());

}
}
class Circle extends Shape {
double radius;
public Circle(double radius) {

C- E S C- 8 2 0 2- 4 2 0 2
[Link] = radius;
}
@Override
public double calculateArea() {
return [Link] * radius * radius;
// write your code here

Vasireddy Venkatadri Institute of Technology


}
@Override
public double calculatePerimeter() {

// write your code here


return 2*[Link]*radius;
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
[Link]("Enter the radius of the circle: ");
double radius = [Link]();
Circle circle = new Circle(radius);
[Link]();
[Link]();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 38
User Output

Enter the radius of the circle:


3
Shape details:

0 G 5 0 A 1 Q B 4 2 : DI
Area: 28.274333882308138
Perimeter: 18.84955592153876

Test Case - 2

User Output

Enter the radius of the circle:


4.2
Shape details:

C- E S C- 8 2 0 2- 4 2 0 2
Area: 55.41769440932395
Perimeter: 26.389378290154262

Vasireddy Venkatadri Institute of Technology


Date: 2025-11-
[Link]: 13 Exp. Name: Demonstrating super keyword

Page No: 39
04

Aim:
Create a Java Class Using Single Inheritance with a base class Addition consists of

0 G 5 0 A 1 Q B 4 2 : DI
method add()and a derived class Calculation consists of method sub, Demonstrate Super
keyword by calling add() method first from the base class and then its child class method
sub().
Source Code:

q18039/[Link]

package q18039;
import [Link];
class Addition {
void add(int x,int y)

C- E S C- 8 2 0 2- 4 2 0 2
{
[Link]("Addition: "+(x+y));
}
}

class Calculation extends Addition {


void sub(int x,int y)

Vasireddy Venkatadri Institute of Technology


{
[Link](x,y);
[Link]("Subtraction: "+(x-y));
}
}
class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
int x=[Link]();
int y=[Link]();
Calculation ob=new Calculation();
[Link](x,y);
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

Page No: 40
User Output

5
3
Addition: 8

0 G 5 0 A 1 Q B 4 2 : DI
Subtraction: 2

Test Case - 2

User Output

10
15
Addition: 25

C- E S C- 8 2 0 2- 4 2 0 2
Subtraction: -5

Vasireddy Venkatadri Institute of Technology


Exp. Name: Implementation of multiple Date: 2025-10-
[Link]: 14

Page No: 41
inheritance using interface 22

Aim:
You are required to implement the Circle class, which demonstrates multiple inheritance

0 G 5 0 A 1 Q B 4 2 : DI
using interfaces. The provided Shape and Color interfaces define methods that need to
be implemented within the Circle class.

The Shape Interface contains two methods:


• double calculateArea(): To calculate the area of the circle.
• double calculatePerimeter(): To calculate the perimeter of the circle.
The Color Interface contains one method:
• String getColor(): To get the color of the circle.

Implement a Circle class that implements both Shape and Color interfaces.
In this class, define the methods calculateArea(), calculatePerimeter(), and getColor() to

C- E S C- 8 2 0 2- 4 2 0 2
calculate the area and perimeter of the circle, and return the color.

Input Format:
The program will prompt the user to input:
• "Radius of the circle: " followed by radius of the circle as a double value.
• "Color of the circle: " followed by color of the circle as a String.

Vasireddy Venkatadri Institute of Technology


Output Format:
The program will output the following:
• "Circle Area: " followed by area of the circle formatted to two decimal places.
• "Circle Perimeter: " followed by perimeter of the circle formatted to two decimal
places.
• "Circle Color: " followed by color of the circle.

Note:
• Use [Link] for pi value.
Source Code:

q27463/[Link]
package q27463;

Page No: 42
import [Link];

interface Shape {
double calculateArea();
double calculatePerimeter();

0 G 5 0 A 1 Q B 4 2 : DI
}
interface Color {
String getColor();
}
class Circle implements Shape, Color {
private double radius;
private String color;
//write your code here
public Circle(double radius,String color)
{
[Link]=radius;

C- E S C- 8 2 0 2- 4 2 0 2
[Link]=color;
}
public double calculateArea(){
return [Link]*radius*radius;
}
public double calculatePerimeter(){
return 2*[Link]*radius;

Vasireddy Venkatadri Institute of Technology


}
public String getColor()
{
return color;
}

}
public class MultipleInheritance {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Radius of the circle: ");
double radius = [Link]();
[Link]();
[Link]("Color of the circle: ");
String color = [Link]();
Circle circle = new Circle(radius, color);

// Formatting double values to 2 decimal places


[Link]("Circle Area: %.2f%n",
[Link]());
[Link]("Circle Perimeter: %.2f%n",
[Link]());

Page No: 43
[Link]("Circle Color: " + [Link]());

[Link]();
}
}

0 G 5 0 A 1 Q B 4 2 : DI
Execution Results - All test cases have succeeded!

Test Case - 1

User Output

Radius of the circle:


2.0

C- E S C- 8 2 0 2- 4 2 0 2
Color of the circle:
red
Circle Area: 12.57
Circle Perimeter: 12.57
Circle Color: red

Vasireddy Venkatadri Institute of Technology


Test Case - 2

User Output

Radius of the circle:


5.0
Color of the circle:
violet
Circle Area: 78.54
Circle Perimeter: 31.42
Circle Color: violet

Test Case - 3

User Output

Radius of the circle:


3.0
Color of the circle:
blue
Circle Color: blue

Vasireddy Venkatadri Institute of Technology C- E S C- 8 2 0 2- 4 2 0 2 0 G 5 0 A 1 Q B 4 2 : DI Page No: 44


Exp. Name: Polymorphism - Area of Date: 2025-10-
[Link]: 15

Page No: 45
Geometric shapes 22

Aim:
Write a Java program that provides an interactive menu for users to perform calculations

0 G 5 0 A 1 Q B 4 2 : DI
on 2D shapes. The program should allow users to calculate the area of different shapes:
circle and square. Implement the program using the concept of inheritance and method
overriding to achieve runtime polymorphism.
Source Code:

[Link]

C- E S C- 8 2 0 2- 4 2 0 2
Vasireddy Venkatadri Institute of Technology
import [Link];

Page No: 46
abstract class Shape {
abstract double calculateArea();
}
class Circle extends Shape{

0 G 5 0 A 1 Q B 4 2 : DI
double radius;
Circle(double rad){
radius=rad;
}
double calculateArea(){
return [Link]*radius*radius;

}
}
class Square extends Shape{
double side;

C- E S C- 8 2 0 2- 4 2 0 2
Square(double s){
side=s;
}
double calculateArea(){
return side*side;
}
}

Vasireddy Venkatadri Institute of Technology


class ShapeCalculator{
public static void main(String args[]){
int ch;
do{
[Link]("Select an option:");
[Link]("1. Area of Circle");
[Link]("2. Area of Square");
[Link]("3. Exit");
Scanner sc=new Scanner([Link]);
[Link]("Enter option: ");
ch=[Link]();
switch(ch){
case 1: [Link]("radius:
");
double
rad=[Link]();
Circle c=new Circle(rad);
[Link]("Area:
"+[Link]());
break;
case 2:[Link]("side:
");
double

Page No: 47
side=[Link]();
Square s=new
Square(side);
[Link]("Area:
"+[Link]());

0 G 5 0 A 1 Q B 4 2 : DI
break;
case 3:return;

default:[Link]("Invalid choice");
}
}while(ch!=0);
}
}
//write your code here..

C- E S C- 8 2 0 2- 4 2 0 2
Execution Results - All test cases have succeeded!

Test Case - 1

User Output

Select an option:

Vasireddy Venkatadri Institute of Technology


1. Area of Circle
2. Area of Square
3. Exit
Enter option:
1
radius:
3.75
Area: 44.178646691106465
Select an option:
1. Area of Circle
2. Area of Square
3. Exit
Enter option:
2
side:
40
Area: 1600.0
Select an option:
1. Area of Circle
3. Exit
Enter option:

Page No: 48
5
Invalid choice
Select an option:
1. Area of Circle

0 G 5 0 A 1 Q B 4 2 : DI
2. Area of Square
3. Exit
Enter option:
3

Test Case - 2

User Output

Select an option:

C- E S C- 8 2 0 2- 4 2 0 2
1. Area of Circle
2. Area of Square
3. Exit
Enter option:
1
radius:

Vasireddy Venkatadri Institute of Technology


3.3578
Area: 35.4208943214851
Select an option:
1. Area of Circle
2. Area of Square
3. Exit
Enter option:
5
Invalid choice
Select an option:
1. Area of Circle
2. Area of Square
3. Exit
Enter option:
3
Date: 2025-11-
[Link]: 16 Exp. Name: Exception Handling

Page No: 49
04

Aim:
Write a Java program that demonstrates the use of exception handling for the following

0 G 5 0 A 1 Q B 4 2 : DI
scenarios:
1. Divide by zero (ArithmeticException)
2. Accessing an invalid index in an array (ArrayIndexOutOfBoundsException)
3. Using a method on a null object (NullPointerException)

The program should prompt the user for inputs in sequence, perform each operation, and
handle exceptions using try-catch blocks, printing appropriate error messages or results.

Input and Output Format (in order of execution):


Division Operation:
Input:

C- E S C- 8 2 0 2- 4 2 0 2
• First line prompts "Enter the numerator: " followed by an integer input for the
numerator.
• The second line prompts "Enter the denominator: " followed by an integer input for
the denominator.
Output:
• If the denominator is 0, print: "ArithmeticException: Division by zero is not allowed."
• Otherwise, print: "Result of division: <result>"

Vasireddy Venkatadri Institute of Technology


Note: Handle ArithmeticException for division by zero.

Array Access Operation:


Input:
• Third line prompts "Enter the index to access in the array: " followed by an integer
input.
• Use a predefined array {1, 2, 3, 4, 5}.
Output:
• If the index is invalid, print: "ArrayIndexOutOfBoundsException: Index is out of
bounds."
• Otherwise, print: "Value at index <index>: <value>"
Note: Handle ArrayIndexOutOfBoundsException for invalid indices.

String Length Operation:


Input:
• Foutrh line prompts "Enter a string (or 'null' to simulate null pointer exception): "
followed by a string input
• If the input is the literal string "null", treat it as a null reference.
Output:
• If the string is null: "NullPointerException: Cannot perform operations on a null
reference."
• Otherwise, print: "Length of the string: <length>"
Note: Handle NullPointerException when attempting to call .length() on a null string.

Page No: 50
Refer to the visible testcases for better understanding and to match with the print
statements.
Source Code:

[Link]

0 G 5 0 A 1 Q B 4 2 : DI
C- E S C- 8 2 0 2- 4 2 0 2
Vasireddy Venkatadri Institute of Technology
import [Link];

Page No: 51
public class ExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Scenario 1: Divide by Zero (ArithmeticException)
[Link]("Enter the numerator: ");

0 G 5 0 A 1 Q B 4 2 : DI
int numerator = [Link]();
[Link]("Enter the denominator: ");
int denominator = [Link]();

try {
int res=numerator/denominator;
[Link]("Result of division: "+res);
} catch (ArithmeticException e ) {
[Link]("ArithmeticException:
Division by zero is not allowed.");
}

C- E S C- 8 2 0 2- 4 2 0 2
// Scenario 2: Array Index Out of Bounds
(ArrayIndexOutOfBoundsException)
int[] numbers = { 1, 2, 3, 4, 5 };
[Link]("Enter the index to access in the array:
");
int index = [Link]();

Vasireddy Venkatadri Institute of Technology


try {
[Link]("Value at index %d:
%d\n",index,numbers[index]);
} catch (ArrayIndexOutOfBoundsException a) {

[Link]("ArrayIndexOutOfBoundsException: Index is out


of bounds.");
}

// Scenario 3: Null Pointer Exception


(NullPointerException)
[Link]("Enter a string (or 'null' to simulate
null pointer exception): ");
String input = [Link]();
if([Link]("null")){
input=null;
}
try {
[Link]("Length of the string:
"+[Link]());
} catch (NullPointerException n) {
[Link]("NullPointerException: Cannot

Page No: 52
perform operations on a null reference.");
}

[Link]();
}

0 G 5 0 A 1 Q B 4 2 : DI
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output

Enter the numerator:

C- E S C- 8 2 0 2- 4 2 0 2
6
Enter the denominator:
3
Result of division: 2
Enter the index to access in the array:
1

Vasireddy Venkatadri Institute of Technology


Value at index 1: 2
Enter a string (or 'null' to simulate null pointer exception):
null
NullPointerException: Cannot perform operations on a null
reference.

Test Case - 2

User Output

Enter the numerator:


3
Enter the denominator:
0
ArithmeticException: Division by zero is not allowed.
Enter the index to access in the array:
6
ArrayIndexOutOfBoundsException: Index is out of bounds.
Enter a string (or 'null' to simulate null pointer exception):
hello
Exp. Name: Multiple Catch blocks using Date: 2025-11-
[Link]: 17

Page No: 53
command line arguments 04

Aim:
Write a Java Program to illustrate Multiple Catch blocks using command line argument.

0 G 5 0 A 1 Q B 4 2 : DI
Refer to the sample test case provided to write the code.

Input Format:
The program takes two command-line arguments:
• The first argument is the numerator (an integer).
• The second argument is the denominator (an integer).

Output Format:
• If both inputs are valid integers, print the result of the division in the format:
"Division: result"
• If the denominator is zero, print: "Cannot divide with zero"

C- E S C- 8 2 0 2- 4 2 0 2
• If the inputs are not valid integers, print: "Input is not of integer type"
• If there are insufficient inputs, print: "Insufficient inputs"
Source Code:

q27498/[Link]

Vasireddy Venkatadri Institute of Technology


package q27498;

Page No: 54
public class PrintDivMain {
public static void main(String[] args) {
try {
//two command-line arguments converted into
integer values

0 G 5 0 A 1 Q B 4 2 : DI
//write your code here
int a=[Link](args[0]);
int b=[Link](args[1]);

try{
//perform divison operation and catch
exception
//write your code here
[Link]("Division: "+a/b);
}
catch( ArithmeticException e ){

C- E S C- 8 2 0 2- 4 2 0 2
//write your code here
[Link]("Cannot divide with
zero");
}
}
catch(ArrayIndexOutOfBoundsException e ){
//write your code here

Vasireddy Venkatadri Institute of Technology


[Link]("Insufficient inputs");
}
catch( NumberFormatException e ){
//write your code here
[Link]("Input is not of integer
type");

}
}
}

Execution Results - All test cases have succeeded!

Test Case - 1

User Output

Input is not of integer type


Test Case - 2

Page No: 55
User Output

Division: 0

0 G 5 0 A 1 Q B 4 2 : DI
Test Case - 3

User Output

Cannot divide with zero

Test Case - 4

User Output

Insufficient inputs

C- E S C- 8 2 0 2- 4 2 0 2
Vasireddy Venkatadri Institute of Technology
Date: 2025-12-
[Link]: 18 Exp. Name: Cube root calculator

Page No: 56
10

Aim:
Divijoy is creating a calculator application that returns the cube root of the given number.

0 G 5 0 A 1 Q B 4 2 : DI
He wants to write Java code for his application that handles multiple exceptions such as
input other than a double or a negative number in a single catch block.

What will be the code that perfectly handles the case that Divijoy wants to perform?

Input Format:
• The input line reads a double value.

Output Format:
• The output is a double representing the cube root of the given number if the user
enters the valid input, Otherwise, it will print An error occurred: Invalid input

C- E S C- 8 2 0 2- 4 2 0 2
format if the user enters non-numeric value or it will print An error occurred:
Cannot calculate cube root of a negative number if the user enters a negative
number.
Source Code:

q28900/[Link]

Vasireddy Venkatadri Institute of Technology


package q28900;

Page No: 57
import [Link].*;

public class CubeRootCalculator {


// write your code here
public static void main(String args[])

0 G 5 0 A 1 Q B 4 2 : DI
{
Scanner sc=new Scanner([Link]);

try {
// write your code here
String input=[Link]();
double number=[Link](input);
if(number<0)
{

C- E S C- 8 2 0 2- 4 2 0 2
throw new
IllegalArgumentException("Cannot calculate cube root of a
negative number");
}
double cubeRoot=[Link](number);
[Link]("%.1f%n",cubeRoot);
} catch ( NumberFormatException e ) {

Vasireddy Venkatadri Institute of Technology


// write your code here
[Link]("An error occurred:
Invalid input format");
} catch( IllegalArgumentException e ) {
[Link]("An error occurred: " +
[Link]());
} catch ( Exception e ) {
[Link]("An error occurred: " +
[Link]());
} finally {
[Link]();}
}

Execution Results - All test cases have succeeded!

Test Case - 1
User Output

Page No: 58
64
4.0

Test Case - 2

0 G 5 0 A 1 Q B 4 2 : DI
User Output

-64
An error occurred: Cannot calculate cube root of a negative
number

Test Case - 3

User Output

C- E S C- 8 2 0 2- 4 2 0 2
CodeTantra
An error occurred: Invalid input format

Vasireddy Venkatadri Institute of Technology


Exp. Name: Exception Handling using Date: 2025-12-
[Link]: 19

Page No: 59
Custom Exception Weight Limit 10

Aim:
Write a Java program to handle user user-defined exception. Create a user exception and

0 G 5 0 A 1 Q B 4 2 : DI
then check the validity of a given weight input and throw the custom exception if the
weight exceeds a specified limit, as shown in the sample test case.

Input Format:
• The input contains an integer value for the weight.

Output Format:
• If the entered weight is valid (≤100), the program displays a message indicating
it's valid.
• If the entered weight exceeds 100, the program throws an InvalidWeight exception
and catches it, displaying an error message.

C- E S C- 8 2 0 2- 4 2 0 2
Note:
• Refer to the visible test cases to strictly match with the input/output layout.
Source Code:

[Link]

Vasireddy Venkatadri Institute of Technology


/*import [Link].*;

Page No: 60
import [Link].*;
class InvalidWeight extends Exception {
// Write your code here..

0 G 5 0 A 1 Q B 4 2 : DI
}
class CheckWeight {
// Write your code here..

C- E S C- 8 2 0 2- 4 2 0 2
public static void main(String args[]) {
CheckWeight cw = new CheckWeight();
Scanner sc = new Scanner([Link]);
int weight;
[Link]("Enter weight: ");
weight = [Link]();

Vasireddy Venkatadri Institute of Technology


try {
[Link](weight);
} catch(InvalidWeight iw) {
[Link]("Exception caught: " +
[Link]());
}
}

}
*/
import [Link].*;
class CheckWeight{
public void validWeight(int weight) throws InvalidWeight{
if(weight>100){
throw new InvalidWeight("Exception
caught: "+weight+" is invalid weight");
}
[Link](+weight+" is the valid
weight");
}
public static void main(String args[]){
CheckWeight check = new CheckWeight();
Scanner scanner=new Scanner([Link]);

Page No: 61
try{
[Link]("Enter weight: ");
int weight=[Link]();
[Link](weight);
}

0 G 5 0 A 1 Q B 4 2 : DI
catch(InvalidWeight e){
[Link]([Link]());
}finally{
[Link]();
}
}
}
class InvalidWeight extends Exception{
public InvalidWeight(String message){
super(message);
}

C- E S C- 8 2 0 2- 4 2 0 2
}

Execution Results - All test cases have succeeded!

Test Case - 1

Vasireddy Venkatadri Institute of Technology


User Output

Enter weight:
101
Exception caught: 101 is invalid weight

Test Case - 2

User Output

Enter weight:
1000
Exception caught: 1000 is invalid weight

Test Case - 3

User Output

Enter weight:
99
Date: 2025-12-
[Link]: 20 Exp. Name: Producer Consumer Concept

Page No: 62
10

Aim:
Write a Java program using synchronized threads, which demonstrates producer

0 G 5 0 A 1 Q B 4 2 : DI
consumerconcept.

The Producer-Consumer problem is a classic synchronization problem in computer


science. It involves two types of threads:
• Producer: This thread generates data (e.g., items) and places it in a shared
resource (like a buffer).
• Consumer: This thread takes data (items) from the shared resource for processing
or consumption.

The problem revolves around coordinating these threads such that:


• The producer does not produce when the buffer is full.

C- E S C- 8 2 0 2- 4 2 0 2
• The consumer does not consume when the buffer is empty.
• Both threads operate safely without corrupting the shared resource.

To achieve synchronization in Java, we can use the synchronized keyword along with
wait and notify methods to control the interaction between the threads.

Input Format:

Vasireddy Venkatadri Institute of Technology


• Prompt the user to enter an integer representing the number of items to produce
along with a print statement "Enter the number of items to produce: "

Output Format:
Output should print the following:
• Messages indicating the production of each item as <Produced: {Produced item}>
• Messages indicating the consumption of each item as <Consumed: {Consumed
item}>
Source Code:

q28802/[Link]
package q28802;

Page No: 63
import [Link];
import [Link];
class Producer implements Runnable{
private final LinkedList<Integer> list;
private final Object lock;

0 G 5 0 A 1 Q B 4 2 : DI
private final int maxItems;
public Producer(LinkedList<Integer> list,Object lock,int
maxItems)
{
[Link]=list;
[Link]=lock;
[Link]=maxItems;
}
public void run()
{
for(int i=1;i<=maxItems;i++)

C- E S C- 8 2 0 2- 4 2 0 2
{
synchronized(lock)
{
[Link](i);

[Link]("Produced: "+i);
[Link]();

Vasireddy Venkatadri Institute of Technology


try{

if(i<maxItems){

[Link]();
}

}catch(InterruptedException e){

[Link]().interrupt();
}
}
}
}
}
class Consumer implements Runnable
{
private final LinkedList<Integer> list;
private final Object lock;
private final int maxItems;
public Consumer(LinkedList<Integer> list,Object
lock,int maxItems)
{

Page No: 64
[Link]=list;
[Link]=lock;
[Link]=maxItems;
}
public void run(){

0 G 5 0 A 1 Q B 4 2 : DI
for(int i=1;i<=maxItems;i++){
synchronized(lock){
while([Link]()){
try{

[Link]();

}catch(InterruptedException e){

[Link]().interrupt();
}

C- E S C- 8 2 0 2- 4 2 0 2
}
int
consItem=[Link]();

[Link]("Consumed: "+consItem);
[Link]();
}

Vasireddy Venkatadri Institute of Technology


}
}
}

public class ProducerConsumerDemo {


public static void main(String args[]){
Scanner scan=new Scanner([Link]);
[Link]("Enter the number of items to
produce: ");
int numOfItems=[Link]();
LinkedList<Integer> list=new LinkedList<>();
Object lock=new Object();
Thread pro=new Thread(new
Producer(list,lock,numOfItems));
Thread con=new Thread(new
Consumer(list,lock,numOfItems));
[Link]();
[Link]();
}

}
Execution Results - All test cases have succeeded!

Page No: 65
Test Case - 1

User Output

Enter the number of items to produce:

0 G 5 0 A 1 Q B 4 2 : DI
3
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3

Test Case - 2

C- E S C- 8 2 0 2- 4 2 0 2
User Output

Enter the number of items to produce:


4
Produced: 1
Consumed: 1

Vasireddy Venkatadri Institute of Technology


Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Exp. Name: A Java program to illustrate Date: 2025-12-
[Link]: 21

Page No: 66
creation of threads using Runnable 10

Aim:
Write a java program to illustrate creation of threads using Runnable Interface(start

0 G 5 0 A 1 Q B 4 2 : DI
method start each of the newly created thread. Inside the run method there is
sleep() for suspend the thread for 500 milliseconds).
Sample Input and Sample Output:

Good Morning
Good Morning
Hello
Good Morning
Hello
Welcome
Good Morning

C- E S C- 8 2 0 2- 4 2 0 2
Hello
Welcome
Good Morning
Hello
Welcome
Hello
Welcome

Vasireddy Venkatadri Institute of Technology


Welcome

Source Code:

q19/[Link]
package q19;

Page No: 67
import [Link];

0 G 5 0 A 1 Q B 4 2 : DI
import [Link];
class MessagePrinter implements Runnable{
private final String message;
public MessagePrinter(String message){
[Link]=message;
}
public void run(){
try{
[Link](500);
[Link](message);
}catch(InterruptedException e){

C- E S C- 8 2 0 2- 4 2 0 2
[Link]().interrupt();
}
}
}
public class MyThread{
public static void main(String args[]){
String[] messages={"Good

Vasireddy Venkatadri Institute of Technology


Morning","Hello","Welcome"};
List<Thread>threads=new ArrayList<>();
for(int i=0;i<5;i++){
for(String message:messages){
Thread thread=new Thread(new
MessagePrinter(message));
[Link](thread);
[Link]();
}
}
for(Thread thread:threads){
try{
[Link]();
}catch(InterruptedException e){

[Link]().interrupt();
}
}
}
}
Execution Results - All test cases have succeeded!

Page No: 68
Test Case - 1

User Output

Good Morning

0 G 5 0 A 1 Q B 4 2 : DI
Good Morning
Hello
Good Morning
Hello
Welcome
Good Morning
Hello
Welcome
Good Morning
Hello

C- E S C- 8 2 0 2- 4 2 0 2
Welcome
Hello
Welcome
Welcome

Vasireddy Venkatadri Institute of Technology


Date: 2025-12-
[Link]: 22 Exp. Name: Daemon Threads

Page No: 69
10

Aim:
Create a Java program that demonstrates the use of user and daemon threads.

0 G 5 0 A 1 Q B 4 2 : DI
Implement a class WorkerThread that extends Thread and overrides the run method to
simulate some work by printing messages and sleeping for a short duration.

In the DaemonThread class:


1. Prompt the user to input the number of user threads and daemon threads.
2. Create and start the specified number of user threads and daemon threads.
• User Threads: These threads will run to completion and are not interrupted by the
main [Link] Threads: These threads will run in the background and may
be terminated abruptly when the main thread exits.
3. The main thread should print a message indicating its exit after creating the threads.

C- E S C- 8 2 0 2- 4 2 0 2
Input Format:
• The first line contains an integer specifying the number of user threads.
• The second line contains an integer specifying the number of daemon threads.

Output Format:
The output should display the following:
• Messages indicating the start and finish of each user thread.

Vasireddy Venkatadri Institute of Technology


• Messages indicating the start and finish of each daemon thread.
• A message indicating that the main thread is exiting as: "Main thread exiting".

Note:
• Ensure that daemon threads are correctly set using setDaemon(true) before
calling start().
• Refer to visible test cases for better understanding and to match with input/output
layout.
Source Code:

[Link]
import [Link];

Page No: 70
class WorkerThread extends Thread {

private int id;


public WorkerThread(int id){

0 G 5 0 A 1 Q B 4 2 : DI
[Link]=id;
}
@Override
public void run(){
[Link]("Thread " + id + " started");
try{
//Simulate some work with sleep
[Link](1000);
}catch (InterruptedException e ){
[Link]();
}

C- E S C- 8 2 0 2- 4 2 0 2
[Link]("Thread " + id + " finished");
}
}

Vasireddy Venkatadri Institute of Technology


public class DaemonThread {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter the number of user threads: ");


int numUserThreads = [Link]();

[Link]("Enter the number of daemon threads: ");


int numDaemonThreads = [Link]();

for(int i=1;i <= numUserThreads; i++){


WorkerThread userThread=new
WorkerThread(i);
[Link]();
}
// Create daemon threads
for(int i = 1;i <= numDaemonThreads; i++){
WorkerThread daemonThread=new
WorkerThread(i);
[Link](true);
[Link]();
}

Page No: 71
[Link]("Main thread exiting");
}
}

0 G 5 0 A 1 Q B 4 2 : DI
Execution Results - All test cases have succeeded!

Test Case - 1

User Output

Enter the number of user threads:


3
Enter the number of daemon threads:
2

C- E S C- 8 2 0 2- 4 2 0 2
Main thread exiting
Thread 2 started
Thread 3 started
Thread 1 started
Thread 2 started
Thread 1 started

Vasireddy Venkatadri Institute of Technology


Thread 1 finished
Thread 1 finished
Thread 2 finished
Thread 2 finished
Thread 3 finished

Test Case - 2

User Output

Enter the number of user threads:


2
Enter the number of daemon threads:
3
Main thread exiting
Thread 3 started
Thread 2 started
Thread 1 started
Thread 1 started
Thread 2 started
Thread 2 finished
Thread 1 finished
Thread 1 finished

Vasireddy Venkatadri Institute of Technology C- E S C- 8 2 0 2- 4 2 0 2 0 G 5 0 A 1 Q B 4 2 : DI Page No: 72


Exp. Name: Arithmetic operations using Date: 2025-12-
[Link]: 24

Page No: 73
packages 10

Aim:
Write a java program to create a user-defined package called “data” and perform

0 G 5 0 A 1 Q B 4 2 : DI
Arithmetic operations (addition, subtraction, multiplication, divison) using packages.

Note: Write the required operations in the data/[Link] file.


Source Code:

data/[Link]

package data;
public class Arithmetic
{
public static int add(int a,int b)

C- E S C- 8 2 0 2- 4 2 0 2
{
return a+b;
}
public static int subtract(int a,int b)
{
return a-b;
}

Vasireddy Venkatadri Institute of Technology


public static int multiply(int a,int b)
{
return a*b;
}
public static double divide(int a,int b)
{
return (double)a/b;
}
}

[Link]
import [Link];

Page No: 74
import [Link].*;
public class ArithmeticMain {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("First number: ");

0 G 5 0 A 1 Q B 4 2 : DI
int a = [Link]();
[Link]("Second number: ");
int b = [Link]();
[Link]("Sum: " + [Link](a, b));
[Link]("Difference: " +
[Link](a, b));
[Link]("Product: " + [Link](a,
b));
if (b != 0) {
[Link]("Divison: " + [Link](a,
b));

C- E S C- 8 2 0 2- 4 2 0 2
} else {
[Link]("Cannot divide by zero");
}
}
}

Vasireddy Venkatadri Institute of Technology


Execution Results - All test cases have succeeded!

Test Case - 1

User Output

First number:
12
Second number:
10
Sum: 22
Difference: 2
Product: 120
Divison: 1.2

Test Case - 2

User Output

First number:
Second number:
0

Page No: 75
Sum: 25
Difference: 25
Product: 0
Cannot divide by zero

0 G 5 0 A 1 Q B 4 2 : DI
C- E S C- 8 2 0 2- 4 2 0 2
Vasireddy Venkatadri Institute of Technology

You might also like