0% found this document useful (0 votes)
23 views121 pages

Ilovepdf - Merged (1) - Merged

The document outlines various programming problems that require the implementation of algorithms in Java. Key tasks include calculating BMI, summing digits, estimating utility bills, finding repeated elements in arrays, and converting numbers to Roman numerals. Each problem is accompanied by a code snippet to illustrate the solution approach.

Uploaded by

asterix.120887
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)
23 views121 pages

Ilovepdf - Merged (1) - Merged

The document outlines various programming problems that require the implementation of algorithms in Java. Key tasks include calculating BMI, summing digits, estimating utility bills, finding repeated elements in arrays, and converting numbers to Roman numerals. Each problem is accompanied by a code snippet to illustrate the solution approach.

Uploaded by

asterix.120887
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
You are on page 1/ 121

Problem Statement

John is a fitness trainer, and he wants to use the BMI calculator to assess the body
mass index of his clients. He has a list of clients with their height (in meters) and weight
(in kilograms).

John plans to write a program to quickly determine the BMI and provide a classification
for each client.
1. If BMI is less than 18.5, the program will classify it as "Underweight"

2. If BMI is between 18.6 and 24.9, the program will classify it as "Normal Weight"

3. If BMI is between 25.0 and 29.9, the program will classify it as "Overweight"

4. If BMI is 30.0 or higher, the program will classify it as "Obese"

Formula to calculate BMI = weight/(height*height)


import java.util.Scanner;

public class Main {

public static void main(String[]arg){

Scanner scanner = new Scanner(System.in);

double height=scanner.nextDouble();

double weight=scanner.nextDouble();

double bmi=(weight/(height*height));

String category;

if (bmi<18.5){

category="underweight";

}else if (bmi>=18.6 && bmi<=24.9){

category="normal weight";

}else if (bmi==25.0 && bmi<=29.9){

category="overweight";

}else{

category= "obese";
}

System.out.printf("BMI:"+"%.2f",bmi);

System.out.println("classification:"+category);

scanner.close();

Problem Statement

Alice, a math teacher, is creating a programming exercise to help her students practice
multiplying all the odd digits of a given integer. She wants to create a simple program
that takes a positive integer input and finds the product of its odd digits.

Help Alice to complete the program using the 'while' loop.


import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String message="No odd digits found";

int num = scanner.nextInt();

int product=1;

boolean hasOdd=false;

while(num>0){

int digit=num%10;

if(digit%2==1){

product*=digit;

hasOdd=true;

num/=10;

}
if (!hasOdd){

System.out.print(message);

}else{

System.out.print(product);

scanner.close();

Problem Statement

James, a mathematics teacher, is developing a programming exercise to help his


students practice continuously summing the digits of a number until it becomes a single-
digit integer.

He wants to create a simple program using a 'while' loop that takes a positive integer
input and generates the final single-digit result.
import java.util.Scanner;

public class Main{

public static void main(String arg[]){

Scanner sc = new Scanner(System.in);

int n=sc.nextInt();

int originalN=n;

while(n>=10){

int sum=0;

while(n>0){

sum+=n%10;

n/=10;

n=sum;

System.out.println("The single-digit sum of"+originalN+"is"+n+".");


sc.close();

Problem Statement

Ravi wants to estimate the total utility bill for a household based on the consumption of
electricity, water, and gas.

Write a program to calculate the total bill using the following criteria:

1. The cost per unit for electricity is 0.12, for water is 0.05, and for gas is 0.08.

2. A discount is applied to the total cost based on the following conditions:

3. If the total cost is 100 or more, a 10% discount is applied.

4. If the total cost is between 50 and 99.99, a 5% discount is applied.

5. No discount is applied if the total cost is less than 50.

The program should output the total bill after applying the discount with two decimal
places.
import java.util.Scanner;

public class Main{

public static void main(String args[]){

Scanner sc=new Scanner(System.in);

double elec=sc.nextDouble();

double water=sc.nextDouble();

double gas=sc.nextDouble();

double elecCost=elec*0.12;

double waterCost=water*0.05;

double gasCost=gas*0.08;

double total=elecCost+waterCost+gasCost;
double discount=0.0;

if (total>=100){

discount=0.10;

} else if (total>=50 && total <100){

discount=0.05;

double finalBill= total*(1-discount);

System.out.printf("%.2f%n",finalBill);

sc.close();

Problem Statement

Sharon is creating a program that finds the first repeated element in an integer array.
The program should efficiently identify the first element that appears more than once in
the given array. If no such element is found, it should appropriately display a message.

Help Sharon to complete the program.


import java.util.HashSet;

import java.util.Scanner;

import java.util.Set;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();

int[] arr= new int[n];

Set<Integer> seen = new HashSet<>();

int firstRepeated = -1;


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

arr[i] = scanner.nextInt();

if(seen.contains(arr[i])&& firstRepeated == -1){

firstRepeated = arr[i];

seen.add(arr[i]);

if(firstRepeated != -1){

System.out.println(firstRepeated);

} else {

System.out.println("No repeated element found in the array");

scanner.close();

Problem Statement

Sesha is developing a weather monitoring system for a region with multiple weather
stations. Each weather station collects temperature data hourly and stores it in a 2D
array.

Write a program that can add the temperature data from two different weather stations
to create a combined temperature record for the region.

import java.util.Scanner;
public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


int N = scanner.nextInt();

int M = scanner.nextInt();

int[][] matrix1 = new int[N][M];

int[][] matrix2 = new int[N][M];

int[][] result = new int[N][M];

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

for (int j = 0;j<M;j++)

matrix1[i][j] = scanner.nextInt();

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

for (int j = 0;j<M;j++)

matrix2[i][j] = scanner.nextInt();

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

for (int j =0;j<M;j++)

result[i][j] = matrix1[i][j] + matrix2[i][j];

for(int i = 0;i<N;i++){

for (int j = 0;j<M;j++){

System.out.print(result[i][j] +" ");


}

System.out.println();

}
}
Problem Statement

Monica is interested in finding a treasure but the key to opening is to get the sum of the
main diagonal elements and secondary diagonal elements.

Write a program to help Monica find the diagonal sum of a square 2D array.

Note: The main diagonal of the array consists of the elements traversing from the top-
left corner to the bottom-right corner. The secondary diagonal includes elements from
the top-right corner to the bottom-left corner.

import java.util.Scanner;

class DiagonalSum {

public static void main(String[] arg){

Scanner sc= new Scanner(System.in);

int N =sc.nextInt();

sc.nextLine();

int[][] matrix =new int[N][N];

for(int i=0;i<N;i++){

for(int j=0;j<N;j++){
matrix[i][j]=sc.nextInt();

}
int mainDiagonalSum = 0;

int secondaryDiagonalSum = 0;

for (int i = 0; i<N;i++){

mainDiagonalSum += matrix[i][i];

secondaryDiagonalSum += matrix[i][N - 1 - i];


}

System.out.println("Sum of the main diagonal: "+ mainDiagonalSum);

System.out.println("Sum of the secondary diagonal: "+ secondaryDiagonalSum);

sc.close();

}
Problem Statement

Imagine a sports event where participants are ranked based on their performance, and
medals are awarded to the best athletes. In this scenario, you have an array of athletes'
performance scores and you want to identify the k th largest score among all the scores.

import java.util.*;

class KthLargestScore{
public static void main(String[] args){

Scanner sc=new Scanner(System.in);

int N =sc.nextInt();

int[] scores =new int[N];

for (int i =0;i<N;i++){

scores[i]=sc.nextInt();

int k =sc.nextInt();

sc.close();

Arrays.sort(scores);

System.out.println(scores[N-k]);

}
Problem Statement
Meet Jancy, a diligent student learning to master programming. She is working on a
project that requires her to process text data. Today, she needs to convert a given string
to lowercase to ensure consistent and uniform text.

Write a program that takes an input string and converts it to lowercase to help out
Jancy.

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


String input = scanner.nextLine();

String lowerCaseInput = input.toLowerCase();

// Print the result

System.out.println(lowerCaseInput);

scanner.close();

}
Problem Statement

Maya is working on a text analysis project and needs to determine the length of any
string input by the user. Write a program to take a string as input and print its length.

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Read the entire line

String input = scanner.nextLine();

// Find the length of the string


int length = input.length();

// Print the length

System.out.println(length);

scanner.close();

}
Problem Statement

Chetan needs to analyze different strings to determine the count of vowels and check if
vowels are present.

Write a program that accomplishes this task. The program should count all vowels in the
string and identify if at least one vowel exists. Ensure the results are displayed clearly

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Read input string

String input = scanner.nextLine();

int vowelCount = 0;

String vowels = "aeiouAEIOU";

// Loop through each character


for (int i = 0; i < input.length(); i++) {

if (vowels.indexOf(input.charAt(i)) != -1) {

vowelCount++;

// Print number of vowels

System.out.println("Number of vowels: " + vowelCount);

// Print if vowels are present or not

if (vowelCount > 0) {

System.out.println("Vowels are present.");

} else {

System.out.println("Vowels are not present.");

scanner.close();

}
Problem Statement

Kunal is developing a software tool that requires him to efficiently determine the length
of the longest substring without repeating characters from a given string. This capability
is crucial for optimizing search functionality within large text data. The program reads a
string and calculates the length of the longest substring that contains unique characters.

Help Kunal to accomplish his task.

import java.util.Scanner;
import java.util.HashSet;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Read input string

String s = scanner.nextLine();

// Initialize pointers and max length

int maxLength = 0;

int left = 0;

HashSet<Character> set = new HashSet<>();

// Sliding window approach

for (int right = 0; right < s.length(); right++) {

while (set.contains(s.charAt(right))) {

set.remove(s.charAt(left));

left++;
}

set.add(s.charAt(right));

maxLength = Math.max(maxLength, right - left + 1);

// Print result

System.out.println(maxLength);
scanner.close();

}
Problem Statement

Robin is fascinated by ancient Roman numerals and wants to create a program to


convert decimal numbers to Roman numerals. He needs your help to complete the
program.

Roman numerals are represented using the following symbols:

Given an integer, convert it to a Roman numeral.


import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read input integer

int num = scanner.nextInt();

// Arrays to store Roman numeral mappings

int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

String[] symbols =
{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

StringBuilder roman = new StringBuilder();

// Build the Roman numeral

for (int i = 0; i < values.length && num > 0; i++) {

while (num >= values[i]) {

num -= values[i];

roman.append(symbols[i]);

// Print the Roman numeral

System.out.println(roman.toString());

scanner.close();

}
Problem Statement
Consider a scenario where you are tasked with organizing the different possible
subsequences of a word into sorted order. You are given a string, and your goal is to
find and display all the contiguous subsequences (subarrays) of that string.

For instance, if the input string is "FUN", the output should list all possible contiguous
subsequences such as F, U, N, FU, UN, and FUN, arranged in sorted order.

The total number of subarrays for a string of length `n` can be calculated using the
formula n(n+1)/2.

Write a program that generates all subarrays of the given string and prints them in
sorted order.
import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Read the input string

String s = scanner.nextLine();

List<String> subarrays = new ArrayList<>();

// Generate all contiguous subarrays

for (int i = 0; i < s.length(); i++) {

for (int j = i + 1; j <= s.length(); j++) {


subarrays.add(s.substring(i, j));

}
}

// Sort according to rules: first by character, then length

Collections.sort(subarrays, new Comparator<String>() {

@Override

public int compare(String a, String b) {

if (a.charAt(0) != b.charAt(0)) {

return Character.compare(a.charAt(0), b.charAt(0));


} else {

return a.length() - b.length();

});

// Print each subarray on a new line

for (String subarray : subarrays) {

System.out.println(subarray);

scanner.close();

}
Problem Statement

Sarah is organizing a letter-counting game for her friends. She has a string of letters
and wants to identify the first letter that appears more than once. She needs the result
to determine the winner of her game.
Help Sarah by writing a program that finds the first repeating character in the string.

import java.util.HashSet;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Read input string

String s = scanner.nextLine();

HashSet<Character> seen = new HashSet<>();

// Loop through each character

for (char ch : s.toCharArray()) {

if (seen.contains(ch)) {

// First repeating character found

System.out.println(ch);

return;
} else {

seen.add(ch);

scanner.close();

}
Problem Statement

Marina wants to determine whether the sum and difference of two numbers are prime or
not. She needs a program that takes two integers as input, calculates their sum and
difference, and checks if both are prime numbers.

So she wants to write a program that showcases constructor overloading within the
PrimeDecider class, offering three distinct constructors:

 Constructor with two parameters: Initializes num1 and num2 with the given
parameters.

 Constructor with no parameters: Initializes num1 and num2 to 0.

 Constructor with a single parameter: Initializes both num1 and num2 with the
same value provided as the parameter.
import java.util.Scanner;

class PrimeDecider {

private int num1;

private int num2;

// Constructor with no parameters

public PrimeDecider() {

this.num1 = 0;

this.num2 = 0;

// Constructor with one parameter

public PrimeDecider(int num) {


this.num1 = num;

this.num2 = num;

// Constructor with two parameters

public PrimeDecider(int num1, int num2) {

this.num1 = num1;

this.num2 = num2;
}

// Method to check if a number is prime

private boolean isPrime(int n) {

if (n <= 1) {

return false;

if (n == 2) {

return true;

if (n % 2 == 0) {
return false;

for (int i = 3; i <= Math.sqrt(n); i += 2) {

if (n % i == 0) {
return false;

return true;
}

// Method to decide and print the results

public void decide() {

int sum = num1 + num2;

int diff = Math.abs(num1 - num2);

System.out.println("Sum: " + sum + ", Difference: " + diff);

System.out.println(sum + (isPrime(sum) ? " is prime" : " is not prime"));

System.out.println(diff + (isPrime(diff) ? " is prime" : " is not prime"));

}
Problem Statement:

Anu is tasked with creating a program to determine whether a given number or a range
of numbers falls into one of two categories: prime numbers or Fibonacci numbers. There
are two constructors to achieve this task:
Single Number Checker

Constructor: PrimeFibonacciChecker(int number, String type)

Input: A single integer number and a type ("prime" or "fibonacci").

Output: Determine if the provided number is a prime number or part of the Fibonacci
series.
Range Checker

Constructor: PrimeFibonacciChecker(int start, int end, String type)

Input: A range of integers defined by a start and end value, along with a type ("prime" or
"fibonacci").

Output: Find all numbers within the given range that are prime numbers or part of the
Fibonacci series.
import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

class PrimeFibonacciChecker {

private int number;

private int start;

private int end;


private String type;

// Constructor for single number check

public PrimeFibonacciChecker(int number, String type) {

this.number = number;

this.type = type.toLowerCase();

checkSingleNumber();

// Constructor for range check

public PrimeFibonacciChecker(int start, int end, String type) {


this.start = start;

this.end = end;

this.type = type.toLowerCase();

checkRange();
}

// Method to check if a number is prime

private boolean isPrime(int n) {


if (n <= 1) {

return false;

if (n == 2) {

return true;

if (n % 2 == 0) {

return false;
}

for (int i = 3; i <= Math.sqrt(n); i += 2) {

if (n % i == 0) {

return false;

return true;

// Method to check if a number is part of the Fibonacci series

private boolean isFibonacci(int n) {


if (n == 0 || n == 1) {

return true;

int a = 0;
int b = 1;

int c = a + b;

while (c <= n) {

if (c == n) {
return true;

a = b;

b = c;

c = a + b;

return false;

// Method to check a single number

private void checkSingleNumber() {

if (type.equals("prime")) {

if (isPrime(number)) {

System.out.println(number + " is a prime number.");

} else {

System.out.println(number + " is not a prime number.");

} else if (type.equals("fibonacci")) {

if (isFibonacci(number)) {
System.out.println(number + " is part of the Fibonacci series.");

} else {

System.out.println(number + " is not part of the Fibonacci series.");

}
} else {

System.out.println("Invalid");

}
// Method to check a range of numbers

private void checkRange() {

List<Integer> result = new ArrayList<>();

if (type.equals("prime")) {

for (int i = start; i <= end; i++) {

if (isPrime(i)) {

result.add(i);
}

System.out.println("Prime numbers in the range " + start + " to " + end + ": " +
result);

} else if (type.equals("fibonacci")) {

for (int i = start; i <= end; i++) {

if (isFibonacci(i)) {

result.add(i);

}
System.out.println("Fibonacci numbers in the range " + start + " to " + end + ": "
+ result);

} else {

System.out.println("Invalid");

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


String firstLine = scanner.nextLine().trim();
String secondLine = scanner.nextLine().trim();

String[] parts = firstLine.split(" ");

if (parts.length == 1) {

int number = Integer.parseInt(parts[0]);

String type = secondLine;

new PrimeFibonacciChecker(number, type);

} else if (parts.length == 2) {
int start = Integer.parseInt(parts[0]);

int end = Integer.parseInt(parts[1]);

String type = secondLine;

new PrimeFibonacciChecker(start, end, type);

} else {

System.out.println("Invalid");

scanner.close();

}
Problem Statement

You are tasked with developing a program to check for perfect numbers or Armstrong
numbers. Additionally, the program should be able to handle a range of numbers to
check for both types of numbers. The program should perform the following tasks based
on user input.

Create a program to achieve the task.

import java.util.Scanner;
class NumberChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String type = scanner.nextLine().toLowerCase();

if (type.equals("perfect") || type.equals("armstrong")) {

int number = scanner.nextInt();

if (type.equals("perfect")) {
if (isPerfect(number)) {

System.out.println(number + " is a perfect number.");

} else {

System.out.println(number + " is not a perfect number.");

} else {

if (isArmstrong(number)) {

System.out.println(number + " is an Armstrong number.");

} else {

System.out.println(number + " is not an Armstrong number.");

}
}

} else if (type.equals("range")) {

int start = scanner.nextInt();

int end = scanner.nextInt();


for (int i = start; i <= end; i++) {

if (isPerfect(i)) {

System.out.println(i + " is a perfect number.");

}
if (isArmstrong(i)) {

System.out.println(i + " is an Armstrong number.");

scanner.close();

private static boolean isPerfect(int number) {

if (number <= 1) {

return false;

int sum = 1; // 1 is a proper divisor for all numbers > 1

for (int i = 2; i <= Math.sqrt(number); i++) {

if (number % i == 0) {

sum += i;

int complement = number / i;

if (complement != i) {

sum += complement;
}

return sum == number;


}

private static boolean isArmstrong(int number) {

int originalNumber = number;


int digits = String.valueOf(number).length();

int sum = 0;

while (number > 0) {

int digit = number % 10;

sum += Math.pow(digit, digits);

number /= 10;

return sum == originalNumber;


}

}
Problem Statement

Arjun is working on a math project and needs a program to find the average (mean) of
two types of numbers: whole numbers (integers) and numbers with decimal points
(doubles). He wants to write a program but is having trouble with a concept called
"constructor overloading." Arjun needs your help to write a program.

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();

int[] intArray = new int[n];

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

intArray[i] = scanner.nextInt();

}
double[] doubleList = new double[n];

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

doubleList[i] = scanner.nextDouble();

double intSum = 0;

for (int num : intArray) {

intSum += num;
}

double intMean = intSum / n;

double doubleSum = 0;

for (double num : doubleList) {

doubleSum += num;

double doubleMean = doubleSum / n;

System.out.printf("%.2f\n", intMean);

System.out.printf("%.2f\n", doubleMean);

scanner.close();

Problem Statement

You are tasked with creating a program to calculate the speed of highway drivers based
on the distance travelled and the time taken.
Your program should define a class HighwayDriver with the following specifications:

1. The class should have two private member variables:

2. distance (double): representing the distance travelled in miles.

3. time (double): representing the time taken to travel the distance in hours.

4. The class should have two constructors:

5. HighwayDriver(double dist, double hours, double mins): Initializes the distance


and time based on the given parameters. The time parameter is in hours, with an
additional parameter for minutes. It should calculate the speed (distance/time) for
the first driver in miles per hour and display it with two decimal places.

6. HighwayDriver(double dist, double hours): Initializes the distance and time based
on the given parameters. The time parameter is in hours. It should calculate the
speed (distance/time) for the second driver in miles per hour and display it with
two decimal places.

Your task is to implement the HighwayDriver class and the main program to achieve the
specified functionality.
import java.util.Scanner;

class HighwayDriver {
private double distance;

private double time;

// Constructor with distance, hours and minutes

public HighwayDriver(double dist, double hours, double mins) {

this.distance = dist;

this.time = hours + (mins / 60.0);

double speed = this.distance / this.time;


System.out.printf("%.2f mph%n", speed);

// Constructor with distance and hours

public HighwayDriver(double dist, double hours) {

this.distance = dist;

this.time = hours;

double speed = this.distance / this.time;


System.out.printf("%.2f mph%n", speed);

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Reading input for the first driver

double dist1 = sc.nextDouble();

double hours1 = sc.nextDouble();


double mins1 = sc.nextDouble();

// Reading input for the second driver

double dist2 = sc.nextDouble();


double hours2 = sc.nextDouble();

// Creating objects, which automatically print the speed

HighwayDriver driver1 = new HighwayDriver(dist1, hours1, mins1);


HighwayDriver driver2 = new HighwayDriver(dist2, hours2);

sc.close();

}
Problem Statement

Reema, an environmental enthusiast, is conducting research on forest ecosystems. She


needs a program to calculate the annual rainfall for different forest areas.

Write a program that can determine the annual rainfall for square and rectangular
forests based on the provided dimensions (side length, length, and width) and the
average annual rainfall in millimeters (mm)

Create a class Forest and utilize constructor overloading in the Forest class to handle
two types of forests:
1. For Square Forest: annual rainfall = sideLength * sideLength * rainfallinmm

2. For Rectangular Forest: annual rainfall = length * width * rainfallinmm

import java.util.Scanner;

class Forest {

// Constructor for Square Forest

public Forest(double sideLength, double rainfallInMm) {

double annualRainfall = sideLength * sideLength * rainfallInMm;

System.out.printf("%.2f mm%n", annualRainfall);

// Constructor for Rectangular Forest


public Forest(double length, double width, double rainfallInMm, boolean isRectangle)
{

double annualRainfall = length * width * rainfallInMm;


System.out.printf("%.2f mm%n", annualRainfall);

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Reading input for the square forest

double sideLength = sc.nextDouble();

double rainfallSquare = sc.nextDouble();

// Reading input for the rectangular forest

double length = sc.nextDouble();

double width = sc.nextDouble();


double rainfallRectangle = sc.nextDouble();

// Creating objects, which automatically calculate and print rainfall

Forest squareForest = new Forest(sideLength, rainfallSquare);

Forest rectangularForest = new Forest(length, width, rainfallRectangle, true);

sc.close();

}
Problem Statement

Ravi, a marathon enthusiast, requires a program to effortlessly convert distances


between miles and kilometers to maintain consistent records.

The program should take a distance value and a unit indicator ('m' for miles or 'k' for
kilometers) as input and employ constructor overloading within the MarathonRunner
class to perform the conversion between units when needed.

This program will streamline Ravi's record-keeping process and ensure accuracy in his
marathon distance tracking.

import java.util.Scanner;

class MarathonRunner {

// Constructor for miles input

public MarathonRunner(double distance, char unit) {

if (unit == 'm') {

double converted = distance * 1.60934;


System.out.printf("%.2f%n", converted);

} else if (unit == 'k') {


double converted = distance * 1.2;

System.out.printf("%.2f%n", converted);

} else {

System.out.println("Invalid input for unit");

}
public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

double distance = sc.nextDouble();

sc.nextLine(); // consume newline

char unit = sc.nextLine().charAt(0);

MarathonRunner runner = new MarathonRunner(distance, unit);

sc.close();

}
Problem Statement

Rohit wants to develop an interactive square root calculator program. He wants the
program to take the user's name and an integer as input, calculate the square root of
the integer, and display a personalized message using the class CustomClass.

The program must use the instanceof operator to check the presence of specific
instances.

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Reading input

String name = sc.nextLine();

int number = sc.nextInt();


// Checking if name is an instance of String

System.out.println("Name is an instance of String: " + (name instanceof String));

// Calculating and displaying the square root

double sqrtValue = Math.sqrt(number);

System.out.println("Square root of the entered number: " + sqrtValue);

// Creating an instance of CustomClass

CustomClass customObj = new CustomClass(name);

// Printing custom message

customObj.greet();

// Checking if customObj is an instance of CustomClass

System.out.println("customObj is an instance of CustomClass: " + (customObj


instanceof CustomClass));

sc.close();
}

static class CustomClass { // <<<--- notice 'static' added here

private String name;

public CustomClass(String name) {

this.name = name;

}
public void greet() {

System.out.println("CustomClass: Hey, " + name + "! Nice to meet you");

}
Problem Statement

Alice is developing an interactive square calculator program to engage his students. He


wants the program to take the user's name and an integer as input, calculate the square
of the integer, and display a personalized message using the class CustomClass.

Alice is interested in ensuring that the program uses the instanceof operator to check
the presence of specific instances.

import java.util.Scanner;

class CustomClass {

public void displayMessage(String message) {

System.out.println("CustomClass: " + message);

public boolean isInstanceOfCustomClass(CustomClass customObj) {

return customObj instanceof CustomClass;

}
}

class Utility {

public boolean isStringInstance(String name) {

return name instanceof String;


}

public int squareNumber(int number) {

return number * number;

}
Problem Statement

Michael, a computer science student, is working on a project to create a GPA calculator.


He wants to develop a program that accepts grades in different subjects and calculates
the Grade Point Average (GPA) for the student.

Additionally, he aims to determine if the student is eligible for a scholarship based on


their GPA and the number of subjects they've taken. Help him with a suitable program
that uses the 'this' keyword.

// You are using Java

import java.util.Scanner;

class GPA_Calculator {

private int numSubjects;


private double[] grades;

// Constructor to initialize the number of subjects and grades

public GPA_Calculator(int numSubjects, double[] grades) {

this.numSubjects = numSubjects; // Using 'this' to refer to the instance variable

this.grades = grades; // Using 'this' to refer to the instance variable

}
// Method to calculate GPA

public double calculateGPA() {

double sum = 0;

for (double grade : grades) {

sum += grade;

return sum / numSubjects;

// Method to determine scholarship eligibility

public String scholarshipEligibility() {

double gpa = calculateGPA();

if (gpa >= 3.5 && numSubjects >= 5) {

return "Eligible for a scholarship";

} else {

return "Not eligible for a scholarship";

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Read the number of subjects

int numSubjects = scanner.nextInt();

double[] grades = new double[numSubjects];


// Read the grades for each subject

for (int i = 0; i < numSubjects; i++) {

grades[i] = scanner.nextDouble();

// Create an object of GPA_Calculator

GPA_Calculator calculator = new GPA_Calculator(numSubjects, grades);

// Calculate GPA and print it rounded to two decimal places

double gpa = calculator.calculateGPA();

System.out.printf("GPA: %.2f\n", gpa);

// Print the scholarship eligibility status

System.out.println(calculator.scholarshipEligibility());

scanner.close();

}
Problem Statement

Mr. Smith, a mathematics teacher, is developing an interactive cube calculator program


to engage his students. He wants the program to take the user's name and an integer
as input, calculate the cube of the integer, and display a personalized message using
the class CustomClass.

Mr. Smith is interested in ensuring that the program uses the instanceof operator to
check the presence of specific instances.
import java.util.Scanner;

class CustomClass {

public void displayMessage(String name) {

System.out.println("CustomClass: Hello, " + name + "!");

public boolean isInstanceOfCustomClass(Object customObj) {


return customObj instanceof CustomClass;

class CubeCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String name = scanner.nextLine();

int n = scanner.nextInt();

boolean isStringInstance = name instanceof String;

System.out.println("Name is an instance of String: " + isStringInstance);

int cube = n * n * n;

System.out.println("Cube of the entered number: " + cube);


CustomClass customObj = new CustomClass();

customObj.displayMessage(name);

boolean isCustomClassInstance = customObj instanceof CustomClass;


System.out.println("customObj is an instance of CustomClass: " +
isCustomClassInstance);

scanner.close();

}
Problem Statement

Arun is working on a project to convert seconds into a time format. He wants to create a
program that accepts a time duration in seconds and converts it into hours, minutes,
and seconds (hh:mm:ss).To achieve this, you need to design a class called
SecondsToTime that:
 Takes the total time duration in seconds as an input.

 Converts this total time into hours, minutes, and seconds.


 Provides getter and setter methods to access and modify the time values
(hours, minutes, and seconds).

 Displays the time in the hh:mm:ss format.

Formulas used:

hours = total seconds / 3600

totalSeconds = totalSeconds % 3600;


minutes = total seconds / 60

seconds = total seconds % 60

import java.util.Scanner;

class SecondsToTime {

private int hours;

private int minutes;

private int seconds;


public SecondsToTime(int totalSeconds) {

if (totalSeconds < 0) {

return;

this.hours = totalSeconds / 3600;

totalSeconds %= 3600;

this.minutes = totalSeconds / 60;

this.seconds = totalSeconds % 60;

public int getHours() {


return hours;

public int getMinutes() {

return minutes;
}

public int getSeconds() {

return seconds;

}
public void setHours(int hours) {

if (hours >= 0) {

this.hours = hours;

public void setMinutes(int minutes) {

if (minutes >= 0) {

this.minutes = minutes;
}

public void setSeconds(int seconds) {

if (seconds >= 0) {

this.seconds = seconds;

public void displayTime() {

System.out.printf("%02d:%02d:%02d", getHours(), getMinutes(), getSeconds());

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


int totalSeconds = scanner.nextInt();

scanner.close();

SecondsToTime timeConverter = new SecondsToTime(totalSeconds);

timeConverter.displayTime();
}

}
Problem Statement

You are tasked with creating a program that simulates a bank account. The program
should allow a user to input the initial balance and specify the account type (Savings,
Checking, or Other). Based on the account type, the program should calculate and
display the yearly interest.

The yearly interest is calculated as follows:

1. 5% annual interest for Savings accounts

2. 2% annual interest for Checking accounts

3. 1% annual interest for Other account types

Note: Make use of a constructor to initialize the balance and account type while
calculating the interest

import java.util.Scanner;

class BankAccount {

private double balance;


private String accountType;

// Constructor to initialize the balance and account type

public BankAccount(double balance, String accountType) {

this.balance = balance;

this.accountType = accountType;

}
// Method to calculate yearly interest based on account type

public double calculateYearlyInterest() {

double interestRate = 0;

// Determine the interest rate based on account type

if (accountType.equalsIgnoreCase("Savings")) {

interestRate = 0.05; // 5% for Savings

} else if (accountType.equalsIgnoreCase("Checking")) {
interestRate = 0.02; // 2% for Checking

} else if (accountType.equalsIgnoreCase("Other")) {

interestRate = 0.01; // 1% for Other

// Calculate and return the yearly interest

return balance * interestRate;

class Main {
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input: Initial balance and account type


double initialBalance = scanner.nextDouble();

scanner.nextLine(); // Consume the newline character

String accountType = scanner.nextLine();


// Create a BankAccount object

BankAccount account = new BankAccount(initialBalance, accountType);

// Calculate the yearly interest

double yearlyInterest = account.calculateYearlyInterest();

// Output: Yearly interest rounded to one decimal place

System.out.printf("Yearly Interest: Rs. %.1f\n", yearlyInterest);

scanner.close();

}
Problem Statement

John is curious to know how many leap years he has lived through. He wants a program
where he can input his birth year and the current year, and the program calculates the
total number of leap years between them.

Leap Year Conditions:

A year is considered a leap year if:


 It is divisible by 4, and

 It is not divisible by 100 unless it is also divisible by 400.

Implement a class AgeCalculatorFunctions with a constructor


AgeCalculatorFunctions(int birthYear, int currentYear) to initialize the birth year. The
class should contain a method to count the number of leap years from the birth year to
the current year.
// You are using Java

class AgeCalculatorFunctions {
private int birthYear;

private int currentYear;

// Constructor to initialize birthYear and currentYear

public AgeCalculatorFunctions(int birthYear, int currentYear) {

this.birthYear = birthYear;

this.currentYear = currentYear;

// Method to check if a year is a leap year

public boolean isLeapYear(int year) {

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {

return true;

return false;

// Method to count leap years between birthYear and currentYear

public int countLeapYears() {


int leapYearsCount = 0;

// Iterate through each year from birthYear to currentYear

for (int year = birthYear; year <= currentYear; year++) {


if (isLeapYear(year)) {

leapYearsCount++;

}
return leapYearsCount;

class Main {

public static void main(String[] args) {

// Input: birthYear and currentYear


java.util.Scanner scanner = new java.util.Scanner(System.in);

int birthYear = scanner.nextInt();

int currentYear = scanner.nextInt();

// Create an object of AgeCalculatorFunctions

AgeCalculatorFunctions calculator = new AgeCalculatorFunctions(birthYear,


currentYear);

// Output: Count of leap years between birthYear and currentYear

int leapYears = calculator.countLeapYears();


System.out.println(leapYears);

scanner.close();

}
Lab-6

Preethi is working on a project to automate sales tax calculations for items in a store. She wants to
create a program that takes the price of an item and the sales tax rate as input and calculates the
final price of the item after applying the sales tax.

Write a program that handles both integer and double inputs using an overloaded method named
calculateFinalPrice and print the final price of the item.

Formula Used: Final price = price + ((price * sales tax rate) / 100)
class SalesTaxCalculator {

public static int calculateFinalPrice(int price, int taxRate) {

int taxAmount = (price * taxRate) / 100;

return price + taxAmount;

public static double calculateFinalPrice(double price, double taxRate) {

double taxAmount = (price * taxRate) / 100;

return price + taxAmount;

Hari is working on a Java program for his homework to calculate the sum of two and three integers. Write a
program that allows Hari to input two integers and three integers separately. Use overloaded methods called
sum to calculate and display the sum for each case.

Input format :

The first line of input consists of two space-separated integers m and n.

The second line consists of three space-separated integers a, b, and c.


class Summation {

public int sum(int num1, int num2) {

return num1 + num2;

public int sum(int num1, int num2, int num3) {

return num1 + num2 + num3;

}
Hagrid needs a program capable of performing two calculations: square roots and cube roots.

1. When he inputs an integer value, the program calculates the square root and displays the result.

2. Likewise, if he enters a double, he anticipates the program to compute the cube root and display the outcome.

Create a program that enables Hagrid to input a number and then see the result of the respective root calculation. Use method
overloading with the name calculateRoot() for this and also sqrt() and cbrt() functions from the Java library.

import java.util.Scanner;

import java.text.DecimalFormat;

class AdvancedArithmetic {

public double calculateSquareRoot(int num) {

return Math.sqrt(num);

public double calculateCubeRoot(double num) {

return Math.cbrt(num);

public class Main {

public static void main(String[] args) {

AdvancedArithmetic calculator = new AdvancedArithmetic();

Scanner scanner = new Scanner(System.in);

if (scanner.hasNextInt()) {

int intNumber = scanner.nextInt();

double squareRoot = calculator.calculateSquareRoot(intNumber);

System.out.format("%.1f", squareRoot);

} else if (scanner.hasNextDouble()) {

double doubleNumber = scanner.nextDouble();

double cubeRoot = calculator.calculateCubeRoot(doubleNumber);

System.out.format("%.1f", cubeRoot);

scanner.close();

}
Ria is developing a simple educational game for children to test their knowledge of uppercase and lowercase letters. The game will present
four letters, and the children will input their answers for each letter. Her task is to implement a program that calculates the score based on
the following rules:

• For every correct uppercase letter input, the player earns 10 points.

• For every correct lowercase letter input, the player loses 5 points.

• The game presents four letters, and the player will provide their answers one by one.

• After receiving all four answers, the program will display the final score.

import java.util.Scanner;

class QuizGame {

public void game() {

System.out.println("This is a quiz game.");

class StudentScore extends QuizGame {

char a, b, c, d;

int s = 0;

@Override

public void game() {

if (Character.isUpperCase(a)) s += 10; else s -= 5;

if (Character.isUpperCase(b)) s += 10; else s -= 5;

if (Character.isUpperCase(c)) s += 10; else s -= 5;

if (Character.isUpperCase(d)) s += 10; else s -= 5;

System.out.print("Score : " + s);

class QuizGameMain {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

QuizGame game = new StudentScore();

StudentScore student = (StudentScore) game;


student.a = sc.next().charAt(0);

student.b = sc.next().charAt(0);

student.c = sc.next().charAt(0);

student.d = sc.next().charAt(0);

game.game();

sc.close();

Ashok is creating a program that calculates the surface area of a sphere and a cube. There are specific instructions from his professor, that
the program should use runtime polymorphism to handle the different shapes, and he needs your assistance for this.

Question Instructions

import java.util.Scanner;

class Polygon {

public void show(double value) {

System.out.println("Polygon class method.");

class Sphere extends Polygon {

@Override

public void show(double radius) {

double area = 4 * 3.14 * radius * radius;

System.out.printf("Area of Sphere: %.2f%n", area);

class Cube extends Polygon {

public void show(double side) {

double area = 6 * side * side;

System.out.printf("Area of Cube: %.2f%n", area);

class PolygonMain {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

double radius = sc.nextDouble();

double side = sc.nextDouble();

Polygon p;

Sphere s = new Sphere();

Cube c = new Cube();

p = s; // Upcasting to Sphere

p.show(radius); // Calls overridden method in Sphere

p = c; // Upcasting to Cube

p.show(side); // Calls overridden method in Cube

sc.close();

Renu works for a retail store that sells two types of items: wooden items and electronics. The store needs a program to calculate the total
amount for a customer's purchase based on their choice of item type and the quantity or cost of the items.

Create a base class, ItemType, with one virtual function: double calculateAmount()

Create a class called wooden that extends ItemType with a number of items and cost as its private attributes. Obtain the data members
and override the virtual function.

Create a class electronics that extends ItemType with cost as its private attribute. Obtain the data member and override the virtual
function.

In the main method, obtain a choice.

1. If the choice is 1, create an object for the wooden class and call the method.

2. If the choice is 2, create an object for the electronics class and call the method.

import java.util.Scanner;

class ItemType {
public double calculateAmount() {

return 0; // Default implementation (will be overridden)

class Wooden extends ItemType {

private int noOfItems;

private double cost;

public void get(Scanner sc) {

noOfItems = sc.nextInt();

cost = sc.nextDouble();

@Override

public double calculateAmount() {

return noOfItems * cost;

class Electronics extends ItemType {

private double cost;

public void get(Scanner sc) {

cost = sc.nextDouble();

@Override

public double calculateAmount() {

double discount = cost * 0.20;

return cost - discount;

class ItemMain {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int choice = sc.nextInt();


ItemType item; // Parent reference for runtime polymorphism

if (choice == 1) {

item = new Wooden();

((Wooden) item).get(sc);

} else if (choice == 2) {

item = new Electronics();

((Electronics) item).get(sc);

} else {

System.out.println("Invalid choice");

sc.close();

return;

// Calls the overridden method dynamically at runtime

System.out.printf("%.2f", item.calculateAmount());

sc.close();

An ice-cream vendor sells his ice-creams in a cone(radius r and height h) and square(side r) shaped containers. However, he is unsure of
the quantity that can be filled in the two containers.

You are required to write a program that prints the volume of the containers given their respective dimensions as input. Your class must be
named ‘Icecream’ which has two methods with the same name ‘Quantity’ each having the respective dimensions of the containers as the
parameters.

import java.util.Scanner;

class Icecream {

public void quantity() {

class Square extends Icecream {

private int r;

public Square(int side) {

this.r = side;
}

public void quantity() {

double volume = Math.pow(r, 3);

System.out.printf("%.2f%n", volume);

class Cone extends Icecream {

private int r, h;

public Cone(int radius, int height) {

this.r = radius;

this.h = height;

public void quantity() {

double volume = 0.33 * Math.PI * Math.pow(r, 2) * h;

System.out.printf("%.2f%n", volume);

class IcecreamMain {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int choice = sc.nextInt();

Icecream icecream = null; // Parent reference

if (choice == 1) {

int r = sc.nextInt();

icecream = new Square(r);

} else if (choice == 2) {

int r = sc.nextInt();

int h = sc.nextInt();

icecream = new Cone(r, h);

if (icecream != null) {

icecream.quantity();
} else {

System.out.println("Invalid choice");

sc.close();

Lab6

Arun has been assigned the task of writing a program that accepts user input for an Integer and a Character. The program should then use
wrapper classes to convert these inputs into their corresponding primitive types (int, and char) and display the result

class OutputPrinter {

public void printValues(Integer myInt,Character myChar){

System.out.println("Integer Value: "+myInt);

System.out.println("Character value: "+myChar);

Sneha is learning Java and is experimenting with autoboxing and unboxing concepts. She has a list of integers, and she wants to convert
them into a list of Integer objects using autoboxing. After that, she needs to print the sum of the elements using unboxing.

However, her code isn't producing the correct results. Help Sneha debug her program.

import java.util.*;

class Solution {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

List<Integer> list = new ArrayList<>();

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

int num = sc.nextInt();

list.add(num);

int sum = calculateSum(list);

System.out.println(sum);
sc.close();

public static int calculateSum(List<Integer> list) {

int sum = 0;

for (int num : list) {

sum +=num;

return sum;

Arun has been tasked with demonstrating the use of wrapper classes. His task is to accept a string input from the user, which represents a
number, and convert it to the corresponding integer primitive type using the Integer wrapper class.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String numberString = scanner.nextLine();

int number = Integer.parseInt(numberString);

System.out.println("Integer Value: " + number);

scanner.close();

Design a Java program to demonstrate the use of autoboxing (converting primitive types to their corresponding wrapper classes) and
unboxing (converting wrapper classes back to primitive types). The program should allow the user to enter primitive values and display
their equivalent wrapper class objects and vice versa.

The system should perform the following operations:

• Convert primitive types (int, double, char, boolean) to their wrapper class objects.

• Extract the primitive values back from the wrapper objects

import java.util.Scanner;
import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int intValue = scanner.nextInt();

double doubleValue = scanner.nextDouble();

char charValue = scanner.next().charAt(0);

boolean boolValue = scanner.nextBoolean();

Integer intWrapper = intValue;

Double doubleWrapper = doubleValue;

Character charWrapper = charValue;

Boolean boolWrapper = boolValue;

System.out.println("Autoboxing:");

System.out.println("Integer wrapper: " + intWrapper);

System.out.println("Double wrapper: " + doubleWrapper);

System.out.println("Character wrapper: " + charWrapper);

System.out.println("Boolean wrapper: " + boolWrapper);

int unboxedInt = intWrapper;

double unboxedDouble = doubleWrapper;

char unboxedChar = charWrapper;

boolean unboxedBool = boolWrapper;

System.out.println("Unboxing:");

System.out.println("Primitive int: " + unboxedInt);

System.out.println("Primitive double: " + unboxedDouble);

System.out.println("Primitive char: " + unboxedChar);

System.out.println("Primitive boolean: " + unboxedBool);

scanner.close();

Aman wants to create a simple calculator that accepts a single numerical value as a String, converts it into an Integer using Java’s Wrapper
Class, and performs the following operations:

1. Square of the number

2. Cube of the number

3. Square root of the number (rounded to 2 decimal places)


However, his code has some mistakes, causing incorrect calculations. Help Aman debug his program to convert the input and perform the
calculations correctly.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String input = scanner.nextLine();

int number = Integer.parseInt(input);

int square = number * number;

int cube = number * number * number;

double squareRoot = Math.sqrt(number);

System.out.printf("%d %d %.2f", square, cube, squareRoot);

scanner.close();

Aarav is learning about Wrapper Classes and Autoboxing in Java. His mentor gives him a task to store a character and a byte value using
their wrapper classes and then retrieve their original (primitive) values. Help Aarav by writing a program that demonstrates autoboxing and
unboxing using Character and Byte wrapper classes.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

char charValue = scanner.next().charAt(0);

byte byteValue = scanner.nextByte();

Character charWrapper = charValue;

Byte byteWrapper = byteValue;

System.out.println("Displaying values of Wrapper class objects:");

System.out.println("Character object: " + charWrapper);

System.out.println("Byte object: " + byteWrapper);


char unboxedChar = charWrapper;

byte unboxedByte = byteWrapper;

System.out.println("Displaying unwrapped values:");

System.out.println("char value: " + unboxedChar);

System.out.println("byte value: " + unboxedByte);

scanner.close();

Create a program that performs basic arithmetic operations (addition, subtraction, multiplication, and division) on two numbers provided
as input by the user. The program should handle both integers and decimal numbers, ensuring that all results are displayed as double
values rounded to two decimal places.

Use Java's wrapper classes (Integer and Double) to convert the input strings into numeric values, and perform calculations accordingly.

import java.util.Scanner;

class Integer {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String input1 = scanner.nextLine();

String input2 = scanner.nextLine();

Double num1 = Double.valueOf(input1);

Double num2 = Double.valueOf(input2);

double sum = num1 + num2;

double difference = num1 - num2;

double product = num1 * num2;

double division = num1 / num2;

System.out.printf("%.2f%n", sum);

System.out.printf("%.2f%n", difference);

System.out.printf("%.2f%n", product);

System.out.printf("%.2f%n", division);

scanner.close();

Lab-8

Create a program that demonstrates hierarchical inheritance using three classes: Animal, Bird, and Mammal.

An Animal has one member function, eat(); Bird has one member function, fly(); and Mammal has one member function, run().
Derive Bird and Mammal from Animal and override the eat() function in both derived classes to display different messages. Take the input
for the type of animal and output the appropriate message for the eat(), fly(), and run() functions.

class Animal {

public void eat() {

System.out.println("Animal is eating.");

class Bird extends Animal {

@Override

public void eat() {

System.out.println("Bird is eating worms.");

public void fly() {

System.out.println("Bird is flying.");

class Mammal extends Animal {

@Override

public void eat() {

System.out.println("Mammal is eating grass.");

public void run() {

System.out.println("Mammal is running.");

Write a program to implement hybrid inheritance for managing employee information.

The program should have a base class Employee which has a name and an id attribute. The Employee class should also have a display
method that will display the name and id of an employee.

The program should also have two derived classes: Manager and Engineer. The Manager class should have a salary attribute, and the
Engineer class should also have a salary attribute. Both derived classes should have a display method that will display the name, ID, and
salary of the employee.
class Employee {

protected String name;

protected int id;

public Employee(String name, int id) {

this.name = name;

this.id = id;

public void display() {

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

System.out.println("ID: " + id);

class Manager extends Employee {

private int salary;

public Manager(String name, int id, int salary) {

super(name, id);

this.salary = salary;

@Override

public void display() {

System.out.println("Employee Type: Manager");

super.display();

System.out.println("Salary: " + salary);

class Engineer extends Employee {

private int salary;

public Engineer(String name, int id, int salary) {

super(name, id);

this.salary = salary;

@Override
public void display() {

System.out.println("Employee Type: Engineer");

super.display();

System.out.println("Salary: " + salary);

You are required to design a system to manage customer information and calculate discounts based on their bill amounts. The system
should handle two types of customers: BasicCustomer and premiumCustomer. Each customer has attributes such as name, city, age,
gender, and bill amount. Premium Customers have an additional attribute for the subscription fee.

Requirements for BasicCustomer Class

Attributes:

1. name (String)

2. city (String)

3. age (int)

4. gender (String)

5. billamount (int)

import java.util.Scanner;

class BasicCustomer {

private String name;

private String city;

private int age;

private String gender;

private int billamount;

public BasicCustomer() {

public BasicCustomer(String name, String city, int age, String gender, int billamount) {

this.name = name;

this.city = city;

this.age = age;

this.gender = gender;

this.billamount = billamount;

public void setName(String name) {


this.name = name;

public void setCity(String city) {

this.city = city;

public void setAge(int age) {

this.age = age;

public void setGender(String gender) {

this.gender = gender;

public void setBillamount(int billamount) {

this.billamount = billamount;

public String getName() {

return name;

public String getCity() {

return city;

public int getAge() {

return age;

public String getGender() {

return gender;

public int getBillamount() {

return billamount;

public void calculateDiscount() {

int discount = 0;

int amount = billamount;

if (amount >= 1 && amount <= 4999) discount = 100;

else if (amount <= 7499) discount = 250;

else if (amount <= 9999) discount = 500;

else if (amount <= 19999) discount = 750;

else if (amount <= 29999) discount = 1000;


else discount = 1500;

System.out.println("Discount: " + discount);

class PremiumCustomer extends BasicCustomer {

private int subamt;

public PremiumCustomer() {

public PremiumCustomer(String name, String city, int age, String gender, int billamount, int subamt) {

super(name, city, age, gender, billamount);

this.subamt = subamt;

public void setSubamt(int subamt) {

this.subamt = subamt;

public int getSubamt() {

return subamt;

@Override

public void calculateDiscount() {

int discount = 0;

int amount = getBillamount();

if (amount >= 1 && amount <= 4999) discount = 200;

else if (amount <= 7499) discount = 400;

else if (amount <= 9999) discount = 700;

else if (amount <= 19999) discount = 1000;

else if (amount <= 29999) discount = 1500;

else discount = 2000;

System.out.println("Subscription fee/month: " + subamt);

System.out.println("Discount: " + discount);

class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


String name = sc.nextLine();

String city = sc.nextLine();

int age = sc.nextInt();

sc.nextLine(); // consume newline

String gender = sc.nextLine();

int billamount = sc.nextInt();

int choice = sc.nextInt();

if (choice == 0) {

BasicCustomer bc = new BasicCustomer();

bc.setName(name);

bc.setCity(city);

bc.setAge(age);

bc.setGender(gender);

bc.setBillamount(billamount);

System.out.println("Name: " + bc.getName());

System.out.println("City: " + bc.getCity());

System.out.println("Age: " + bc.getAge());

System.out.println("Gender: " + bc.getGender());

System.out.println("Total Bill Amount: " + bc.getBillamount());

bc.calculateDiscount();

} else if (choice == 1) {

int subamt = sc.nextInt();

PremiumCustomer pc = new PremiumCustomer();

pc.setName(name);

pc.setCity(city);

pc.setAge(age);

pc.setGender(gender);

pc.setBillamount(billamount);

pc.setSubamt(subamt);

System.out.println("Name: " + pc.getName());

System.out.println("City: " + pc.getCity());

System.out.println("Age: " + pc.getAge());

System.out.println("Gender: " + pc.getGender());

System.out.println("Total Bill Amount: " + pc.getBillamount());

pc.calculateDiscount();

sc.close();
}

Write a Java program to create a class Shape representing geometric shapes. Implement the following functionalities:

• Create a constructor to initialize the shape type.

• Create a derived class Rectangle from Shape representing rectangles. Implement a constructor to initialize the length and width
of the rectangle.

• Create a derived class Circle from Shape representing circles. Implement a constructor to initialize the radius of the circle.

Formula: Area of the circle: Math.PI * radius * radius

import java.util.Scanner;

class Shape {

protected String shapeType;

public Shape(String shapeType) {

this.shapeType = shapeType;

class Rectangle extends Shape {

private double length;

private double width;

public Rectangle(double length, double width) {

super("Rectangle");

this.length = length;

this.width = width;

System.out.println("Creating a rectangle with length " + (int)length + " and width " + (int)width + ".");

public double calculateArea() {

return length * width;

class Circle extends Shape {

private double radius;

public Circle(double radius) {

super("Circle");
this.radius = radius;

System.out.println("Creating a circle with radius " + (int)radius + ".");

public double calculateArea() {

return Math.PI * radius * radius;

class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

double length = sc.nextDouble();

double width = sc.nextDouble();

double radius = sc.nextDouble();

Rectangle rectangle = new Rectangle(length, width);

Circle circle = new Circle(radius);

System.out.printf("Area of rectangle: %.2f\n", rectangle.calculateArea());

System.out.printf("Area of circle: %.2f\n", circle.calculateArea());

sc.close();

Overriding is another concept that every application developer should know. Overriding is a runtime polymorphism. The inherited class has
the overridden method, which has the same name as the method in the parent class. The argument number, types, or return types should
not differ in any case. The method is invoked with the object of the specific class (but with the reference of the parent class).

Now let's try out a simple overriding concept in our application. For this, we can take our original example of "class event" and its child
classes "exhibition" and "stage event."

Create a parent class Event with the following protected attributes

import java.util.Scanner;

class Event {

protected String name;

protected String detail;

protected String ownerName;

public Event(String name, String detail, String ownerName) {

this.name = name;

this.detail = detail;
this.ownerName = ownerName;

public String getName() {

return name;

public String getDetail() {

return detail;

public String getOwnerName() {

return ownerName;

public double projectedRevenue() {

return 0.0;

class Exhibition extends Event {

private int noOfStalls;

public Exhibition(String name, String detail, String ownerName, int noOfStalls) {

super(name, detail, ownerName);

this.noOfStalls = noOfStalls;

public int getNoOfStalls() {

return noOfStalls;

@Override

public double projectedRevenue() {

return noOfStalls * 10000.0;

class StageEvent extends Event {

private int noOfShows;

private int noOfSeatsPerShow;

public StageEvent(String name, String detail, String ownerName, int noOfShows, int noOfSeatsPerShow) {

super(name, detail, ownerName);

this.noOfShows = noOfShows;

this.noOfSeatsPerShow = noOfSeatsPerShow;

}
public int getNoOfShows() {

return noOfShows;

public int getNoOfSeatsPerShow() {

return noOfSeatsPerShow;

@Override

public double projectedRevenue() {

return noOfShows * noOfSeatsPerShow * 50.0;

class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String name = sc.nextLine();

String detail = sc.nextLine();

String ownerName = sc.nextLine();

int choice = sc.nextInt();

Event event;

if (choice == 1) {

int noOfStalls = sc.nextInt();

event = new Exhibition(name, detail, ownerName, noOfStalls);

} else if (choice == 2) {

int noOfShows = sc.nextInt();

int noOfSeatsPerShow = sc.nextInt();

event = new StageEvent(name, detail, ownerName, noOfShows, noOfSeatsPerShow);

} else {

System.out.println("Invalid input");

sc.close();

return;

System.out.println(event.projectedRevenue());

sc.close();

Ajay, an airline manager, needs to manage and display the details of aircrafts in his fleet. He has a base class Aircraft and two subclasses:
PublicAircraft and PrivateAircraft. The subclasses extend the functionality of the base class by adding specific attributes for each type of
aircraft.

Help Ajay by implementing the system to input and display these details efficiently.

import java.util.Scanner;

class Aircraft {

protected String aircraftName;

protected String source;

protected String destination;

public Aircraft(String aircraftName, String source, String destination) {

this.aircraftName = aircraftName;

this.source = source;

this.destination = destination;

public void displayBasicDetails() {

System.out.println("Aircraft Name : " + aircraftName);

System.out.println("Source : " + source);

System.out.println("Destination : " + destination);

class PublicAircraft extends Aircraft {

private int noOfKgsAllowed;

private float additionalFeePerKg;

public PublicAircraft(String aircraftName, String source, String destination, int noOfKgsAllowed, float additionalFeePerKg) {

super(aircraftName, source, destination);

this.noOfKgsAllowed = noOfKgsAllowed;

this.additionalFeePerKg = additionalFeePerKg;

public void displayDetails() {

System.out.println("Aircraft Type : Public Aircraft");

displayBasicDetails();

System.out.println("Check in before two hours : Yes");

System.out.println("Number of kgs allowed per person : " + noOfKgsAllowed);

System.out.println("Additional fee charged for extra baggage per Kg : " + additionalFeePerKg);

}
}

class PrivateAircraft extends Aircraft {

private String pilotPreference;

private String purpose;

public PrivateAircraft(String aircraftName, String source, String destination, String pilotPreference, String purpose) {

super(aircraftName, source, destination);

this.pilotPreference = pilotPreference;

this.purpose = purpose;

public void displayDetails() {

System.out.println("Aircraft Type : Private Aircraft");

displayBasicDetails();

System.out.println("Check in before two hours : No");

System.out.println("Pilot Name : " + pilotPreference);

System.out.println("Purpose :" + purpose);

class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String aircraftName = sc.nextLine();

String source = sc.nextLine();

String destination = sc.nextLine();

int flightType = sc.nextInt();

sc.nextLine();

if (flightType == 1) {

int noOfKgsAllowed = sc.nextInt();

float additionalFeePerKg = sc.nextFloat();

PublicAircraft pubAircraft = new PublicAircraft(aircraftName, source, destination, noOfKgsAllowed, additionalFeePerKg);

pubAircraft.displayDetails();

} else if (flightType == 2) {

String pilotPreference = sc.nextLine();

String purpose = sc.nextLine();

PrivateAircraft priAircraft = new PrivateAircraft(aircraftName, source, destination, pilotPreference, purpose);

priAircraft.displayDetails();

}
sc.close();

A company maintains a database that has the details of all the employees. There are two levels of employees where level 1 is the top
management having a salary of more than 100 dollars and level 2 is the staff who are getting a salary of fewer than 100 dollars. Create a
class named Employee with empId and salary as attributes. Create another class empLevel that extends employee and categorizes the
employee into various levels.

import java.util.Scanner;

class Employee {

protected int empId;

protected float salary;

public Employee(int empId, float salary) {

this.empId = empId;

this.salary = salary;

public void display() {

System.out.println(empId);

System.out.println(salary);

class EmpLevel extends Employee {

public EmpLevel(int empId, float salary) {

super(empId, salary);

public void display() {

super.display();

if (salary > 100) {

System.out.println(1);

} else {

System.out.println(2);

}
class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int empId = sc.nextInt();

float salary = sc.nextFloat();

EmpLevel employee = new EmpLevel(empId, salary);

employee.display();

sc.close();

Lab-9

Arun wants to calculate the age gap between the grandfather and the son and determine the father's age after 5 years.

Your task is to assist him in developing a program using three classes: GrandFather, Father, and Son, where GrandFather stores the
grandfather's age, Father extends GrandFather to include the father's age and calculates his age after 5 years, and Son extends Father to
include the son's age and calculate the age difference between the grandfather and the son.

class GrandFather {

private int grandfatherAge;

public void setGrandfatherAge(int age) {

this.grandfatherAge = age;

public int getGrandfatherAge() {

return grandfatherAge;

class Father extends GrandFather {

private int fatherAge;

public void setFatherAge(int age) {

this.fatherAge = age;

public int getFatherAge() {

return fatherAge;
}

public int calculateFatherAgeAfter5Years() {

return fatherAge + 5;

class Son extends Father {

private int sonAge;

public void setSonAge(int age) {

this.sonAge = age;

public int getSonAge() {

return sonAge;

public int calculateGrandfatherSonAgeDifference() {

return getGrandfatherAge() - sonAge;

Sharon, a software developer, is working on a library system program.

She has created a class hierarchy for different types of books:

1. class Book (with title and author attributes),

2. class Fiction (which extends the Book class and includes an attribute called "genre" for which string "Fantasy" is passed as a
default value through the constructor),

3. class Fantasy (which extends the Fiction class and includes an attribute called daysLate).

Now, she needs to calculate the late fees for borrowed fantasy books. The late fee is determined by multiplying the number of days a book
is late by 0.50.

Write a program that takes input for a borrowed fantasy book's title, author, and days late. The program should then calculate and display
the late fee.

Input format :

class Book {
protected String title;

protected String author;

public Book(String title, String author) {

this.title = title;

this.author = author;

class Fiction extends Book {

protected String genre;

public Fiction(String title, String author, String genre) {

super(title, author);

this.genre = genre;

class Fantasy extends Fiction {

private int daysLate;

public Fantasy(String title, String author, String genre, int daysLate) {

super(title, author, genre);

this.daysLate = daysLate;

public double calculateLateFee() {

return daysLate * 0.5;

A painter needs to determine the cost to paint different shapes based on their surface area.

Write a program that calculates the area of a sphere and the cost to paint it using three classes: Shape, Area, and Cost. The Shape class
should set the shape type and radius, the Area class should extend Shape to calculate the area, and the Cost class should extend Area to
calculate the total painting cost.

import java.util.Scanner;
class Shape {

protected String shapeType;

protected double radius;

public Shape(String shapeType, double radius) {

this.shapeType = shapeType;

this.radius = radius;

class Area extends Shape {

protected double area;

public Area(String shapeType, double radius) {

super(shapeType, radius);

public double calculateArea() {

area = 4 * 3.14 * radius * radius;

return area;

class Cost extends Area {

private double costPerSquareMeter;

public Cost(String shapeType, double radius, double costPerSquareMeter) {

super(shapeType, radius);

this.costPerSquareMeter = costPerSquareMeter;

public double calculatePaintingCost() {

return calculateArea() * costPerSquareMeter;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String shapeType = scanner.nextLine();

double radius = scanner.nextDouble();

double costPerSquareMeter = scanner.nextDouble();

if (shapeType.equals("Sphere")) {
Cost cost = new Cost(shapeType, radius, costPerSquareMeter);

double area = cost.calculateArea();

double totalCost = cost.calculatePaintingCost();

System.out.printf("Area of Sphere is: %.2f%n", area);

System.out.printf("Cost to paint the shape is: %.2f%n", totalCost);

} else {

System.out.println("Invalid type");

In an organization, employees have different roles and salaries. The task is to calculate the net salary of employees based on their role,
considering tax deductions and additional benefits.

Implement the following class hierarchy:

import java.util.Scanner;

class Employee {

protected String name;

protected double baseSalary;

public Employee(String name, double baseSalary) {

this.name = name;

this.baseSalary = baseSalary;

public double calculateNetSalary() {

return baseSalary;

class Engineer extends Employee {

protected double bonus;

public Engineer(String name, double baseSalary, double bonus) {

super(name, baseSalary);

this.bonus = bonus;

}
@Override

public double calculateNetSalary() {

double gross = baseSalary + bonus;

double tax = gross * 0.10;

double benefit = 100.0;

return gross - tax + benefit;

class SoftwareEngineer extends Engineer {

public SoftwareEngineer(String name, double baseSalary, double bonus) {

super(name, baseSalary, bonus);

@Override

public double calculateNetSalary() {

double gross = baseSalary + bonus;

double tax = gross * 0.15;

double benefit = 150.0;

return gross - tax + benefit;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String name = scanner.nextLine();

double baseSalary = scanner.nextDouble();

double bonus = scanner.nextDouble();

int type = scanner.nextInt();

if (type == 1) {

Engineer eng = new Engineer(name, baseSalary, bonus);

System.out.println(eng.calculateNetSalary());

} else if (type == 2) {

SoftwareEngineer se = new SoftwareEngineer(name, baseSalary, bonus);

System.out.println(se.calculateNetSalary());
} else {

System.out.println("Invalid");

Dinesh, a dedicated fitness enthusiast, decides to track his daily running sessions using a fitness app. He uses the app to record his running
duration and speed. Write a program that takes his running duration and speed as input and calculates the calories burned during the run.

Refer to the below class diagram:

import java.util.Scanner;

class FitnessTracker {

private double duration;

private double speed;

private final double MET = 7.0;

public FitnessTracker(double duration, double speed) {

this.duration = duration;

this.speed = speed;

public double calculateCaloriesBurned() {

return MET * (duration / 60.0) * 3.5 * (speed / 3.0);

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

double duration = scanner.nextDouble();

double speed = scanner.nextDouble();

FitnessTracker tracker = new FitnessTracker(duration, speed);

double calories = tracker.calculateCaloriesBurned();

System.out.printf("%.2f", calories);

Maria, a software developer, is building a grading automation system for Computer Science students. The program calculates the Grade
Point Average (GPA) and determines class standing based on credits completed.
The GPA is calculated using the formula:

GPA = 4.0 × ( creditsCompleted / 120.0 )

where 120 credits are required for graduation, with a maximum possible GPA of 4.0. The class standing is determined as follows:
Freshman (0-29 credits), Sophomore (30-59), Junior (60-89), and Senior (90 or more).

import java.util.Scanner;

class Student {

protected String name;

protected int age;

public Student(String name, int age) {

this.name = name;

this.age = age;

public void displayInfo() {

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

System.out.println("Age: " + age);

class Undergraduate extends Student {

protected double creditsCompleted;

public Undergraduate(String name, int age, double creditsCompleted) {

super(name, age);

this.creditsCompleted = creditsCompleted;

public double calculateGPA() {

double gpa = 4.0 * (creditsCompleted / 120.0);

return Math.min(gpa, 4.0);

public String getClassStanding() {

if (creditsCompleted >= 0 && creditsCompleted <= 29) {

return "Freshman";

} else if (creditsCompleted <= 59) {

return "Sophomore";

} else if (creditsCompleted <= 89) {


return "Junior";

} else {

return "Senior";

class ComputerScienceMajor extends Undergraduate {

public ComputerScienceMajor(String name, int age, double creditsCompleted) {

super(name, age, creditsCompleted);

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String name = scanner.nextLine();

int age = scanner.nextInt();

double creditsCompleted = scanner.nextDouble();

ComputerScienceMajor csStudent = new ComputerScienceMajor(name, age, creditsCompleted);

csStudent.displayInfo();

System.out.printf("Credits Completed: %.1f%n", csStudent.creditsCompleted);

System.out.printf("GPA: %.1f%n", csStudent.calculateGPA());

System.out.println("Class Standing: " + csStudent.getClassStanding());

A new airline, Boeing747, needs to calculate its total revenue based on ticket cost and seat availability.

Implement a program using three classes: Airline, Indigo, and Boeing747, where Airline has a cost attribute, Indigo extends Airline with
seatAvailability, and Boeing747 extends Indigo with a method calculateTotalRevenue to calculate the total revenue.

Note: Total revenue = ticket cost * seat availability

import java.util.Scanner;

class Airline {

protected double cost;

public Airline(double cost) {


this.cost = cost;

public double getCost() {

return cost;

class Indigo extends Airline {

protected int seatAvailability;

public Indigo(double cost, int seatAvailability) {

super(cost);

this.seatAvailability = seatAvailability;

public int getSeatAvailability() {

return seatAvailability;

class Boeing747 extends Indigo {

public Boeing747(double cost, int seatAvailability) {

super(cost, seatAvailability);

public double calculateTotalRevenue() {

return cost * seatAvailability;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

double ticketCost = scanner.nextDouble();

int seats = scanner.nextInt();

Boeing747 flight = new Boeing747(ticketCost, seats);

System.out.printf("Ticket Cost: Rs. %.1f\n", flight.getCost());

System.out.printf("Seat Availability: %d seats\n", flight.getSeatAvailability());

System.out.printf("Total Revenue: Rs. %.1f\n", flight.calculateTotalRevenue());

}
Lab-10

Jaheer is working on a health monitoring system to help individuals calculate their Body Mass Index (BMI). He has implemented a basic
BMI calculator and an interface called HealthCalculator. It should have a method called calculateBMI.

You are tasked with creating a program that takes weight and height as input, calculates the BMI using the BMICalculator class, and
displays the result. If the height or weight is less than or equal to zero, then return -1.

interface HealthCalculator {

double calculateBMI(double weight, double height);

class BMICalculator implements HealthCalculator {

@Override

public double calculateBMI(double weight, double height) {

if (weight <= 0 || height <= 0) {

return -1;

return weight / (height * height);

Raj is curious about how old he is in the current year.

He has asked you to create a simple program that calculates a person's age based on their birth year. You decide to implement this
functionality using the AgeCalculator interface and the HumanAgeCalculator class.

interface AgeCalculator {

int calculateAge(int birthYear);

class HumanAgeCalculator implements AgeCalculator {

private static final int CURRENT_YEAR = 2024;

public int calculateAge(int birthYear) {

return CURRENT_YEAR - birthYear;

Jeevan is developing a fitness-tracking application to monitor daily physical activity.


The application incorporates a FitnessTracker class that implements two interfaces: StepCounter for tracking the number of steps taken
and CalorieCalculator for estimating total calories burned based on total steps.

Jeevan needs your help creating a program.

Note

The calorie calculation formula is: Total caloriesBurned = (total steps / 100.0) * 20.0.

Input format :

import java.util.Scanner;

interface StepCounter {

int calculateTotalSteps(int[] steps);

interface CalorieCalculator {

double calculateCaloriesBurned(int totalSteps);

class FitnessTracker implements StepCounter, CalorieCalculator {

@Override

public int calculateTotalSteps(int[] steps) {

int totalSteps = 0;

for (int step : steps) {

totalSteps += step;

return totalSteps;

@Override

public double calculateCaloriesBurned(int totalSteps) {

return (totalSteps / 100.0) * 20.0;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();

int[] steps = new int[n];

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

steps[i] = scanner.nextInt();
}

FitnessTracker fitnessTracker = new FitnessTracker();

int totalSteps = fitnessTracker.calculateTotalSteps(steps);

double caloriesBurned = fitnessTracker.calculateCaloriesBurned(totalSteps);

System.out.println("Total Steps: " + totalSteps);

System.out.printf("Calories Burned: %.2f\n", caloriesBurned);

scanner.close();

Sam is developing a geometry application and needs a class for trapezoid calculations. Create a "Trapezoid" class implementing a
"ShapeInput" interface with a method to input trapezoid dimensions.

Also, implement a "ShapeCalculator" interface with methods to compute area and perimeter. In the "Main" class, instantiate Trapezoid,
gather user input, and display the calculated area and perimeter with two decimal places.

Note

Area of Trapezoid = (1/2) * (base1 + base2) * height

Perimeter of Trapezoid = base1 + base2 + side1 + side2

import java.util.Scanner;

interface ShapeInput {

void inputDimensions();

interface ShapeCalculator {

double calculateArea();

double calculatePerimeter();

class Trapezoid implements ShapeInput, ShapeCalculator {

private double base1, base2, height, side1, side2;

@Override

public void inputDimensions() {

Scanner scanner = new Scanner(System.in);

base1 = scanner.nextDouble();

base2 = scanner.nextDouble();

height = scanner.nextDouble();
side1 = scanner.nextDouble();

side2 = scanner.nextDouble();

@Override

public double calculateArea() {

return 0.5 * (base1 + base2) * height;

@Override

public double calculatePerimeter() {

return base1 + base2 + side1 + side2;

class Main {

public static void main(String[] args) {

Trapezoid trapezoid = new Trapezoid();

trapezoid.inputDimensions();

double area = trapezoid.calculateArea();

double perimeter = trapezoid.calculatePerimeter();

System.out.printf("Area of the Trapezoid: %.2f\n", area);

System.out.printf("Perimeter of the Trapezoid: %.2f\n", perimeter);

A developer aims to create a budget management system using two interfaces, ExpenseRecorder for recording expenses and
BudgetCalculator for calculating remaining budgets.

The ExpenseTracker class implements these interfaces, allowing users to input an initial budget and record expenses iteratively until
entering 0.0 as a sentinel value.

The program then computes and displays the remaining budget or notifies of budget exceed

import java.util.Scanner;

interface ExpenseRecorder {

void recordExpense(double expense);

interface BudgetCalculator {
double calculateRemainingBudget();

class ExpenseTracker implements ExpenseRecorder, BudgetCalculator {

private double initialBudget;

private double totalExpenses;

public ExpenseTracker(double initialBudget) {

this.initialBudget = initialBudget;

this.totalExpenses = 0.0;

@Override

public void recordExpense(double expense) {

if (expense > 0.0) {

totalExpenses += expense;

@Override

public double calculateRemainingBudget() {

return initialBudget - totalExpenses;

public boolean isBudgetExceeded() {

return calculateRemainingBudget() < 0;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

double initialBudget = scanner.nextDouble();

ExpenseTracker tracker = new ExpenseTracker(initialBudget);

double expense;

while ((expense = scanner.nextDouble()) != 0.0) {

tracker.recordExpense(expense);

if (tracker.isBudgetExceeded()) {

System.out.println("No remaining budget, You've exceeded your budget!");

} else {

System.out.printf("Remaining budget: Rs. %.2f\n", tracker.calculateRemainingBudget());

scanner.close();
}

Problem Statement

Oviya is fascinated by automorphic numbers and wants to create a program to determine whether a given number is an automorphic
number or not.

An automorphic number is a number whose square ends with the same digits as the number itself. For example, 25 = (25)2 = 625

Oviya has defined two interfaces, NumberInput for taking user input and AutomorphicChecker for checking if a given number is
automorphic. The class AutomorphicNumber implements both interfaces.

import java.util.Scanner;

interface NumberInput {

int getInput();

interface AutomorphicChecker {

boolean isAutomorphic(int n);

class AutomorphicNumber implements NumberInput, AutomorphicChecker {

@Override

public int getInput() {

Scanner scanner = new Scanner(System.in);

return scanner.nextInt();

@Override

public boolean isAutomorphic(int n) {

int square = n * n;

String strNumber = String.valueOf(n);

String strSquare = String.valueOf(square);

return strSquare.endsWith(strNumber);

public static void main(String[] args) {

AutomorphicNumber automorphicNumber = new AutomorphicNumber();

int n = automorphicNumber.getInput();
if (automorphicNumber.isAutomorphic(n)) {

System.out.println(n + " is an automorphic number");

} else {

System.out.println(n + " is not an automorphic number");

John is developing a car loan calculator and has structured his program using two interfaces, Principal and InterestRate, defining methods
for principal and interest rate retrieval.

The Loan class implements these interfaces, taking principal and annual interest rates as parameters. User input is solicited for these
values, and the program ensures their validity before performing calculations. If input values are invalid (less than or equal to zero), an
error message is displayed.

Note: Total interest = principal * interest rate * years

import java.util.Scanner;

interface Principal {

double getPrincipal();

interface InterestRate {

double getInterestRate();

class Loan implements Principal, InterestRate {

private double principal;

private double interestRate;

private int years;

public Loan(double principal, double interestRate, int years) {

this.principal = principal;

this.interestRate = interestRate;

this.years = years;

@Override

public double getPrincipal() {

return principal;

@Override
public double getInterestRate() {

return interestRate;

public double calculateTotalInterest() {

return principal * interestRate * years;

public boolean isValid() {

return principal > 0 && interestRate > 0 && interestRate <= 1 && years > 0;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

double principal = scanner.nextDouble();

double interestRate = scanner.nextDouble();

int years = scanner.nextInt();

Loan loan = new Loan(principal, interestRate, years);

if (loan.isValid()) {

double totalInterest = loan.calculateTotalInterest();

System.out.printf("Total interest paid: Rs.%.2f\n", totalInterest);

} else {

System.out.println("Invalid input values!");

scanner.close();

}
Problem Statement

Alex is fascinated by mountains and valleys. He defines a peak element as an element


that is strictly greater than its neighbours.

Given an array of integers, help Alex find a peak element and its index.
import java.util.Scanner;

class PeakElementFinder{

public static void main(String[]args){

Scanner sc=new Scanner(System.in);

int N=sc.nextInt();

int[] arr=new int[N];

for(int i=0;i<N;i++){

arr[i]=sc.nextInt();

sc.close();

int peakElement=-1;

int peakIndex =-1;

for(int i=0;i<N;i++){

if((i==0||arr[i]>arr[i-1])&&(i==N-1||arr[i]>arr[i+1])){

peakElement=arr[i];

peakIndex=i;

System.out.println("Peak Element: "+peakElement+"at index"+peakIndex);

Problem Statement
Mukhil is working on a program to analyze the frequency of characters in a string. He
wants to find the character with the highest frequency in the string. Write a Java
program to help Mukhil with his character frequency analysis.

The program should prompt Mukhil to enter a string. After receiving the input, the
program should count the frequency of each character in the string and then determine
and display the character with the highest frequency.
import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

class HighestFrequencyCharacter{

public static void main(String[] args){

Scanner scanner=new Scanner(System.in);

String input=scanner.nextLine();

scanner.close();

Map<Character,Integer>frequencyMap=new HashMap<>();

for(char ch : input.toCharArray()){

frequencyMap.put(ch,frequencyMap.getOrDefault(ch,0)+1);

char maxChar=input.charAt(0);

int maxFreq=0;

for(Map.Entry<Character,Integer>entry:frequencyMap.entrySet()){

if(entry.getValue()>maxFreq){

maxChar=entry.getKey();

maxFreq=entry.getValue();

System.out.println("Highest frequency character: "+maxChar);

Problem Statement
Mia is designing a solar panel performance calculator. Help Mia to create two classes,
SolarPanel and PerformanceCalculator. The SolarPanel class should have a
parameterized constructor that accepts panelArea (double in square meters) and
efficiency (double as a percentage).

The PerformanceCalculator class should have two methods:

 calculateEnergyGenerated(SolarPanel sp, double sunlightHours) to calculate the


energy generated.

 calculateYearlySavings(SolarPanel sp, double sunlightHours, double


electricityRate) to calculate yearly savings

Formula:

Efficiency rate= Efficiency percentage / 100.

Energy Generated=panelArea×efficiency rate×sunlightHours×1.036

Yearly Savings=Energy Generated×electricityRate×365


class SolarPanel{

double panelArea;

double efficiency;

public SolarPanel(double panelArea,double efficiency){

this.panelArea = panelArea;

this.efficiency = efficiency;

class PerformanceCalculator{

public double calculateEnergyGenerated(SolarPanel sp,double sunlightHours){

double efficiencyRate=sp.efficiency/100;

return sp.panelArea*efficiencyRate*sunlightHours*1.036;

public double calculateYearlySavings(SolarPanel sp,double sunlightHours,double electricityRate){

double dailyEnergy=calculateEnergyGenerated(sp,sunlightHours);
return dailyEnergy*electricityRate*365;

public class Main{

public static void main(String[]args){

Scanner scanner = new Scanner(System.in);

double panelArea=scanner.nextDouble();

double efficiency=scanner.nextDouble();

double sunlight=scanner.nextDouble();

double electricityRate=scanner.nextDouble();

scanner.close();

SolarPanel sp=new SolarPanel(panelArea,efficiency);

PerformanceCalculator pc = new PerformanceCalculator();

double dailyEnergy=pc.calculateEnergyGenerated(sp,sunlight);

double yearlySavings=pc.calculateYearlySavings(sp,sunlight,electricityRate);

System.out.printf("%.2f\n",dailyEnergy);

System.out.printf("%.2f\n",yearlySavings);

LAB 2
Problem Statement

Raj, an insurance agent, needs a program to streamline the calculation and updating of
insurance prices for two-wheelers and four-wheelers using hierarchical inheritance.
Implement three classes:

 Vehicle with a method setBasePrice(double basePrice).


 TwoWheeler (inherits from Vehicle) with methods
calculateFinalPriceTwoWheeler() to calculate the updated price for two-wheelers.

 FourWheeler (inherits from Vehicle) with methods


calculateFinalPriceFourWheeler() to calculate the updated price for four-
wheelers.

Raj inputs the base prices of the vehicles, and the program calculate and display the
original and updated prices, incorporating a 20% (0.20) increase for two-wheelers and a
30% (0.30) increase for four-wheelers.

Formula: Updated price = base price + (base price * increase);


class Vehicle{

protected double basePrice;

public void setBasePrice(double basePrice){

this.basePrice = basePrice;

public void showPrice(){

System.out.println("Original and Updated Price");

System.out.printf("Rs. %.2f\n",basePrice);

class TwoWheeler extends Vehicle{

public void calculateFinalPriceTwoWheeler(){

double finalPrice = basePrice +(basePrice*0.20);

System.out.printf("Rs. %.2f\n",finalPrice);

}
}

class FourWheeler extends Vehicle{

public void calculateFinalPriceFourWheeler(){

double finalPrice =basePrice +(basePrice*0.30);

System.out.printf("Rs. %.2f\n",finalPrice);

Problem Statement

Janani aims to create a versatile palindrome checker capable of handling both numeric
values and words.

The base class, PalindromeChecker, features a parameterized constructor that takes


an integer as input. It includes a method, isPalindrome(), which determines whether
the given integer is a palindrome. Include a method displayResult() to print the result of
the palindrome check for numbers.

The subclass, WordPalindromeChecker, is derived from the base class. This subclass
overrides the isPalindrome() method to accommodate word inputs, treating them case-
insensitively. The overridden displayResult() method ensures that the outcome of the
word palindrome check is appropriately printed.

Create instances of both classes in the main class and display the results.
class PalindromeChecker{

protected int number;

public PalindromeChecker(int number)

this.number=number;

public boolean isPalindrome(){

int original=number,reversed=0,remainder;

while(original>0){

remainder=original%10;
reversed=reversed*10+remainder;

original/=10;

return reversed==number;

public void displayResult(){

if (isPalindrome()){

System.out.println("The number is a palindrome.");

}else{

System.out.println("The word is not a palindrome.");

class WordPalindromeChecker extends PalindromeChecker{

private String word;

public WordPalindromeChecker(String word){

super(0);

this.word=word;

public boolean isPalindrome(){

String reversed=new StringBuilder(word).reverse().toString();

return word.equalsIgnoreCase(reversed);

public void dispalyResult(){

if (isPalindrome()){

System.out.print("The word is palindrome.");

}else{

System.out.println("The number is not a palindrome.");

}
}

Problem Statement

Wick is developing a real-time strategy game where the players command armies
represented by square matrices. The game requires matrix operations to calculate army
strength and overall battle outcomes.

Write a program to assist Wich that includes an abstract class MatrixOperation with an
abstract method performOperation(int[][] matrix1, int[][] matrix2), and a class
MatrixAddition. Calculate the army strength by adding all the elements in the given
matrices. Display the matrix that represents the army's strength.
abstract class MatrixOperation{

public abstract int[][] performOperation(int[][] matrix1,int[][] matrix2);

class MatrixAddition extends MatrixOperation{

public int[][] performOperation(int[][] matrix1,int[][] matrix2){

int n= matrix1.length ;

int[][] result =new int[n][n];

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

for(int j=0;j<n;j++){

result[i][j]=matrix1[i][j]+matrix2[i][j];

return result;

LAB 3
Problem Statement
Sophie, an investment enthusiast, wants to develop a program to calculate the Annual
Percentage Yield (APY) based on different interest rates and compounding frequencies.

Your task is to design and implement a program that includes an APYCalculator class,
which uses an anonymous inner class to implement the APYCalculatorInterface for APY
calculation.

The program should prompt Sophie to enter the interest rate and compounding
frequency, then compute the APY using the formula:
APY = (1 + Interest Rate / Compounding Frequency) CF-1

Finally, the program should display the APY rounded to two decimal places.
class APYCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the interest rate (as a decimal):");

double interestRate = scanner.nextDouble();

System.out.print("Enter the compounding frequency:");

int compoundingFrequency = scanner.nextInt();

APYCalculatorInterface calculator = new APYCalculatorInterface() {

public double calculateAPY(double interestRate, int compoundingFrequency) {

return Math.pow(1+(interestRate / compundingFrequency), compoundingFrequency)-1;

};

double apy = calculator.calculateAPY(interestRate, compoundingFrequency);

System.out.print("The Annual Percentage Yield (APY) is: %.4f%n",apy);

scanner.close();
}

interface APYCalculatorInterface {

double calculateAPY(double interestRate,int compundingfrequency);

Problem Statement:

Sam is developing a geometry application and needs a class for trapezoid calculations.
Create a "Trapezoid" class implementing a "ShapeInput" interface with a method to
input trapezoid dimensions.

Also, implement a "ShapeCalculator" interface with methods to compute area and


perimeter. In the "Main" class, instantiate Trapezoid, gather user input, and display the
calculated area and perimeter with two decimal places.

Note

Area of Trapezoid = (1/2) * (base1 + base2) * height

Perimeter of Trapezoid = base1 + base2 + side1 + side2


import java.util.Scanner;

interface ShapeInput{

void getInput();

interface ShapeCalculator{

double calculateArea();

double calculatePerimeter();

class Trapezoid implements ShapeInput,ShapeCalculator{

private double base1;

private double base2;

private double height;


private double side1;

private double side2;

@Override

public void getInput(){

Scanner scanner=new Scanner(System.in);

base1=scanner.nextDouble();

base2=scanner.nextDouble();

height=scanner.nextDouble();

side1=scanner.nextDouble();

side2=scanner.nextDouble();

scanner.close();

@Override

public double calculateArea(){

return 0.5*(base1+base2)*height;

public double calculatePerimeter(){

return base1+base2+side1+side2;

Problem Statement

Raj is curious about how old he is in the current year.

He has asked you to create a simple program that calculates a person's age based on
their birth year. You decide to implement this functionality using the AgeCalculator
interface and the HumanAgeCalculator class.

Note: The current year is 2024. Calculate the current age by using the formula: current
year - birth year.
import java.util.Scanner;

interface AgeCalculator {

int calculateAge(int birthYear);

class HumanAgeCalculator implements AgeCalculator{

private static final int CURRENT_YEAR=2024;

public int calculateAge(int birthYear){

return CURRENT_YEAR-birthYear;

}
LAB 4
Problem Statement

Raghav's program should allow the user to define an integer array size and input only
positive integers. If a non-positive integer is entered, an IllegalArgumentException with
the message "IllegalArgumentException: Only positive integers are allowed"
should be thrown. If more elements are input than the array size, an
ArrayIndexOutOfBoundsException with the message
"ArrayIndexOutOfBoundsException: Input elements exceed array size" should be
thrown . The program should print the array elements if no exception occurs and always
print "Program executed successfully!" in the finally block.
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

try {

int N = scanner.nextInt();

int[] arr = new int[N];

scanner.nextLine();

String numbers = scanner.nextLine();

String[] numStrings = numbers.split(" ");

if (numStrings.length > N) {

throw new ArrayIndexOutOfBoundsException();

for (int i = 0; i < N; i++) {

int num = Integer.parseInt(numStrings[i]);

if (num <= 0) {

throw new IllegalArgumentException();

}
arr[i] = num;

System.out.print("Array: ");

for (int num : arr) {

System.out.print(num + " ");

System.out.println();

} catch (IllegalArgumentException e) {

System.out.println("IllegalArgumentException: Only positive integers are allowed");

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("ArrayIndexOutOfBoundsException: Input elements exceeds array size");

} finally {

System.out.println("Program executed successfully!");

scanner.close();

Problem Statement

Jordan is developing a banking application that manages account withdrawals with


special considerations for premium accounts and bonus rewards. The application must
validate and handle various exceptions related to withdrawals:

 Bonus Amount Validation: If the bonus amount is negative, a


WithdrawalException must be thrown with the message: "Bonus amount cannot
be negative."

 Account Status for Bonus Rewards: If the user is a premium account holder
but has made fewer than 3 transactions this month, an AccountStatusException
must be thrown with the message: "User is not eligible for bonus rewards."
 Withdrawal Fee Calculation: If the withdrawal amount exceeds a threshold of
$50.00, a withdrawal fee is applied. The fee is 1% for premium accounts and 2%
for non-premium accounts.

The formulas used in the withdraw method are:

Withdrawal Fee Calculation:

 If the withdrawal amount w exceeds the threshold ($50.00), a fee is applied:

 If w ≤ 50, then withdrawalFee = 0.

Remaining Balance Calculation:

 remainingBalance = balance − amount − withdrawalFee

Bonus Amount Check:

 If bonusAmount < 0, a WithdrawalException is thrown.

Bonus Reward Eligibility:

 If the account is premium but has transactionsThisMonth < 3, an


AccountStatusException is thrown.

Final Balance Update:

 balance = balance − amount − withdrawalFee + bonusAmount

Transaction Count Update:

 transactionsThisMonth += 1

Help Jordan complete his task efficiently.


import java.util.Scanner;
class WithdrawalException extends Exception {

public WithdrawalException(String message) {

super(message);

class AccountStatusException extends Exception {

public AccountStatusException(String message) {

super(message);

class BankAccount {

private double balance;

private boolean isPremium;

private int transactionsThisMonth;

private final double withdrawalFeeThreshold = 50.0;

private final double monthlyWithdrawalLimitPercentage = 0.50;

private final double bonusAmount;

public BankAccount(double initialBalance, boolean isPremium, int transactionsThisMonth, double bonusAmount) {

this.balance = initialBalance;

this.isPremium = isPremium;

this.transactionsThisMonth = transactionsThisMonth;

this.bonusAmount = bonusAmount;

public double getBalance() {

return balance;

}
public void withdraw(double amount) throws WithdrawalException, AccountStatusException {

if (bonusAmount < 0) {

throw new WithdrawalException("Bonus amount cannot be negative.");

double withdrawalFee = amount > withdrawalFeeThreshold ? (isPremium ? 0.01 * amount : 0.02 * amount) : 0;

double remainingBalance = balance - amount - withdrawalFee;

if (transactionsThisMonth < 3 && isPremium) {

throw new AccountStatusException("User is not eligible for bonus rewards.");

balance -= amount + withdrawalFee;

balance += bonusAmount;

transactionsThisMonth++;

this.transactionsThisMonth = transactionsThisMonth;

this.bonusAmount = bonusAmount;

public double getBalance() {

return balance;

public void withdraw(double amount) throws WithdrawalException, AccountStatusException {

if (bonusAmount < 0) {

throw new WithdrawalException("Bonus amount cannot be negative.");

double withdrawalFee = amount > withdrawalFeeThreshold ? (isPremium ? 0.01 * amount : 0.02 * amount) : 0;

double remainingBalance = balance - amount - withdrawalFee;


if (transactionsThisMonth < 3 && isPremium) {

throw new AccountStatusException("User is not eligible for bonus rewards.");

balance -= amount + withdrawalFee;

balance += bonusAmount;

transactionsThisMonth++;

scanner.close();

Problem Statement

Thomson is developing a program to validate and compute the speed based on user-
provided distance and time. The program needs to ensure that the inputs for distance
and time are valid before calculating the speed.

Here’s how Thomson’s program works:

 Validate Distance: Distance must be between 0.0 and 10,000.0. If it’s out of this
range, the program throws an IllegalArgumentException with: "Distance is out
of range".

 Validate Time: Time must be positive. If it’s less than or equal to 0.0, the
program throws an IllegalArgumentException with: "Time must be positive".

 Calculate Speed: Speed is calculated as distance/time. If the computed speed is


less than or equal to 0.0, the program throws an IllegalArgumentException with:
"Calculated speed must be greater than zero".

 Handle Input Errors: If the input format is incorrect or the values cannot be
parsed to floats, the program catches a NumberFormatException and displays:
"Invalid number format: For input string: 'input'"."
import java.util.Scanner;

class DistanceTimeValidator {
public static void validateDistance(float distance) throws IllegalArgumentException {

if (distance < 0.0 || distance > 10000.0) {

throw new IllegalArgumentException("Distance is out of range");

public static void validateTime(float time) throws IllegalArgumentException {

if (time <= 0.0) {

throw new IllegalArgumentException("Time must be positive");

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

try {

int n = Integer.parseInt(scanner.nextLine());

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

String[] input = scanner.nextLine().split(" ");

if (input.length != 2) {

throw new IllegalArgumentException("Input must contain exactly two values");

float distance = Float.parseFloat(input[0]);

float time = Float.parseFloat(input[1]);

validateDistance(distance);

validateTime(time);
// Calculate speed

float speed = distance / time;

if (speed <= 0.0) {

throw new IllegalArgumentException("Calculated speed must be greater than zero");

System.out.printf("%.2f\n", speed);

} catch (NumberFormatException e) {

System.out.println("Invalid number format: " + e.getMessage());

} catch (IllegalArgumentException e) {

System.out.println(e.getMessage());

} finally {

scanner.close();

LAB 5
Problem Statement

John is organizing a fruit festival, and the quantities of various fruits are stored in a
HashMap where fruit names are keys and quantities are values.

Help him develop a program to find the total quantity of fruits for the festival by summing
up the values in the HashMap.

class ValueProcessor {
public static Map<String, Double> readValues(Scanner scanner) {

Map<String, Double> valueMap = new HashMap<>();


while (true) {
String input = scanner.nextLine();

if (input.toLowerCase().equals("done")) {

break;

}
String[] pair = input.split(":");

if (pair.length == 2) {

String key = pair[0].trim();

try {

double value = Double.parseDouble(pair[1].trim());

valueMap.put(key, value);

} catch (NumberFormatException e) {

System.out.println("Invalid input");
return null;

} else {

System.out.println("Invalid format");

return null;

}
return valueMap;

public static double calculateSum(Map<String, Double> valueMap) {

double sum = 0;

for (double value : valueMap.values()) {

sum += value;
}
return sum;

Problem Statement

A city traffic management system needs to track vehicles entering a toll booth. Each
vehicle is uniquely identified by its registration number. The system should allow adding
vehicles to a record, ensuring that no duplicate registration numbers exist. The vehicles
should be stored in HashSet, which does not guarantee any specific order.

Your task is to implement a program using HashSet that allows adding vehicle details
and displaying the records.
class Vehicle {

String regNumber;

String ownerName;

String vehicleType;

private static HashSet<Vehicle> vehicleSet = new HashSet<>();

public Vehicle(String regNumber, String ownerName, String vehicleType) {

this.regNumber = regNumber;

this.ownerName = ownerName;

this.vehicleType = vehicleType;

public static void addVehicle(String regNumber, String ownerName, String vehicleType) {

vehicleSet.add(new Vehicle(regNumber, ownerName, vehicleType));

public static void displayVehicles() {

for (Vehicle v : vehicleSet) {

System.out.println(v);

public boolean equals(Object obj) {

if (this == obj) return true;


if (obj == null || getClass() != obj.getClass()) return false;

Vehicle vehicle = (Vehicle) obj;

return regNumber.equals(vehicle.regNumber);

public int hashCode() {

return Objects.hash(regNumber);

public String toString() {

return regNumber + " " + ownerName + " " + vehicleType;

Problem Statement

During a festive gathering, participants have placed their gifts in a circle, each labeled
with a unique ID. To add excitement, Alex wants to rearrange the gifts by swapping two
presents positioned at indices a and b to create a thrilling surprise.

Write a program to perform this gift exchange using the generics concept.

public class Main {

public static <T> void swap(T[] array, int firstIndex, int secondIndex) {

if (firstIndex < 0 || firstIndex >= array.length || secondIndex < 0 || secondIndex >=


array.length) {

System.out.println("Invalid indices. Swap operation aborted.");


return;

T temp = array[firstIndex];

array[firstIndex] = array[secondIndex];
array[secondIndex] = temp;
}

LAB 6
Problem Statement

Alex needs to calculate the absolute differences between consecutive integers in a list
for his data analysis project. He requires a program that uses a separate thread to
compute these differences efficiently.

Help Alex by writing a program that reads a list of integers, computes the absolute
differences between consecutive numbers using multithreading, and prints the results.
import java.util.Scanner;

class DifferenceThread extends Thread {

private int[] numbers;

public DifferenceThread(int[] numbers) {

this.numbers = numbers;

@Override

public void run() {

for (int i = 0; i < numbers.length - 1; i++) {

int diff = Math.abs(numbers[i] - numbers[i + 1]);

System.out.print(diff + " ");

System.out.println();

Problem Statement
Alice is analyzing a sorted list of exam scores and wants to determine how many scores
are greater than the median. She decides to use multithreading to improve performance
and synchronize the counting process.

Help Alice implement a program that calculates the count of scores above the median
and their average.
import java.util.Scanner;

class CountGreaterThanMedianThread extends Thread {

private static int count = 0;

private static double average = 0.0;

private int[] numbers;

public CountGreaterThanMedianThread(int[] numbers) {

this.numbers = numbers;

@Override

public void run() {

int n = numbers.length;

int median = numbers[n / 2];

int sum = 0;

int cnt = 0;

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

if (numbers[i] > median) {

cnt++;

sum += numbers[i];

synchronized (CountGreaterThanMedianThread.class) {
count = cnt;

if (cnt > 0) {

average = (double) sum / cnt;

public static void printResults() {

System.out.println(count);

System.out.printf("%.2f\n", average);

Problem Statement

Sneha is managing a system that processes multiple tasks concurrently. She has
designed a multi-threaded program to process these tasks using an ExecutorService.
However, she needs the program to ensure that tasks always start and finish in the
correct order based on their task IDs, regardless of which thread handles them.

She needs your help to implement a solution using ExecutorService and


CountDownLatch to ensure the tasks are processed in the correct order. Each task will
be processed in a fixed time, and the program should maintain the order in which tasks
start and complete.
class Task implements Runnable {

private final int taskId;

private final CountDownLatch prevLatch;

private final CountDownLatch currLatch;

public Task(int taskId, CountDownLatch prevLatch, CountDownLatch currLatch) {

this.taskId = taskId;

this.prevLatch = prevLatch;

this.currLatch = currLatch;

}
@Override

public void run() {

try {

if (prevLatch != null) {

prevLatch.await();

System.out.println("Task " + taskId + " started.");

Thread.sleep(100); // Simulating task processing

System.out.println("Task " + taskId + " completed.");

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

} finally {

currLatch.countDown();

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy