T0236 - Java Progg - Lab - Record - 2025 - 02 - 04
T0236 - Java Progg - Lab - Record - 2025 - 02 - 04
Page No: 1
S.No: 1 Exp. Name: Generate Electricity Bill
12
Aim:
ID: T0236
Develop a Java application to generate Electricity bill. Create a class with the following
members: Consumer no., consumer name, previous month reading, current month
reading, and type of EB connection (i.e., domestic or commercial).
Compute the bill amount using the following tariff.
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
1. First 100 units - Rs. 1 per unit
2. 101-200 units - Rs. 2.50 per unit
3. 201 -500 units - Rs. 4 per unit
4. >501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:
2024-50-Faculty
1. First 100 units - Rs. 2 per unit
2. 101-200 units - Rs. 4.50 per unit
3. 201 -500 units - Rs. 6 per unit
4. >501 units - Rs. 7 per unit
Source Code:
Page No: 2
public class ElectricityBill {
ID: T0236
private String consumerName;
private int previousMonthReading;
private int currentMonthReading;
private String ebConnectionType;
2024-50-Faculty
this.currentMonthReading = currentMonthReading;
this.ebConnectionType = ebConnectionType;
}
Page No: 3
(unitsConsumed - 500) * 7;
}
}
return billAmount;
ID: T0236
}
2024-50-Faculty
String consumerName = input.nextLine();
System.out.print("Domestic/Commercial: ");
String ebConnectionType = input.nextLine();
Page No: 4
}
}
ID: T0236
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
Consumer Number:
12345
Consumer Name:
Swathi
Previous Month Reading:
2024-50-Faculty
200
Current Month Reading:
450
Domestic/Commercial:
Domestic
Test Case - 2
User Output
Consumer Number:
2563
Consumer Name:
Sangeetha
Previous Month Reading:
100
Current Month Reading:
690
Domestic/Commercial:
Commercial
Page No: 5
Electricity Bill Details:
Consumer Number: 2563
Consumer Name: Sangeetha
Previous Month Reading: 100
ID: T0236
Current Month Reading: 690
EB Connection Type: Commercial
Bill Amount: Rs. 2980.0
2024-50-Faculty
RMK Engineering College
Date: 2025-01-
S.No: 2 Exp. Name: kth Smallest Element
Page No: 6
10
Aim:
Write a Java program that takes an unsorted array of n integers and an integer k from the
ID: T0236
user and finds the k smallest element in the array. The array can contain duplicate
th
elements.
Input Format:
• First line is an integer n, representing the number of elements in the array.
• Second line contains n integers separated by spaces, representing the elements of
the array.
• Third line is an integer k representing the position (1-based index) of the element
you need to find after sorting the array.
Output Format:
2024-50-Faculty
• The output is the integer which represents the k th
smallest element of the array.
Note:
• The value of k should be a valid index within the array bounds (i.e., 1 ≤ k ≤ array
length), If k is out of the bond, print "Invalid input" .
• The array elements must be unique.
Source Code:
Page No: 7
import java.util.Arrays;
import java.util.Scanner;
ID: T0236
// write the code..
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
2024-50-Faculty
}
scanner.close();
}
}
User Output
5
58946
2
Page No: 8
5
Test Case - 2
ID: T0236
User Output
6
14 852 625 742 351 748
8
Invalid input
2024-50-Faculty
RMK Engineering College
Date: 2025-01-
S.No: 3 Exp. Name: Sub Array with Given Sum
Page No: 9
10
Aim:
Write a Java program to find a first continuous subarray in a given unsorted array of n
ID: T0236
non-negative integers that adds up to a specified sum S . The program should return the
indices of the subarray if it exists. If no such subarray is found, it should output that no
subarray was found.
Input Format:
• The first line contains an integer n, the number of elements in the array.
• The second line contains n space-separated integers, representing the array
elements.
• The third line contains an integer S , the target sum.
2024-50-Faculty
Output Format:
• If a subarray with the given sum exists, print the 0-based starting and ending
indices of the subarray.
• If no such subarray is found, print No subarray.
Source Code:
q42212/SubarrayWithSum.java
Page No: 10
import java.util.Scanner;
ID: T0236
Scanner scanner = new Scanner(System.in);
2024-50-Faculty
// Reading the target sum
int targetSum = scanner.nextInt();
scanner.close();
Page No: 11
return; // Exit the function after finding the first
subarray
}
}
ID: T0236
// If no subarray is found
System.out.println("No subarray");
}
}
2024-50-Faculty
User Output
5
12375
12
1 3
User Output
10
4 5 96 2 3 5 3 4 8 5
100
No subarray
Date: 2025-01-
S.No: 4 Exp. Name: Matrix Addition
Page No: 12
10
Aim:
Write a Java program to add two matrices of size n × n. The program should print the
ID: T0236
resulting matrix after addition.
Input Format:
• The first integer represents the size n of the square matrices.
• The next n × n integers represent the elements of the first matrix.
• The next n × n integers represent the elements of the second matrix.
Output Format:
• The resulting matrix after addition, printed in matrix form.
Source Code:
2024-50-Faculty
q42213/MatrixAddition.java
Page No: 13
import java.util.Scanner;
ID: T0236
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
2024-50-Faculty
// Read elements for the first matrix
//System.out.println("Enter the elements of the first
matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix1[i][j] = scanner.nextInt();
Page No: 14
for (int j = 0; j < n; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println(); // Move to the next line after
printing each row
ID: T0236
}
scanner.close();
}
}
2024-50-Faculty
User Output
2
12
34
Test Case - 2
User Output
3
454
234
256
123
321
213
5 7 7
5 5 5
4 6 9
Date: 2025-01-
S.No: 5 Exp. Name: Matrix Subtraction
Page No: 15
10
Aim:
Write a Java program to subtract two square matrices of size n × n. The program should
ID: T0236
print the resulting matrix after subtraction.
Input Format:
• The first integer represents the size n of the square matrices.
• The next n × n integers represent the elements of the first matrix.
• The next n × n integers represent the elements of the second matrix.
Output Format:
• The resulting matrix after subtraction, printed in matrix form.
Source Code:
2024-50-Faculty
q42214/MatrixSubtraction.java
Page No: 16
import java.util.Scanner;
ID: T0236
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
2024-50-Faculty
// Read elements for the first matrix
//System.out.println("Enter the elements of the first
matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix1[i][j] = scanner.nextInt();
Page No: 17
for (int j = 0; j < n; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println(); // Move to the next line after
printing each row
ID: T0236
}
scanner.close();
}
}
2024-50-Faculty
User Output
3
123
456
Test Case - 2
User Output
2
56
78
12
34
4 4
4 4
Exp. Name: Program to find Date: 2025-01-
S.No: 6
Page No: 18
Multiplication of Two matrices 09
Aim:
Write a class MultiplicationOfMatrix with a public method multiplication which
ID: T0236
returns the multiplication result of its arguments. if the first argument column size is not
equal to the row size of the second argument, then the method should return null.
Matrix 1:
Enter number of rows: 3
Enter number of columns: 2
Enter 2 numbers separated by space
Enter row 1: 1 2
Enter row 2: 4 5
2024-50-Faculty
Enter row 3: 7 8
Matrix 2:
Enter number of rows: 2
Enter number of columns: 3
Enter 3 numbers separated by space
Enter row 1: 1 2 3
Matrix 1:
Enter number of rows: 2
Enter number of columns: 2
Enter 2 numbers separated by space
Enter row 1: 1 2
Enter row 2: 3 4
Matrix 2:
Enter number of rows: 3
Enter number of columns: 2
Enter 2 numbers separated by space
Enter row 1: 1 2
Enter row 2: 4 5
Enter row 3: 2 3
Multiplication of matrices is not possible
Note: Please don't change the package name.
Source Code:
Page No: 19
q11106/MultiplicationOfMatrix.java
package q11106;
ID: T0236
public class MultiplicationOfMatrix{
public int[][] multiplication(int[][] matrix1, int[][] matrix2)
{
/*Return the result if the matrix1 coloumn size is
equal to matrix2 row size and print the result.
* @Return null.
*/
// Write your logic here for matrix multiplication
// Check if the number of columns in the first matrix is equal to the
number of rows in the second matrix
2024-50-Faculty
if (matrix1[0].length != matrix2.length) {
return null;
}
return result;
}
}
q11106/MultiplicationOfMatrixMain.java
package q11106;
Page No: 20
import java.util.Scanner;
public class MultiplicationOfMatrixMain {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
MultiplicationOfMatrix multiplier = new
ID: T0236
MultiplicationOfMatrix();
System.out.println("Matrix 1:");
int[][] m1 = readMatrix(s);
System.out.println("Matrix 2:");
int[][] m2 = readMatrix(s);
if (multi == null) {
2024-50-Faculty
System.out.println("Multiplication of matrices
is not possible");
} else {
System.out.println("Multiplication of the two
given matrices is:");
for (int i = 0; i < multi.length; i++) {
int c = multi[i].length;
Page No: 21
}
}
return m;
}
}
ID: T0236
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
Matrix 1:
Enter number of rows:
2024-50-Faculty
2
Enter number of columns:
3
Enter 3 numbers separated by space
Enter row 1:
123
Page No: 22
User Output
Matrix 1:
Enter number of rows:
2
ID: T0236
Enter number of columns:
2
Enter 2 numbers separated by space
Enter row 1:
12
Enter row 2:
34
Matrix 2:
Enter number of rows:
2024-50-Faculty
2
Enter number of columns:
2
Enter 2 numbers separated by space
Enter row 1:
56
Page No: 23
11
Aim:
Write a Java program to remove the duplicate elements from the unsorted array
ID: T0236
Input Format:
• The first line of input represents the number of elements n to be entered
• The second line of input represents the n elements separated by a space
Output Format:
• The output should be the array with duplicates removed, preserving the order of
the first occurrence of each element
Source Code:
q42499/Duplicates.java
2024-50-Faculty
RMK Engineering College
package q42499;
Page No: 24
import java.util.Scanner;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.Arrays;
ID: T0236
public class Duplicates {
2024-50-Faculty
String[] elements = input.split(" ");
Page No: 25
User Output
5
12344
ID: T0236
Array after removing duplicates:
1 2 3 4
Test Case - 2
User Output
10
1 2 3 5 8 4 5 1 4 10
Array after removing duplicates:
2024-50-Faculty
1 2 3 5 8 4 10
Page No: 26
11
Aim:
Write a Java program to find the nth digit in the infinite sequence formed by
ID: T0236
concatenating all positive integers in ascending order. For example, the sequence starts
as 12345678910111213... and so on.
Input Format:
The input consists of a single integer n, which represents the position of the digit in the
infinite sequence.
Output Format:
The output should be a single integer which represents the nth digit in the sequence.
Source Code:
2024-50-Faculty
q42500/FindNthDigit.java
Page No: 27
import java.util.Scanner;
//Type your content here
public class FindNthDigit{
ID: T0236
long length = 1; // Length of numbers in the current range (1-
digit, 2-digit, etc.)
long count = 9; // Count of numbers in the current range (9 for
1-digit, 90 for 2-digit, etc.)
long start = 1; // Starting number of the current range (1 for
1-digit, 10 for 2-digit, etc.)
2024-50-Faculty
start *= 10; // Increase start (1, 10, 100, etc.)
}
scanner.close();
}
}
Execution Results - All test cases have succeeded!
Page No: 28
Test Case - 1
User Output
5
ID: T0236
5
Test Case - 2
User Output
25
7
2024-50-Faculty
RMK Engineering College
Date: 2025-01-
S.No: 9 Exp. Name: Currency Converter
Page No: 29
17
Aim:
Develop a Java application to implement currency converter (Dollar to INR, EURO to INR,
ID: T0236
Yen to INR and vice versa), distance converter (meter to KM, miles to KM and vice versa),
time converter (hours to minutes, seconds and vice versa) using packages.
Note:
1. Create a package for each converter (currency, distance, and time).
2. Implement classes for each converter inside their respective packages.
3. Use the main class to provide a user interface for selecting the type of conversion
and calling the appropriate converter class.
4. Your output should match the test cases as displayed.
2024-50-Faculty
1 euro = 89.2 INR
1 yen = 0.67 INR
1 dollar = 74.5 INR
Source Code:
ConverterApp.java
Page No: 30
import currency.CurrencyConverter;
import distance.DistanceConverter;
import time.TimeConverter;
ID: T0236
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
switch (conversionType) {
case 1:
2024-50-Faculty
handleCurrencyConversion(scanner);
break;
case 2:
handleDistanceConversion(scanner);
break;
case 3:
handleTimeConversion(scanner);
switch (currencyChoice) {
case 1:
Page No: 31
System.out.println("Enter the amount in Dollar:");
amount = scanner.nextDouble();
result = CurrencyConverter.dollarToINR(amount);
System.out.println("INR: " + result);
break;
ID: T0236
case 2:
System.out.println("Enter the amount in
Euro:");
amount = scanner.nextDouble();
result = CurrencyConverter.euroToINR(amount);
System.out.println("INR: " + result);
break;
case 3:
System.out.println("Enter the amount in
Yen:");
amount = scanner.nextDouble();
2024-50-Faculty
result = CurrencyConverter.yenToINR(amount);
System.out.println("INR: " + result);
break;
case 4:
System.out.println("Enter the amount in
INR:");
amount = scanner.nextDouble();
Page No: 32
System.out.println("Choose the distance conversion:");
System.out.println("1. Meter to KM");
System.out.println("2. KM to Meter");
System.out.println("3. Miles to KM");
System.out.println("4. KM to Miles");
ID: T0236
int distanceChoice = scanner.nextInt();
switch (distanceChoice) {
case 1:
System.out.println("Enter the distance
in meters:");
value = scanner.nextDouble();
2024-50-Faculty
result = DistanceConverter.meterToKM(value);
System.out.println("KM: " + result);
break;
case 2:
System.out.println("Enter the distance
in KM:");
value = scanner.nextDouble();
Page No: 33
System.out.println("Choose the time conversion:");
System.out.println("1. Hours to Minutes");
System.out.println("2. Minutes to Hours");
System.out.println("3. Hours to Seconds");
System.out.println("4. Seconds to Hours");
ID: T0236
int timeChoice = scanner.nextInt();
switch (timeChoice) {
case 1:
System.out.println("Enter the time in
hours:");
value = scanner.nextInt();
2024-50-Faculty
result = TimeConverter.hoursToMinutes(value);
System.out.println("Minutes: " + result);
break;
case 2:
System.out.println("Enter the time in
minutes:");
value = scanner.nextInt();
Page No: 34
currency/CurrencyConverter.java
ID: T0236
package currency;
public class CurrencyConverter {
2024-50-Faculty
public static double euroToINR(double amount) {
return amount * EURO_TO_INR;
}
distance/DistanceConverter.java
package distance;
Page No: 35
public class DistanceConverter {
ID: T0236
}
2024-50-Faculty
return kilometers / 1.60934;
}
}
time/TimeConverter.java
Page No: 36
public class TimeConverter {
ID: T0236
return hours * 60;
}
2024-50-Faculty
}
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
1
Choose the currency conversion:
1. Dollar to INR
2. Euro to INR
3. Yen to INR
4. INR to Dollar
5. INR to Euro
6. INR to Yen
1
Page No: 37
Enter the amount in Dollar:
30
INR: 2235.0
ID: T0236
Test Case - 2
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
1
Choose the currency conversion:
2024-50-Faculty
1. Dollar to INR
2. Euro to INR
3. Yen to INR
4. INR to Dollar
5. INR to Euro
6. INR to Yen
Test Case - 3
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
1
Choose the currency conversion:
1. Dollar to INR
2. Euro to INR
3. Yen to INR
4. INR to Dollar
5. INR to Euro
6. INR to Yen
20
Page No: 38
Invalid choice
Test Case - 4
ID: T0236
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
2
Choose the distance conversion:
1. Meter to KM
2. KM to Meter
2024-50-Faculty
3. Miles to KM
4. KM to Miles
1
Enter the distance in meters:
100
KM: 0.1
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
2
Choose the distance conversion:
1. Meter to KM
2. KM to Meter
3. Miles to KM
4. KM to Miles
2
Enter the distance in KM:
2
Meters: 2000.0
Test Case - 6
Page No: 39
User Output
Choose the conversion type:
1. Currency
2. Distance
ID: T0236
3. Time
2
Choose the distance conversion:
1. Meter to KM
2. KM to Meter
3. Miles to KM
4. KM to Miles
3
Enter the distance in miles:
2024-50-Faculty
500
KM: 804.67
Test Case - 7
User Output
Test Case - 8
User Output
Choose the conversion type:
1. Currency
Page No: 40
2. Distance
3. Time
3
Choose the time conversion:
ID: T0236
1. Hours to Minutes
2. Minutes to Hours
3. Hours to Seconds
4. Seconds to Hours
1
Enter the time in hours:
2
Minutes: 120
2024-50-Faculty
Test Case - 9
User Output
Choose the conversion type:
1. Currency
2. Distance
Test Case - 10
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
3
Choose the time conversion:
Page No: 41
1. Hours to Minutes
2. Minutes to Hours
3. Hours to Seconds
4. Seconds to Hours
ID: T0236
3
Enter the time in hours:
2
Seconds: 7200
Test Case - 11
User Output
Choose the conversion type:
2024-50-Faculty
1. Currency
2. Distance
3. Time
3
Choose the time conversion:
1. Hours to Minutes
Test Case - 12
User Output
Choose the conversion type:
1. Currency
2. Distance
3. Time
1
Choose the currency conversion:
1. Dollar to INR
2. Euro to INR
3. Yen to INR
Page No: 42
4. INR to Dollar
5. INR to Euro
6. INR to Yen
4
ID: T0236
Enter the amount in INR:
50000
Dollar: 671.1409395973154
Test Case - 13
User Output
Choose the conversion type:
1. Currency
2024-50-Faculty
2. Distance
3. Time
1
Choose the currency conversion:
1. Dollar to INR
2. Euro to INR
Page No: 43
11
Aim:
Ram wants to create a unique calculator that prints the square root of the given number if
ID: T0236
the square root is an integer, otherwise, it will need to print Square root is not an
integer. Ram wants to build this calculator by using user-defined exceptions in Java.
Input Format:
• The input line reads an integer whose square root needs to be printed.
Output Format:
• The output is an integer if the square root of the given number is an integer,
otherwise, it will print Square root is not an integer by using an exception.
2024-50-Faculty
Source Code:
q28875/UniqueCalculator.java
Page No: 44
// write your code here
import java.util.Scanner;
ID: T0236
class NotIntegerSqrtException extends Exception {
public NotIntegerSqrtException(String message) {
super(message);
}
}
2024-50-Faculty
// Read the integer input
//System.out.print("Enter a number: ");
int num = scanner.nextInt();
try {
} catch (NotIntegerSqrtException e) {
// write your code here
// Handle the exception and print the message
System.out.println(e.getMessage());
Page No: 45
}
scanner.close();
}
}
ID: T0236
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
16
4
2024-50-Faculty
Test Case - 2
User Output
10
Square root is not an integer
Page No: 46
Employees 17
Aim:
Develop a Java application with an Employee class with Emp_name, Emp_id, Address,
ID: T0236
Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant Professor,
Associate Professor and Professor from employee class. Add Basic Pay (BP) as the
member of all the inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP
as PF, and 0.1% of BP for staff club fund. Generate pay slips for the employees with their
gross and net salary.
Input Format:
The program will prompt the user to input details for four types of employees
(Programmer, Assistant Professor, Associate Professor, and Professor). For each employee,
the following details are required:
• Employee Name: The name of the employee.
2024-50-Faculty
• Employee ID: A unique ID for the employee.
• Address: The employee's address.
• Mail ID: The email address of the employee.
• Mobile Number: The mobile number of the employee (long integer).
• Basic Pay: The employee's basic pay (a floating-point number).
Each employee's details will be entered one by one. After the details for each employee
are entered, the payslip will be generated.
SalaryManagementSystem.java
import java.util.Scanner;
Page No: 47
class Employee {
protected String empName;
protected int empId;
protected String address;
ID: T0236
protected String mailId;
protected long mobileNo;
2024-50-Faculty
public void displayPaySlip(double basicPay) {
double DA = 0.97 * basicPay;
double HRA = 0.1 * basicPay;
double PF = 0.12 * basicPay;
double staffClubFund = 0.001 * basicPay;
double grossSalary = basicPay + DA + HRA;
Page No: 48
this.basicPay = basicPay;
}
ID: T0236
}
}
2024-50-Faculty
public void generatePaySlip() {
displayPaySlip(basicPay);
}
}
Page No: 49
displayPaySlip(basicPay);
}
}
ID: T0236
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
2024-50-Faculty
System.out.print("Mail ID: ");
String mailId = input.nextLine();
System.out.print("Mobile Number: ");
long mobileNo = input.nextLong();
System.out.print("Basic Pay: ");
double basicPay = input.nextDouble();
Page No: 50
System.out.println("Enter details for Associate Professor:");
input.nextLine();
System.out.print("Employee Name: ");
name = input.nextLine();
ID: T0236
System.out.print("Employee ID: ");
id = input.nextInt();
input.nextLine();
System.out.print("Address: ");
address = input.nextLine();
System.out.print("Mail ID: ");
mailId = input.nextLine();
System.out.print("Mobile Number: ");
mobileNo = input.nextLong();
System.out.print("Basic Pay: ");
basicPay = input.nextDouble();
2024-50-Faculty
AssociateProfessor associateProfessor = new
AssociateProfessor(name, id, address, mailId, mobileNo, basicPay);
associateProfessor.generatePaySlip();
input.close();
}
}
Execution Results - All test cases have succeeded!
Page No: 51
Test Case - 1
User Output
Enter details for Programmer:
ID: T0236
Employee Name:
John
Employee ID:
100
Address:
Princeton
Mail ID:
[email protected]
Mobile Number:
9524304564
2024-50-Faculty
Basic Pay:
10000
Pay Slip for John
Employee ID: 100
Address: Princeton
Page No: 52
12000
Pay Slip for Clarie
Employee ID: 101
Address: Ottawa
ID: T0236
Mail ID: [email protected]
Mobile Number: 8500212274
Basic Pay: 12000.0
DA: 11640.0
HRA: 1200.0
PF: 1440.0
Staff Club Fund: 12.0
Gross Salary: 24840.0
Net Salary: 23388.0
Enter details for Associate Professor:
2024-50-Faculty
Employee Name:
Licoln
Employee ID:
103
Address:
Page No: 53
Krem
Employee ID:
105
Address:
ID: T0236
Loss angels
Mail ID:
[email protected]
Mobile Number:
9010692094
Basic Pay:
15000
Pay Slip for Krem
Employee ID: 105
2024-50-Faculty
Address: Loss angels
Mail ID: [email protected]
Mobile Number: 9010692094
Basic Pay: 15000.0
DA: 14550.0
HRA: 1500.0
Page No: 54
11
Aim:
Design interface for ADT Stack. Implement this interface using array. Provide necessary
ID: T0236
exception handling in both implementation.
StackADT.java
2024-50-Faculty
RMK Engineering College
import java.io.*;
Page No: 55
//write your code here...
interface StackADTInterface {
ID: T0236
void push() throws IOException;
void pop();
void display();
}
public Stack_array() {
2024-50-Faculty
stack = new int[MAX_SIZE];
top = -1; // Empty stack
}
@Override
public void push() throws IOException {
if (top == MAX_SIZE - 1) {
@Override
public void pop() {
if (top == -1) {
System.out.println("Stack Underflow! Cannot pop from the
stack.");
} else {
int poppedElement = stack[top--];
System.out.println("Popped element: " + poppedElement);
}
}
Page No: 56
@Override
public void display() {
if (top == -1) {
System.out.println("Stack is empty");
} else {
ID: T0236
System.out.print("Elements are: ");
for (int i = 0; i <= top; i++) {
if (i == top) {
System.out.print(stack[i] + " <--");
} else {
System.out.print(stack[i] + " <-- ");
}
}
System.out.println();
}
}
2024-50-Faculty
}
class StackADT {
public static void main(String arg[]) throws IOException {
BufferedReader br = new BufferedReader(new
Page No: 57
}
ID: T0236
Test Case - 1
User Output
Implementation of Stack using Array
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
10
2024-50-Faculty
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
20
Page No: 58
Elements are: 10 <-- 20 <-- 30 <--
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
2
ID: T0236
Popped element: 30
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
2
Popped element: 20
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
2
Popped element: 10
2024-50-Faculty
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Stack is empty
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
Page No: 59
of shapes using abstract classes 11
Aim:
Write a Java program that defines an abstract class Shape with three subclasses
ID: T0236
(Rectangle, Triangle, Circle). Each subclass calculates and prints the area of the respective
shape based on user-provided dimensions. Implement the program as described below:
Define an abstract class Shape with the following attributes and methods:
Attributes:
• dimension1 (double)
• dimension2 (double)
Methods:
• public abstract void printArea() - an abstract method to calculate and print the
area of the shape.
2024-50-Faculty
Implement three subclasses of Shape:
• Rectangle: Computes area using the formulalength × width
• Triangle: Computes area using the formula0.5 × base × height
• Circle: Computes area using the formula PI x Radius x Radius [Hint : Use Math.PI]
Input Format:
• For Rectangle: Prompt the user to take two double values representing length and
Output Format:
• The program should print each area formatted to two decimal places on a new
line, prefixed with the shape name followed by the calculated area
Note: Refer to the sample test cases for print statements to be entered
Source Code:
q35629/Main.java
package q35629;
Page No: 60
import java.util.Scanner;
ID: T0236
//Type your content here
protected double dimension1;
protected double dimension2;
2024-50-Faculty
class Rectangle extends Shape {
Page No: 61
this.dimension2 = height;
}
ID: T0236
public void printArea() {
double area = 0.5 * dimension1 * dimension2;
System.out.println("Area of Triangle: " + area);
}
2024-50-Faculty
//Type your content here
// Constructor to initialize radius
public Circle(double radius) {
this.dimension1 = radius;
this.dimension2 = 0; // No second dimension for a circle
ID: T0236
System.out.print("Radius of Circle: ");
double radius = scanner.nextDouble();
Circle circle = new Circle(radius);
circle.printArea();
scanner.close();
}
}
2024-50-Faculty
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
Test Case - 2
User Output
Length and Width of Rectangle:
10 20
Area of Rectangle: 200.00
Base and Height of Triangle:
20 30
Area of Triangle: 300.00
40
Radius of Circle:
Page No: 64
Copying Program in Java 11
Aim:
Imagine you are tasked with designing a Java program to facilitate the copying of
ID: T0236
contents from one file to another. Your objective is to allow users to input both the source
and destination file names. Additionally, you need to implement robust error handling to
gracefully manage scenarios such as files not found during the file copying process.
How would you structure this Java program to achieve the desired functionality, ensuring
a user-friendly experience and effective handling of potential errors?
Input Format:
The first input line reads a string representing the source file name.
The second input line reads a string representing the destination file name.
2024-50-Faculty
Output Format:
The output line prints a string File copied successfully! if the file copied successfully
otherwise it will print Error: Source file not found: <file name> if the source file doesn't
exist or it will print Error: Destination file already exists: <file name> if the destination
file is already exists.
q22114/Main.java
package q22114;
Page No: 65
import java.io.*;
public class Main {
private static void copyFile(String sourceFilePath, String
destinationFilePath) throws IOException {
// write your code here
ID: T0236
// Check if source file exists
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists()) {
throw new FileNotFoundException("Source file not found: " +
sourceFilePath);
}
2024-50-Faculty
destinationFilePath);
}
Page No: 66
String sourceFilePath = reader.readLine();
System.out.print("Destination file: ");
String destinationFilePath = reader.readLine();
copyFile(sourceFilePath, destinationFilePath);
System.out.println("File copied successfully!");
ID: T0236
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurred: " +
e.getMessage());
} finally {
try {
reader.close();
} catch (IOException e) {
System.out.println("Error closing the input stream");
}
2024-50-Faculty
}
}
}
ss.txt
CT.txt
User Output
Source file:
ss.txt
Destination file:
new_file.txt
File copied successfully!
Test Case - 2
Page No: 67
User Output
Source file:
ss.txt
Destination file:
ID: T0236
new_file.txt
Error: Destination file already exists: new_file.txt
Test Case - 3
User Output
Source file:
hello.txt
Destination file:
2024-50-Faculty
file1.txt
Error: Source file not found: hello.txt
Page No: 68
18
Aim:
Write a Java program using synchronized threads, which demonstrates producer
ID: T0236
consumerconcept.
2024-50-Faculty
• The consumer does not consume when the buffer is empty.
• Both threads operate safely without corrupting the shared resource.
To achieve synchronization in Java, we can use the synchronized keyword along with wait
and notify methods to control the interaction between the threads.
Input Format:
Output Format:
Output should print the following:
• Messages indicating the production of each item as <Produced: {Produced item}>
• Messages indicating the consumption of each item as <Consumed: {Consumed
item}>
Source Code:
q28802/ProducerConsumerDemo.java
package q28802;
Page No: 69
import java.util.LinkedList;
import java.util.Scanner;
ID: T0236
private LinkedList<Integer> buffer = new LinkedList<>();
private int capacity;
2024-50-Faculty
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
buffer.add(item);
System.out.println("Produced: " + item);
ID: T0236
@Override
public void run() {
for (int i = 1; i <= itemsToProduce; i++) {
buffer.produce(i);
try {
Thread.sleep(100); // Simulate some production time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
2024-50-Faculty
}
@Override
public void run() {
for (int i = 1; i <= itemsToConsume; i++) {
buffer.consume();
try {
Thread.sleep(100); // Simulate some consumption time
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
Page No: 71
System.out.print("Enter the number of items to produce: ");
int itemsToProduce = scanner.nextInt();
ID: T0236
Producer producer = new Producer(buffer, itemsToProduce);
Consumer consumer = new Consumer(buffer, itemsToProduce);
producer.start();
consumer.start();
scanner.close();
}
}
2024-50-Faculty
Execution Results - All test cases have succeeded!
Test Case - 1
Test Case - 2
User Output
Enter the number of items to produce:
4
Produced: 1
Consumed: 1
Produced: 2
Consumed: 4
Produced: 4
Consumed: 3
Produced: 3
Consumed: 2
Page No: 73
Count the Letters in a Sentence 11
Aim:
Write a Java program that takes a sentence as input and reverse the order of the words
ID: T0236
and count the frequency of each letter in the reversed string. The program should count
the frequency of each letter (case-insensitive), ignoring non-alphabetic characters.
Input Format:
• The program should prompt the user to enter a string of words.
Output Format:
• Display the reversed words.
• Display the frequency of each letter in the reversed string.
Source Code:
2024-50-Faculty
q42718/ReverseAndCount.java
Page No: 74
import java.util.Scanner;
ID: T0236
// Function to reverse the order of words in the sentence
public static String reverseWords(String sentence) {
String[] words = sentence.split("\\s+"); // Split sentence into
words
StringBuilder reversedSentence = new StringBuilder();
2024-50-Faculty
return reversedSentence.toString().trim(); // Remove trailing
space
}
Page No: 75
Scanner sc = new Scanner(System.in);
ID: T0236
// Reverse the order of words
String reversedSentence = reverseWords(sentence);
2024-50-Faculty
sc.close();
}
}
User Output
Java is fun
fun is Java
a: 2
f: 1
i: 1
j: 1
n: 1
s: 1
u: 1
v: 1
Test Case - 2
User Output
sun rises in the east
east the in rises sun
Page No: 76
a: 1
e: 3
h: 1
i: 2
ID: T0236
n: 2
r: 1
s: 4
t: 2
u: 1
Test Case - 3
User Output
2024-50-Faculty
abc aaa bca abc abb bcc
bcc abb abc bca aaa abc
a: 7
b: 6
c: 5
User Output
codetantra is a learning platform
platform learning a is codetantra
a: 5
c: 1
d: 1
e: 2
f: 1
g: 1
i: 2
l: 2
m: 1
n: 3
o: 2
p: 1
r: 3
s: 1
t: 3
Page No: 78
11
Aim:
Given a binary string, your task is to find the number of patterns of form 1[0]1, where [0]
ID: T0236
represents any number of consecutive zeroes (with at least one 0), and there should not
be any other character except 0 in the [0] sequence. The pattern must start with a 1,
followed by one or more zeroes, and end with a 1.
Write a Java program that will take a binary string as input and display the number of
such patterns found.
Input Format:
• A line containing a binary string, where each character is either 0 or 1.
Output Format:
2024-50-Faculty
• An integer representing the number of patterns of the form 1[0]1 found in the
binary string.
Source Code:
q42741/PatternRecognition.java
Page No: 79
import java.util.Scanner;
ID: T0236
// Function to find the number of patterns of the form 1[0]+1
public static int countPatterns(String binaryString) {
int count = 0;
int n = binaryString.length();
2024-50-Faculty
if (binaryString.charAt(j) == '1') {
// Ensure there is at least one '0' between the
'1's
if (j > i + 1 && binaryString.charAt(i + 1) ==
'0') {
count++;
}
sc.close();
}
}
Execution Results - All test cases have succeeded!
Page No: 80
Test Case - 1
User Output
10101
ID: T0236
2
Test Case - 2
User Output
1001
1
Test Case - 3
2024-50-Faculty
User Output
11111110000000
0
Page No: 81
of the Substring in a String 11
Aim:
Given two strings S1 and S2, your task is to remove all occurrences of string S2 in S1
ID: T0236
and print the remaining part of S1. If S2 is not found in S1, the original string S1 should
be printed unchanged.
Write a Java program that will take two strings as input: S1 (the main string) and S2 (the
substring to be removed). The program will output the modified string after removing all
instances of S2.
Input Format:
• The first line contains a string S1, where S1 consists of any characters.
• The second line contains a string S2, where S2 consists of any characters.
2024-50-Faculty
Output Format:
• A single line containing the modified version of string S1, with all occurrences of
S2 removed. If S2 is not found in S1, print S1 unchanged.
Source Code:
q42742/RemoveOccurrences.java
Page No: 82
import java.util.Scanner;
public class RemoveOccurrences {
ID: T0236
string
public static String removeOccurrences(String mainString, String
subString) {
// Replace all occurrences of subString with an empty string
return mainString.replace(subString, "");
}
2024-50-Faculty
String mainString = sc.nextLine();
sc.close();
}
}
User Output
mississippi
iss
mippi
Test Case - 2
gh
abcdef
abcdef
User Output
Page No: 84
12
Aim:
Given a string S , your task is to find the longest repeating sequence of characters in the
ID: T0236
string. A repeating sequence is defined as a substring that appears more than once in the
string. The program should return the longest such repeating sequence. If there are no
repeating sequences, the program should display No repeating sequence.
Write a Java program that takes a string S as input and outputs the longest repeating
sequence of characters. If there is no repeating sequence, print a specific message.
Input Format:
• A single line containing a string S , consisting of lowercase or uppercase letters.
Output Format:
2024-50-Faculty
• A single line containing the longest repeating sequence of characters in S .
• If there is no repeating sequence, print No repeating sequence.
Source Code:
q42743/LongestSequence.java
Page No: 85
import java.util.Scanner;
ID: T0236
// Function to find the longest repeating subsequence in the string
public static String longestRepeatingSubsequence(String str) {
String longestSeq = "";
int n = str.length();
2024-50-Faculty
}
}
}
return longestSeq.isEmpty() ? "No repeating sequence" :
longestSeq;
}
Page No: 86
User Output
banana
ana
ID: T0236
Test Case - 2
User Output
abcdef
No repeating sequence
2024-50-Faculty
RMK Engineering College
Date: 2025-01-
S.No: 20 Exp. Name: Unique String Values
Page No: 87
11
Aim:
Given a string S containing unique characters, your task is to calculate the number of
ID: T0236
distinct permutations that can be formed by rearranging the letters of the string.
Write a Java program that takes a string S as input and outputs the number of distinct
permutations that can be formed.
Input Format:
• A single line containing a string S , where each character is unique (all distinct
letters).
Output Format:
• A single integer represents the number of distinct permutations that can be
2024-50-Faculty
formed from the string S .
Source Code:
q42744/UniquePermutations.java
Page No: 88
import java.util.Scanner;
ID: T0236
// Function to calculate factorial of a number
public static long factorial(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
2024-50-Faculty
// Take input string from the user
String inputString = sc.nextLine();
sc.close();
}
}
User Output
abc
6
24
fast
User Output
Test Case - 2
Page No: 90
ArrayList 11
Aim:
Write a Java program that performs various string operations using an ArrayList.
ID: T0236
Implement the following functionalities:
5. Append: Add a string to the end of the list.
6. Insert: Add a string at a specified index in the list.
7. Search: Search for a string in the list and indicate whether it exists.
8. List all strings starting with a given letter: Print all strings from the list that start
with a specified letter.
9. Display the list: Show all strings currently stored in the list.
Input Format:
• The program should prompt the user to select an operation from a menu.
• For the Insert operation, the user should input an index (0-based) and a string.
2024-50-Faculty
• For the Search operation, the user should input the string they want to search for.
• For the List operation, the user should input a letter.
Output Format:
• For the Append String operation, after entering the string to append, the program
simply adds it to the list.
Note:
The main method has been provided to you in the editor, you are required to fill in the
remaining function bodies.
Source Code:
q42745/StringOperations.java
package q42745;
Page No: 91
import java.util.ArrayList;
import java.util.Scanner;
ID: T0236
// ArrayList to store strings
private ArrayList<String> stringList;
2024-50-Faculty
//System.out.println("Appended: " + str);
}
Page No: 92
}
}
if (!found) {
System.out.println("No strings found");
}
ID: T0236
}
// Function to display the list of strings
public void displayList() {
if (stringList.isEmpty()) {
System.out.println("list is empty");
} else {
System.out.println(stringList);
}
}
2024-50-Faculty
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringOperations operations = new StringOperations();
while (true) {
System.out.println("1. Append String");
System.out.println("2. Insert String at index");
switch (choice) {
case 1:
System.out.println("String to append:");
String strToAppend = sc.nextLine();
operations.appendString(strToAppend);
break;
case 2:
System.out.println("Index to insert at:");
int index = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.println("String to insert:");
String strToInsert = sc.nextLine();
operations.insertString(index, strToInsert);
break;
case 3:
System.out.println("String to search:");
Page No: 93
String strToSearch = sc.nextLine();
operations.searchString(strToSearch);
break;
case 4:
System.out.println("Enter a letter:");
ID: T0236
char letter = sc.nextLine().charAt(0);
operations.listStringsStartingWith(letter);
break;
case 5:
operations.displayList();
break;
case 6:
sc.close();
return;
default:
System.out.println("Invalid choice");
2024-50-Faculty
}
}
}
}
User Output
1. Append String
2. Insert String at index
3. Search String
4. Strings Starting with Letter
5. Display List
6. Exit
5
list is empty
1. Append String
2. Insert String at index
3. Search String
4. Strings Starting with Letter
5. Display List
6. Exit
1
String to append:
Page No: 94
One
1. Append String
2. Insert String at index
3. Search String
ID: T0236
4. Strings Starting with Letter
5. Display List
6. Exit
1
String to append:
Two
1. Append String
2. Insert String at index
3. Search String
2024-50-Faculty
4. Strings Starting with Letter
5. Display List
6. Exit
1
String to append:
Three
Page No: 95
3. Search String
4. Strings Starting with Letter
5. Display List
6. Exit
ID: T0236
5
[One, Two, Four, Three]
1. Append String
2. Insert String at index
3. Search String
4. Strings Starting with Letter
5. Display List
6. Exit
2
Index to insert at:
2024-50-Faculty
4
String to insert:
Five
1. Append String
2. Insert String at index
Page No: 96
4. Strings Starting with Letter
5. Display List
6. Exit
7
ID: T0236
Invalid choice
1. Append String
2. Insert String at index
3. Search String
4. Strings Starting with Letter
5. Display List
6. Exit
6
2024-50-Faculty
Test Case - 2
User Output
1. Append String
2. Insert String at index
3. Search String
Page No: 97
1
String to append:
Three
1. Append String
ID: T0236
2. Insert String at index
3. Search String
4. Strings Starting with Letter
5. Display List
6. Exit
5
[One, Two, Three]
1. Append String
2. Insert String at index
3. Search String
2024-50-Faculty
4. Strings Starting with Letter
5. Display List
6. Exit
3
String to search:
Page No: 98
User Output
1. Append String
2. Insert String at index
3. Search String
ID: T0236
4. Strings Starting with Letter
5. Display List
6. Exit
1
String to append:
One
1. Append String
2. Insert String at index
3. Search String
2024-50-Faculty
4. Strings Starting with Letter
5. Display List
6. Exit
1
String to append:
Two
Page No: 99
2. Insert String at index
3. Search String
4. Strings Starting with Letter
5. Display List
ID: T0236
6. Exit
4
Enter a letter:
F
No strings found
1. Append String
2. Insert String at index
3. Search String
4. Strings Starting with Letter
5. Display List
2024-50-Faculty
6. Exit
5
[One, Two, Three]
1. Append String
2. Insert String at index
3. Search String
Aim:
Write a Java program that finds the frequency of words in a given text using an ArrayList.
The program should read input text from the user, split the text into individual words, and
ID: T0236
then count the occurrences of each word.
Requirements:
10. Split the text into words, treating punctuation and whitespace as delimiters.
11. Count the frequency of each word, making the count case-insensitive.
12. Display the word frequencies in the format: {word}: {frequency}.
Input Format:
• The program should prompt the user to enter a line of text.
2024-50-Faculty
Output Format:
• The program should print the frequency of each word in the text.
Source Code:
ID: T0236
// Method to find the frequency of words in the given text
public static void findWordFrequency(String text) {
// Split the text into words
String[] words = text.split("\\W+"); // Split by non-word
characters
ArrayList<String> wordList = new ArrayList<>();
2024-50-Faculty
// Convert all words to lowercase and add them to the wordList
for (String word : words) {
if (!word.isEmpty()) {
word = word.toLowerCase(); // Ensure case insensitivity
wordList.add(word);
// Increment the word frequency count in the map
wordFrequency.put(word,
scanner.close();
ID: T0236
}
User Output
Hello world! This is a test. Hello
2024-50-Faculty
world.
hello: 2
world: 2
this: 1
is: 1
Test Case - 2
User Output
Sun sun rises Rises in the East
east!!
sun: 2
rises: 2
in: 1
the: 1
east: 2