Ilovepdf - Merged (1) - Merged
Ilovepdf - Merged (1) - Merged
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"
double height=scanner.nextDouble();
double weight=scanner.nextDouble();
double bmi=(weight/(height*height));
String category;
if (bmi<18.5){
category="underweight";
category="normal weight";
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.
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
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;
int n=sc.nextInt();
int originalN=n;
while(n>=10){
int sum=0;
while(n>0){
sum+=n%10;
n/=10;
n=sum;
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.
The program should output the total bill after applying the discount with two decimal
places.
import java.util.Scanner;
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;
discount=0.05;
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.
import java.util.Scanner;
import java.util.Set;
class Main {
int n = scanner.nextInt();
arr[i] = scanner.nextInt();
firstRepeated = arr[i];
seen.add(arr[i]);
if(firstRepeated != -1){
System.out.println(firstRepeated);
} else {
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 {
int M = scanner.nextInt();
for(int i = 0;i<N;i++)
matrix1[i][j] = scanner.nextInt();
for(int i = 0;i<N;i++)
matrix2[i][j] = scanner.nextInt();
for(int i = 0;i<N;i++)
for(int i = 0;i<N;i++){
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 {
int N =sc.nextInt();
sc.nextLine();
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;
mainDiagonalSum += matrix[i][i];
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){
int N =sc.nextInt();
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.
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.
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;
int vowelCount = 0;
if (vowels.indexOf(input.charAt(i)) != -1) {
vowelCount++;
if (vowelCount > 0) {
} else {
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.
import java.util.Scanner;
import java.util.HashSet;
String s = scanner.nextLine();
int maxLength = 0;
int left = 0;
while (set.contains(s.charAt(right))) {
set.remove(s.charAt(left));
left++;
}
set.add(s.charAt(right));
// Print result
System.out.println(maxLength);
scanner.close();
}
Problem Statement
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"};
num -= values[i];
roman.append(symbols[i]);
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.*;
String s = scanner.nextLine();
}
}
@Override
if (a.charAt(0) != b.charAt(0)) {
});
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;
String s = scanner.nextLine();
if (seen.contains(ch)) {
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 a single parameter: Initializes both num1 and num2 with the
same value provided as the parameter.
import java.util.Scanner;
class PrimeDecider {
public PrimeDecider() {
this.num1 = 0;
this.num2 = 0;
this.num2 = num;
this.num1 = num1;
this.num2 = num2;
}
if (n <= 1) {
return false;
if (n == 2) {
return true;
if (n % 2 == 0) {
return false;
if (n % i == 0) {
return false;
return true;
}
}
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
Output: Determine if the provided number is a prime number or part of the Fibonacci
series.
Range Checker
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 {
this.number = number;
this.type = type.toLowerCase();
checkSingleNumber();
this.end = end;
this.type = type.toLowerCase();
checkRange();
}
return false;
if (n == 2) {
return true;
if (n % 2 == 0) {
return false;
}
if (n % i == 0) {
return false;
return true;
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;
if (type.equals("prime")) {
if (isPrime(number)) {
} else {
} else if (type.equals("fibonacci")) {
if (isFibonacci(number)) {
System.out.println(number + " is part of the Fibonacci series.");
} else {
}
} else {
System.out.println("Invalid");
}
// Method to check a range of numbers
if (type.equals("prime")) {
if (isPrime(i)) {
result.add(i);
}
System.out.println("Prime numbers in the range " + start + " to " + end + ": " +
result);
} else if (type.equals("fibonacci")) {
if (isFibonacci(i)) {
result.add(i);
}
System.out.println("Fibonacci numbers in the range " + start + " to " + end + ": "
+ result);
} else {
System.out.println("Invalid");
if (parts.length == 1) {
} else if (parts.length == 2) {
int start = Integer.parseInt(parts[0]);
} 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.
import java.util.Scanner;
class NumberChecker {
if (type.equals("perfect") || type.equals("armstrong")) {
if (type.equals("perfect")) {
if (isPerfect(number)) {
} else {
} else {
if (isArmstrong(number)) {
} else {
}
}
} else if (type.equals("range")) {
if (isPerfect(i)) {
}
if (isArmstrong(i)) {
scanner.close();
if (number <= 1) {
return false;
if (number % i == 0) {
sum += i;
if (complement != i) {
sum += complement;
}
int sum = 0;
number /= 10;
}
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;
int n = scanner.nextInt();
intArray[i] = scanner.nextInt();
}
double[] doubleList = new double[n];
doubleList[i] = scanner.nextDouble();
double intSum = 0;
intSum += num;
}
double doubleSum = 0;
doubleSum += num;
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:
3. time (double): representing the time taken to travel the distance in hours.
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;
this.distance = dist;
this.distance = dist;
this.time = hours;
sc.close();
}
Problem Statement
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
import java.util.Scanner;
class Forest {
sc.close();
}
Problem Statement
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 {
if (unit == 'm') {
System.out.printf("%.2f%n", converted);
} else {
}
public class Main {
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.
// Reading input
customObj.greet();
sc.close();
}
this.name = name;
}
public void greet() {
}
Problem Statement
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 {
}
}
class Utility {
}
Problem Statement
import java.util.Scanner;
class GPA_Calculator {
}
// Method to calculate GPA
double sum = 0;
sum += grade;
} else {
class Main {
grades[i] = scanner.nextDouble();
System.out.println(calculator.scholarshipEligibility());
scanner.close();
}
Problem Statement
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 {
class CubeCalculator {
int n = scanner.nextInt();
int cube = n * n * n;
customObj.displayMessage(name);
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.
Formulas used:
import java.util.Scanner;
class SecondsToTime {
if (totalSeconds < 0) {
return;
totalSeconds %= 3600;
return minutes;
}
return seconds;
}
public void setHours(int hours) {
if (hours >= 0) {
this.hours = hours;
if (minutes >= 0) {
this.minutes = minutes;
}
if (seconds >= 0) {
this.seconds = seconds;
class Main {
scanner.close();
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.
Note: Make use of a constructor to initialize the balance and account type while
calculating the interest
import java.util.Scanner;
class BankAccount {
this.balance = balance;
this.accountType = accountType;
}
// Method to calculate yearly interest based on account type
double interestRate = 0;
if (accountType.equalsIgnoreCase("Savings")) {
} else if (accountType.equalsIgnoreCase("Checking")) {
interestRate = 0.02; // 2% for Checking
} else if (accountType.equalsIgnoreCase("Other")) {
class Main {
public static void main(String[] args) {
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.
class AgeCalculatorFunctions {
private int birthYear;
this.birthYear = birthYear;
this.currentYear = currentYear;
return true;
return false;
leapYearsCount++;
}
return leapYearsCount;
class Main {
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 {
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 :
}
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 {
return Math.sqrt(num);
return Math.cbrt(num);
if (scanner.hasNextInt()) {
System.out.format("%.1f", squareRoot);
} else if (scanner.hasNextDouble()) {
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 {
char a, b, c, d;
int s = 0;
@Override
class QuizGameMain {
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 {
@Override
class PolygonMain {
public static void main(String[] args) {
Polygon p;
p = s; // Upcasting to Sphere
p = c; // Upcasting to 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.
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() {
noOfItems = sc.nextInt();
cost = sc.nextDouble();
@Override
cost = sc.nextDouble();
@Override
class ItemMain {
if (choice == 1) {
((Wooden) item).get(sc);
} else if (choice == 2) {
((Electronics) item).get(sc);
} else {
System.out.println("Invalid choice");
sc.close();
return;
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 {
private int r;
this.r = side;
}
System.out.printf("%.2f%n", volume);
private int r, h;
this.r = radius;
this.h = height;
System.out.printf("%.2f%n", volume);
class IcecreamMain {
if (choice == 1) {
int r = sc.nextInt();
} else if (choice == 2) {
int r = sc.nextInt();
int h = sc.nextInt();
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 {
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 {
int n = sc.nextInt();
list.add(num);
System.out.println(sum);
sc.close();
int sum = 0;
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 {
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.
• Convert primitive types (int, double, char, boolean) to their wrapper class objects.
import java.util.Scanner;
import java.util.Scanner;
class Main {
System.out.println("Autoboxing:");
System.out.println("Unboxing:");
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:
import java.util.Scanner;
class Main {
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 {
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 {
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 {
System.out.println("Animal is eating.");
@Override
System.out.println("Bird is flying.");
@Override
System.out.println("Mammal is running.");
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 {
this.name = name;
this.id = id;
super(name, id);
this.salary = salary;
@Override
super.display();
super(name, id);
this.salary = salary;
@Override
public void display() {
super.display();
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.
Attributes:
1. name (String)
2. city (String)
3. age (int)
4. gender (String)
5. billamount (int)
import java.util.Scanner;
class BasicCustomer {
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;
this.city = city;
this.age = age;
this.gender = gender;
this.billamount = billamount;
return name;
return city;
return age;
return gender;
return billamount;
int discount = 0;
public PremiumCustomer() {
public PremiumCustomer(String name, String city, int age, String gender, int billamount, int subamt) {
this.subamt = subamt;
this.subamt = subamt;
return subamt;
@Override
int discount = 0;
class Main {
if (choice == 0) {
bc.setName(name);
bc.setCity(city);
bc.setAge(age);
bc.setGender(gender);
bc.setBillamount(billamount);
bc.calculateDiscount();
} else if (choice == 1) {
pc.setName(name);
pc.setCity(city);
pc.setAge(age);
pc.setGender(gender);
pc.setBillamount(billamount);
pc.setSubamt(subamt);
pc.calculateDiscount();
sc.close();
}
Write a Java program to create a class Shape representing geometric shapes. Implement the following functionalities:
• 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.
import java.util.Scanner;
class Shape {
this.shapeType = shapeType;
super("Rectangle");
this.length = length;
this.width = width;
System.out.println("Creating a rectangle with length " + (int)length + " and width " + (int)width + ".");
super("Circle");
this.radius = radius;
class Main {
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."
import java.util.Scanner;
class Event {
this.name = name;
this.detail = detail;
this.ownerName = ownerName;
return name;
return detail;
return ownerName;
return 0.0;
this.noOfStalls = noOfStalls;
return noOfStalls;
@Override
public StageEvent(String name, String detail, String ownerName, int noOfShows, int noOfSeatsPerShow) {
this.noOfShows = noOfShows;
this.noOfSeatsPerShow = noOfSeatsPerShow;
}
public int getNoOfShows() {
return noOfShows;
return noOfSeatsPerShow;
@Override
class Main {
Event event;
if (choice == 1) {
} else if (choice == 2) {
} 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 {
this.aircraftName = aircraftName;
this.source = source;
this.destination = destination;
public PublicAircraft(String aircraftName, String source, String destination, int noOfKgsAllowed, float additionalFeePerKg) {
this.noOfKgsAllowed = noOfKgsAllowed;
this.additionalFeePerKg = additionalFeePerKg;
displayBasicDetails();
}
}
public PrivateAircraft(String aircraftName, String source, String destination, String pilotPreference, String purpose) {
this.pilotPreference = pilotPreference;
this.purpose = purpose;
displayBasicDetails();
class Main {
sc.nextLine();
if (flightType == 1) {
pubAircraft.displayDetails();
} else if (flightType == 2) {
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 {
this.empId = empId;
this.salary = salary;
System.out.println(empId);
System.out.println(salary);
super(empId, salary);
super.display();
System.out.println(1);
} else {
System.out.println(2);
}
class Main {
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 {
this.grandfatherAge = age;
return grandfatherAge;
this.fatherAge = age;
return fatherAge;
}
return fatherAge + 5;
this.sonAge = age;
return sonAge;
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;
this.title = title;
this.author = author;
super(title, author);
this.genre = genre;
this.daysLate = daysLate;
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 {
this.shapeType = shapeType;
this.radius = radius;
super(shapeType, radius);
return area;
super(shapeType, radius);
this.costPerSquareMeter = costPerSquareMeter;
class Main {
if (shapeType.equals("Sphere")) {
Cost cost = new Cost(shapeType, radius, costPerSquareMeter);
} 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.
import java.util.Scanner;
class Employee {
this.name = name;
this.baseSalary = baseSalary;
return baseSalary;
super(name, baseSalary);
this.bonus = bonus;
}
@Override
@Override
class Main {
if (type == 1) {
System.out.println(eng.calculateNetSalary());
} else if (type == 2) {
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.
import java.util.Scanner;
class FitnessTracker {
this.duration = duration;
this.speed = speed;
class Main {
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:
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 {
this.name = name;
this.age = age;
super(name, age);
this.creditsCompleted = creditsCompleted;
return "Freshman";
return "Sophomore";
} else {
return "Senior";
class Main {
csStudent.displayInfo();
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.
import java.util.Scanner;
class Airline {
return cost;
super(cost);
this.seatAvailability = seatAvailability;
return seatAvailability;
super(cost, seatAvailability);
class Main {
}
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 {
@Override
return -1;
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 {
Note
The calorie calculation formula is: Total caloriesBurned = (total steps / 100.0) * 20.0.
Input format :
import java.util.Scanner;
interface StepCounter {
interface CalorieCalculator {
@Override
int totalSteps = 0;
totalSteps += step;
return totalSteps;
@Override
int n = scanner.nextInt();
steps[i] = scanner.nextInt();
}
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
import java.util.Scanner;
interface ShapeInput {
void inputDimensions();
interface ShapeCalculator {
double calculateArea();
double calculatePerimeter();
@Override
base1 = scanner.nextDouble();
base2 = scanner.nextDouble();
height = scanner.nextDouble();
side1 = scanner.nextDouble();
side2 = scanner.nextDouble();
@Override
@Override
class Main {
trapezoid.inputDimensions();
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 {
interface BudgetCalculator {
double calculateRemainingBudget();
this.initialBudget = initialBudget;
this.totalExpenses = 0.0;
@Override
totalExpenses += expense;
@Override
class Main {
double expense;
tracker.recordExpense(expense);
if (tracker.isBudgetExceeded()) {
} else {
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 {
@Override
return scanner.nextInt();
@Override
int square = n * n;
return strSquare.endsWith(strNumber);
int n = automorphicNumber.getInput();
if (automorphicNumber.isAutomorphic(n)) {
} else {
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.
import java.util.Scanner;
interface Principal {
double getPrincipal();
interface InterestRate {
double getInterestRate();
this.principal = principal;
this.interestRate = interestRate;
this.years = years;
@Override
return principal;
@Override
public double getInterestRate() {
return interestRate;
return principal > 0 && interestRate > 0 && interestRate <= 1 && years > 0;
class Main {
if (loan.isValid()) {
} else {
scanner.close();
}
Problem Statement
Given an array of integers, help Alex find a peak element and its index.
import java.util.Scanner;
class PeakElementFinder{
int N=sc.nextInt();
for(int i=0;i<N;i++){
arr[i]=sc.nextInt();
sc.close();
int peakElement=-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;
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{
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();
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).
Formula:
double panelArea;
double efficiency;
this.panelArea = panelArea;
this.efficiency = efficiency;
class PerformanceCalculator{
double efficiencyRate=sp.efficiency/100;
return sp.panelArea*efficiencyRate*sunlightHours*1.036;
double dailyEnergy=calculateEnergyGenerated(sp,sunlightHours);
return dailyEnergy*electricityRate*365;
double panelArea=scanner.nextDouble();
double efficiency=scanner.nextDouble();
double sunlight=scanner.nextDouble();
double electricityRate=scanner.nextDouble();
scanner.close();
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:
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.
this.basePrice = basePrice;
System.out.printf("Rs. %.2f\n",basePrice);
System.out.printf("Rs. %.2f\n",finalPrice);
}
}
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 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{
this.number=number;
int original=number,reversed=0,remainder;
while(original>0){
remainder=original%10;
reversed=reversed*10+remainder;
original/=10;
return reversed==number;
if (isPalindrome()){
}else{
super(0);
this.word=word;
return word.equalsIgnoreCase(reversed);
if (isPalindrome()){
}else{
}
}
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{
int n= matrix1.length ;
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 {
};
scanner.close();
}
interface APYCalculatorInterface {
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.
Note
interface ShapeInput{
void getInput();
interface ShapeCalculator{
double calculateArea();
double calculatePerimeter();
@Override
base1=scanner.nextDouble();
base2=scanner.nextDouble();
height=scanner.nextDouble();
side1=scanner.nextDouble();
side2=scanner.nextDouble();
scanner.close();
@Override
return 0.5*(base1+base2)*height;
return base1+base2+side1+side2;
Problem Statement
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 {
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;
try {
int N = scanner.nextInt();
scanner.nextLine();
if (numStrings.length > N) {
if (num <= 0) {
}
arr[i] = num;
System.out.print("Array: ");
System.out.println();
} catch (IllegalArgumentException e) {
} catch (ArrayIndexOutOfBoundsException e) {
} finally {
scanner.close();
Problem Statement
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.
transactionsThisMonth += 1
super(message);
super(message);
class BankAccount {
this.balance = initialBalance;
this.isPremium = isPremium;
this.transactionsThisMonth = transactionsThisMonth;
this.bonusAmount = bonusAmount;
return balance;
}
public void withdraw(double amount) throws WithdrawalException, AccountStatusException {
if (bonusAmount < 0) {
double withdrawalFee = amount > withdrawalFeeThreshold ? (isPremium ? 0.01 * amount : 0.02 * amount) : 0;
balance += bonusAmount;
transactionsThisMonth++;
this.transactionsThisMonth = transactionsThisMonth;
this.bonusAmount = bonusAmount;
return balance;
if (bonusAmount < 0) {
double withdrawalFee = amount > withdrawalFeeThreshold ? (isPremium ? 0.01 * amount : 0.02 * amount) : 0;
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.
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".
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 {
try {
int n = Integer.parseInt(scanner.nextLine());
if (input.length != 2) {
validateDistance(distance);
validateTime(time);
// Calculate speed
System.out.printf("%.2f\n", speed);
} catch (NumberFormatException e) {
} 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) {
if (input.toLowerCase().equals("done")) {
break;
}
String[] pair = input.split(":");
if (pair.length == 2) {
try {
valueMap.put(key, value);
} catch (NumberFormatException e) {
System.out.println("Invalid input");
return null;
} else {
System.out.println("Invalid format");
return null;
}
return valueMap;
double sum = 0;
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;
this.regNumber = regNumber;
this.ownerName = ownerName;
this.vehicleType = vehicleType;
System.out.println(v);
return regNumber.equals(vehicle.regNumber);
return Objects.hash(regNumber);
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 static <T> void swap(T[] array, int firstIndex, int secondIndex) {
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;
this.numbers = numbers;
@Override
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;
this.numbers = numbers;
@Override
int n = numbers.length;
int sum = 0;
int cnt = 0;
cnt++;
sum += numbers[i];
synchronized (CountGreaterThanMedianThread.class) {
count = cnt;
if (cnt > 0) {
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.
this.taskId = taskId;
this.prevLatch = prevLatch;
this.currLatch = currLatch;
}
@Override
try {
if (prevLatch != null) {
prevLatch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
currLatch.countDown();