0% found this document useful (0 votes)
16 views103 pages

T0236 - Java Progg - Lab - Record - 2025 - 02 - 04

The document outlines several Java programming exercises, including generating electricity bills based on consumption, finding the k-th smallest element in an array, identifying a subarray with a given sum, and performing matrix addition and subtraction. Each exercise includes input and output formats, along with source code examples. The document also contains execution results demonstrating successful test cases for each program.

Uploaded by

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

T0236 - Java Progg - Lab - Record - 2025 - 02 - 04

The document outlines several Java programming exercises, including generating electricity bills based on consumption, finding the k-th smallest element in an array, identifying a subarray with a given sum, and performing matrix addition and subtraction. Each exercise includes input and output formats, along with source code examples. The document also contains execution results demonstrating successful test cases for each program.

Uploaded by

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

Date: 2025-01-

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:

RMK Engineering College


ElectricityBill.java
import java.util.Scanner;

Page No: 2
public class ElectricityBill {

//write your code here for calculating the bill...


private int consumerNo;

ID: T0236
private String consumerName;
private int previousMonthReading;
private int currentMonthReading;
private String ebConnectionType;

public ElectricityBill(int consumerNo, String consumerName, int


previousMonthReading, int currentMonthReading, String ebConnectionType)
{
this.consumerNo = consumerNo;
this.consumerName = consumerName;
this.previousMonthReading = previousMonthReading;

2024-50-Faculty
this.currentMonthReading = currentMonthReading;
this.ebConnectionType = ebConnectionType;
}

public double calculateBillAmount() {


int unitsConsumed = currentMonthReading - previousMonthReading;
double billAmount = 0;

RMK Engineering College


if (ebConnectionType.equalsIgnoreCase("domestic")) {
if (unitsConsumed <= 100) {
billAmount = unitsConsumed * 1;
} else if (unitsConsumed <= 200) {
billAmount = 100 + (unitsConsumed - 100) * 2.50;
} else if (unitsConsumed <= 500) {
billAmount = 100 + 100 * 2.50 + (unitsConsumed - 200) *
4;
} else {
billAmount = 100 + 100 * 2.50 + 300 * 4 +
(unitsConsumed - 500) * 6;
}
} else if (ebConnectionType.equalsIgnoreCase("commercial")) {
if (unitsConsumed <= 100) {
billAmount = unitsConsumed * 2;
} else if (unitsConsumed <= 200) {
billAmount = 100 + (unitsConsumed - 100) * 4.50;
} else if (unitsConsumed <= 500) {
billAmount = 100 + 100 * 4.50 + (unitsConsumed - 200) *
6;
} else {
billAmount = 100 + 100 * 4.50 + 300 * 6 +

Page No: 3
(unitsConsumed - 500) * 7;
}
}

return billAmount;

ID: T0236
}

public static void main(String[] args) {


Scanner input = new Scanner(System.in);

System.out.print("Consumer Number: ");


int consumerNo = input.nextInt();
input.nextLine();

System.out.print("Consumer Name: ");

2024-50-Faculty
String consumerName = input.nextLine();

System.out.print("Previous Month Reading: ");


int previousMonthReading = input.nextInt();

System.out.print("Current Month Reading: ");


int currentMonthReading = input.nextInt();

RMK Engineering College


input.nextLine();

System.out.print("Domestic/Commercial: ");
String ebConnectionType = input.nextLine();

// Creating ElectricityBill object with user-input data


ElectricityBill bill = new ElectricityBill(consumerNo,
consumerName, previousMonthReading, currentMonthReading,
ebConnectionType);

// Calculating and displaying the bill amount


double billAmount = bill.calculateBillAmount();
System.out.println("Electricity Bill Details:");
System.out.println("Consumer Number: " + consumerNo);
System.out.println("Consumer Name: " + consumerName);
System.out.println("Previous Month Reading: " +
previousMonthReading);
System.out.println("Current Month Reading: " +
currentMonthReading);
System.out.println("EB Connection Type: " + ebConnectionType);
System.out.println("Bill Amount: Rs. " + billAmount);
input.close();

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

RMK Engineering College


Electricity Bill Details:
Consumer Number: 12345
Consumer Name: Swathi
Previous Month Reading: 200
Current Month Reading: 450
EB Connection Type: Domestic
Bill Amount: Rs. 550.0

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:

RMK Engineering College


q42211/KthSmallest.java
package q42211;

Page No: 7
import java.util.Arrays;
import java.util.Scanner;

public class KthSmallest {

ID: T0236
// write the code..
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Reading the number of elements in the array


int n = scanner.nextInt();

// Reading the array elements


int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();

2024-50-Faculty
}

// Reading the position (1-based index)


int position = scanner.nextInt();

// Check for invalid position input


if (position < 1 || position > n) {

RMK Engineering College


System.out.println("Invalid input");
} else {
// Sort the array
Arrays.sort(array);

// Output the smallest element in the array (sorted order)


System.out.println(array[position - 1]);
}

scanner.close();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

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

RMK Engineering College


package q42212;

Page No: 10
import java.util.Scanner;

public class SubarrayWithSum {


// write the code..
public static void main(String[] args) {

ID: T0236
Scanner scanner = new Scanner(System.in);

// Reading the number of elements in the array


int n = scanner.nextInt();

// Reading the array elements


int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}

2024-50-Faculty
// Reading the target sum
int targetSum = scanner.nextInt();

// Call the function to find the subarray


findSubarrayWithSum(array, targetSum);

scanner.close();

RMK Engineering College


}

// Function to find the first subarray with the given sum


public static void findSubarrayWithSum(int[] array, int targetSum)
{
int currentSum = 0;
int start = 0;

// Iterate through the array


for (int end = 0; end < array.length; end++) {
// Add the current element to currentSum
currentSum += array[end];

// If currentSum exceeds the target sum, move the start


pointer forward
while (currentSum > targetSum && start <= end) {
currentSum -= array[start];
start++;
}

// If we found a subarray that sums up to the targetSum


if (currentSum == targetSum) {
System.out.println(start + " " + end);

Page No: 11
return; // Exit the function after finding the first
subarray
}
}

ID: T0236
// If no subarray is found
System.out.println("No subarray");
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

2024-50-Faculty
User Output
5
12375
12
1 3

RMK Engineering College


Test Case - 2

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

RMK Engineering College


package q42213;

Page No: 13
import java.util.Scanner;

public class MatrixAddition {

// write the code..

ID: T0236
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read the size of the matrices (n x n)


//System.out.print("Enter the size of the matrix: ");
int n = scanner.nextInt();

// Create matrices to store the elements


int[][] matrix1 = new int[n][n];
int[][] matrix2 = new int[n][n];
int[][] resultMatrix = new int[n][n];

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();

RMK Engineering College


}
}

// Read elements for the second matrix


//System.out.println("Enter the elements of the second
matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

// Add the matrices


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Print the resulting matrix


//System.out.println("The resulting matrix after addition
is:");
for (int i = 0; i < n; i++) {

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();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

2024-50-Faculty
User Output
2
12
34

RMK Engineering College


45
56
5 7
8 10

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

RMK Engineering College


package q42214;

Page No: 16
import java.util.Scanner;

public class MatrixSubtraction {

// write the code..

ID: T0236
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read the size of the matrices (n x n)


//System.out.print("Enter the size of the matrix: ");
int n = scanner.nextInt();

// Create matrices to store the elements


int[][] matrix1 = new int[n][n];
int[][] matrix2 = new int[n][n];
int[][] resultMatrix = new int[n][n];

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();

RMK Engineering College


}
}

// Read elements for the second matrix


//System.out.println("Enter the elements of the second
matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

// Subtract the matrices


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
resultMatrix[i][j] = matrix1[i][j] - matrix2[i][j];
}
}

// Print the resulting matrix


//System.out.println("The resulting matrix after subtraction
is:");
for (int i = 0; i < n; i++) {

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();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

2024-50-Faculty
User Output
3
123
456

RMK Engineering College


789
987
654
321
-8 -6 -4
-2 0 2
4 6 8

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.

Consider the following example for your understanding

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

RMK Engineering College


Enter row 2: 4 5 6
Multiplication of the two given matrices is:
9 12 15
24 33 42
39 54 69

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;
}

// Initialize the result matrix


int rows1 = matrix1.length;

RMK Engineering College


int cols1 = matrix1[0].length;
int cols2 = matrix2[0].length;
int[][] result = new int[rows1][cols2];

// Perform matrix multiplication


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

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);

int[][] multi = multiplier.multiplication(m1, m2);

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;

RMK Engineering College


for (int j = 0; j < c; j++) {
String spacer = j == c - 1 ?
"\n" : " ";
System.out.print(multi[i][j] +
spacer);
}
}
}
}

public static int[][] readMatrix(Scanner s) {


System.out.print("Enter number of rows: ");
int r = s.nextInt();
System.out.print("Enter number of columns: ");
int c = s.nextInt();
int[][] m = new int[r][c];
System.out.println("Enter " + c + " numbers separated
by space");
for (int i = 0; i < r; i++) {
System.out.print("Enter row " + (i + 1) + ":
");
for (int j = 0; j < c; j++) {
m[i][j] = s.nextInt();

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

RMK Engineering College


Enter row 2:
456
Matrix 2:
Enter number of rows:
3
Enter number of columns:
2
Enter 2 numbers separated by space
Enter row 1:
12
Enter row 2:
34
Enter row 3:
56
Multiplication of the two given matrices is:
22 28
49 64
Test Case - 2

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

RMK Engineering College


Enter row 2:
78
Multiplication of the two given matrices is:
19 22
43 50
Date: 2025-01-
S.No: 7 Exp. Name: Duplicates in Array

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 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the number of elements in the array


int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline character

// Read the elements of the array


String input = scanner.nextLine();

2024-50-Faculty
String[] elements = input.split(" ");

// Use a LinkedHashSet to remove duplicates and maintain order


Set<String> uniqueElements = new LinkedHashSet<>
(Arrays.asList(elements));

// Convert the Set back to an array

RMK Engineering College


String[] resultArray = uniqueElements.toArray(new String[0]);

// Print the resulting array in the required format


System.out.println("Array after removing duplicates:");
for (String element : resultArray) {
System.out.print(element + " ");
}
System.out.println(); // Ensure a newline at the end
scanner.close();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

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

RMK Engineering College


Date: 2025-01-
S.No: 8 Exp. Name: Infinite Sequence

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

RMK Engineering College


package q42500;

Page No: 27
import java.util.Scanner;
//Type your content here
public class FindNthDigit{

public static int findDigitAtPosition(int position) {

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.)

while (position > length * count) {


position -= length * count;
length++; // Increase length (2-digit, 3-digit, etc.)
count *= 10; // Increase count (9, 90, 900, etc.)

2024-50-Faculty
start *= 10; // Increase start (1, 10, 100, etc.)
}

// Now, position is within the current range (length-digit


numbers)
long number = start + (position - 1) / length;
int digitIndex = (int) ((position - 1) % length);

RMK Engineering College


// Convert number to string and get the digit at the position
String numStr = Long.toString(number);
return numStr.charAt(digitIndex) - '0'; // Convert char to int
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
//System.out.print("Enter the position: ");
int position = scanner.nextInt();

int result = findDigitAtPosition(position);


System.out.println(result);

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.

Assume the following values for currency converter

2024-50-Faculty
1 euro = 89.2 INR
1 yen = 0.67 INR
1 dollar = 74.5 INR
Source Code:

ConverterApp.java

RMK Engineering College


import java.util.Scanner;

Page No: 30
import currency.CurrencyConverter;
import distance.DistanceConverter;
import time.TimeConverter;

public class ConverterApp {

ID: T0236
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Choose the conversion type:");


System.out.println("1. Currency");
System.out.println("2. Distance");
System.out.println("3. Time");
int conversionType = scanner.nextInt();

switch (conversionType) {
case 1:

2024-50-Faculty
handleCurrencyConversion(scanner);
break;
case 2:
handleDistanceConversion(scanner);
break;
case 3:
handleTimeConversion(scanner);

RMK Engineering College


break;
default:
System.out.println("Invalid choice");
}
scanner.close();
}

private static void handleCurrencyConversion(Scanner scanner) {


System.out.println("Choose the currency conversion:");
System.out.println("1. Dollar to INR");
System.out.println("2. Euro to INR");
System.out.println("3. Yen to INR");
System.out.println("4. INR to Dollar");
System.out.println("5. INR to Euro");
System.out.println("6. INR to Yen");
int currencyChoice = scanner.nextInt();

//System.out.println("Enter the amount:");


double amount = 0;
double result = 0;

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();

RMK Engineering College


result = CurrencyConverter.inrToDollar(amount);
System.out.println("Dollar: " + result);
break;
case 5:
System.out.println("Enter the amount in
INR:");
amount = scanner.nextDouble();
result = CurrencyConverter.inrToEuro(amount);
System.out.println("Euro: " + result);
break;
case 6:

System.out.println("Enter the amount in INR:");


amount = scanner.nextDouble();
result = CurrencyConverter.inrToYen(amount);
System.out.println("Yen: " + result);
break;
default:
System.out.println("Invalid choice");
}
}
private static void handleDistanceConversion(Scanner scanner) {

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();

//System.out.println("Enter the distance:");


double value = 0;
double result = 0;

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();

RMK Engineering College


result = DistanceConverter.kmToMeter(value);
System.out.println("Meters: " + result);
break;
case 3:
System.out.println("Enter the distance
in miles:");
value = scanner.nextDouble();
result = DistanceConverter.milesToKM(value);
System.out.println("KM: " + result);
break;
case 4:
System.out.println("Enter the distance
in KM:");
value = scanner.nextDouble();
result = DistanceConverter.kmToMiles(value);
System.out.println("Miles: " + result);
break;
default:
System.out.println("Invalid choice");
}
}
private static void handleTimeConversion(Scanner scanner) {

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();

//System.out.println("Enter the time:");


int value = 0;
int result = 0;

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();

RMK Engineering College


result = TimeConverter.minutesToHours(value);
System.out.println("Hours: " + result);
break;
case 3:
System.out.println("Enter the time in
hours:");
value = scanner.nextInt();
result = TimeConverter.hoursToSeconds(value);
System.out.println("Seconds: " + result);
break;
case 4:
System.out.println("Enter the time in
seconds:");
value = scanner.nextInt();
result = TimeConverter.secondsToHours(value);
System.out.println("Hours: " + result);
break;
default:
System.out.println("Invalid choice");
}
}
}

Page No: 34
currency/CurrencyConverter.java

ID: T0236
package currency;
public class CurrencyConverter {

//write your code here....


private static final double DOLLAR_TO_INR = 74.5;
private static final double EURO_TO_INR = 89.2;
private static final double YEN_TO_INR = 0.67;

public static double dollarToINR(double amount) {


return amount * DOLLAR_TO_INR;
}

2024-50-Faculty
public static double euroToINR(double amount) {
return amount * EURO_TO_INR;
}

public static double yenToINR(double amount) {


return amount * YEN_TO_INR;

RMK Engineering College


}

public static double inrToDollar(double amount) {


return amount / DOLLAR_TO_INR;
}

public static double inrToEuro(double amount) {


return amount / EURO_TO_INR;
}

public static double inrToYen(double amount) {


return amount / YEN_TO_INR;
}
}

distance/DistanceConverter.java
package distance;

Page No: 35
public class DistanceConverter {

//write your code here..


public static double meterToKM(double meters) {
return meters / 1000;

ID: T0236
}

public static double kmToMeter(double kilometers) {


return kilometers * 1000;
}

public static double milesToKM(double miles) {


return miles * 1.60934;
}

public static double kmToMiles(double kilometers) {

2024-50-Faculty
return kilometers / 1.60934;
}
}

time/TimeConverter.java

RMK Engineering College


package time;

Page No: 36
public class TimeConverter {

// Converts hours to minutes


public static int hoursToMinutes(int hours) {

ID: T0236
return hours * 60;
}

// Converts minutes to hours


public static int minutesToHours(int minutes) {
return minutes / 60;
}

// Converts hours to seconds


public static int hoursToSeconds(int hours) {
return hours * 3600;

2024-50-Faculty
}

// Converts seconds to hours


public static int secondsToHours(int seconds) {
return seconds / 3600;
}
}

RMK Engineering College


Execution Results - All test cases have succeeded!
Test Case - 1

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

RMK Engineering College


5
Enter the amount in INR:
9000
Euro: 100.89686098654708

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

RMK Engineering College


Test Case - 5

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

RMK Engineering College


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
4
Enter the distance in KM:
65
Miles: 40.38922788223744

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

RMK Engineering College


3. Time
3
Choose the time conversion:
1. Hours to Minutes
2. Minutes to Hours
3. Hours to Seconds
4. Seconds to Hours
2
Enter the time in minutes:
45
Hours: 0

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

RMK Engineering College


2. Minutes to Hours
3. Hours to Seconds
4. Seconds to Hours
4
Enter the time in seconds:
1200
Hours: 0

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

RMK Engineering College


3. Yen to INR
4. INR to Dollar
5. INR to Euro
6. INR to Yen
6
Enter the amount in INR:
560
Yen: 835.820895522388
Date: 2025-01-
S.No: 10 Exp. Name: Square root Checker

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.

What will be the code that helps Ram to achieve this?

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

RMK Engineering College


package q28875;

Page No: 44
// write your code here
import java.util.Scanner;

// User-defined exception for non-integer square roots

ID: T0236
class NotIntegerSqrtException extends Exception {
public NotIntegerSqrtException(String message) {
super(message);
}
}

public class UniqueCalculator {


// write your code here
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

2024-50-Faculty
// Read the integer input
//System.out.print("Enter a number: ");
int num = scanner.nextInt();

try {

RMK Engineering College


// write your code here
// Calculate the square root of the number
double sqrt = Math.sqrt(num);

// Check if the square root is an integer


if (sqrt == (int) sqrt) {
// If it is an integer, print the integer part of the
square root
System.out.println((int) sqrt);
} else {
// If the square root is not an integer, throw the
custom exception
throw new NotIntegerSqrtException("Square root is not
an integer");
}

} 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

RMK Engineering College


Exp. Name: Generate Pay Slips for Date: 2025-01-
S.No: 11

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.

RMK Engineering College


Output Format:
After entering the details, the program will generate and display a pay slip for each
employee. The output will show:
• Employee Name: Name of the employee.
• Employee ID: The unique ID of the employee.
• Address: The address of the employee.
• Mail ID: The email of the employee.
• Mobile Number: The mobile number of the employee.
• Basic Pay: The basic pay entered for the employee.
• DA (Dearness Allowance): Calculated as 97% of the Basic Pay.
• HRA (House Rent Allowance): Calculated as 10% of the Basic Pay.
• PF (Provident Fund): Calculated as 12% of the Basic Pay.
• Staff Club Fund: Calculated as 0.1% of the Basic Pay.
• Gross Salary: Sum of Basic Pay + DA + HRA.
• Net Salary: Gross Salary - PF - Staff Club Fund.

Note: Refer to visible test cases for better understandings.


Source Code:

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;

public Employee(String empName, int empId, String address, String


mailId, long mobileNo) {
this.empName = empName;
this.empId = empId;
this.address = address;
this.mailId = mailId;
this.mobileNo = 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;

RMK Engineering College


double netSalary = grossSalary - PF - staffClubFund;

System.out.println("Pay Slip for " + empName);


System.out.println("Employee ID: " + empId);
System.out.println("Address: " + address);
System.out.println("Mail ID: " + mailId);
System.out.println("Mobile Number: " + mobileNo);
System.out.println("Basic Pay: " + basicPay);
System.out.println("DA: " + DA);
System.out.println("HRA: " + HRA);
System.out.println("PF: " + PF);
System.out.println("Staff Club Fund: " + staffClubFund);
System.out.println("Gross Salary: " + grossSalary);
System.out.println("Net Salary: " + netSalary);
}
}

class Programmer extends Employee {


private double basicPay;

public Programmer(String empName, int empId, String address, String


mailId, long mobileNo, double basicPay) {
super(empName, empId, address, mailId, mobileNo);

Page No: 48
this.basicPay = basicPay;
}

public void generatePaySlip() {


displayPaySlip(basicPay);

ID: T0236
}
}

class AssistantProfessor extends Employee {


private double basicPay;

public AssistantProfessor(String empName, int empId, String


address, String mailId, long mobileNo, double basicPay) {
super(empName, empId, address, mailId, mobileNo);
this.basicPay = basicPay;
}

2024-50-Faculty
public void generatePaySlip() {
displayPaySlip(basicPay);
}
}

class AssociateProfessor extends Employee {

RMK Engineering College


private double basicPay;

public AssociateProfessor(String empName, int empId, String


address, String mailId, long mobileNo, double basicPay) {
super(empName, empId, address, mailId, mobileNo);
this.basicPay = basicPay;
}

public void generatePaySlip() {


displayPaySlip(basicPay);
}
}

class Professor extends Employee {


private double basicPay;

public Professor(String empName, int empId, String address, String


mailId, long mobileNo, double basicPay) {
super(empName, empId, address, mailId, mobileNo);
this.basicPay = basicPay;
}
public void generatePaySlip() {

Page No: 49
displayPaySlip(basicPay);
}
}

public class SalaryManagementSystem {

ID: T0236
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.println("Enter details for Programmer:");


System.out.print("Employee Name: ");
String name = input.nextLine();
System.out.print("Employee ID: ");
int id = input.nextInt();
input.nextLine();
System.out.print("Address: ");
String address = input.nextLine();

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();

RMK Engineering College


Programmer programmer = new Programmer(name, id, address,
mailId, mobileNo, basicPay);
programmer.generatePaySlip();

System.out.println("Enter details for Assistant Professor:");


input.nextLine();
System.out.print("Employee Name: ");
name = input.nextLine();
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();

AssistantProfessor assistantProfessor = new


AssistantProfessor(name, id, address, mailId, mobileNo, basicPay);
assistantProfessor.generatePaySlip();

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();

System.out.println("Enter details for Professor:");


input.nextLine();

RMK Engineering College


System.out.print("Employee Name: ");
name = input.nextLine();
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();

Professor professor = new Professor(name, id, address, mailId,


mobileNo, basicPay);
professor.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

RMK Engineering College


Mail ID: [email protected]
Mobile Number: 9524304564
Basic Pay: 10000.0
DA: 9700.0
HRA: 1000.0
PF: 1200.0
Staff Club Fund: 10.0
Gross Salary: 20700.0
Net Salary: 19490.0
Enter details for Assistant Professor:
Employee Name:
Clarie
Employee ID:
101
Address:
Ottawa
Mail ID:
[email protected]
Mobile Number:
8500212274
Basic Pay:

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:

RMK Engineering College


Washington
Mail ID:
[email protected]
Mobile Number:
9100390742
Basic Pay:
14000
Pay Slip for Licoln
Employee ID: 103
Address: Washington
Mail ID: [email protected]
Mobile Number: 9100390742
Basic Pay: 14000.0
DA: 13580.0
HRA: 1400.0
PF: 1680.0
Staff Club Fund: 14.0
Gross Salary: 28980.0
Net Salary: 27286.0
Enter details for Professor:
Employee Name:

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

RMK Engineering College


PF: 1800.0
Staff Club Fund: 15.0
Gross Salary: 31050.0
Net Salary: 29235.0
Date: 2025-01-
S.No: 12 Exp. Name: Stack ADT using interface

Page No: 54
11

Aim:
Design interface for ADT Stack. Implement this interface using array. Provide necessary

ID: T0236
exception handling in both implementation.

Note: The main function is provided to you in the editor.


Source Code:

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();
}

class Stack_array implements StackADTInterface {


private int[] stack;
private int top;
private final int MAX_SIZE = 5; // Maximum size of the stack

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) {

RMK Engineering College


System.out.println("Stack Overflow! Cannot push to the
stack.");
} else {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the element");
int element = Integer.parseInt(br.readLine());
stack[++top] = element;
//System.out.println("Element pushed: " + element);
}
}

@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

RMK Engineering College


InputStreamReader(System.in));
System.out.println("Implementation of Stack using Array");
Stack_array stk = new Stack_array();
int ch = 0;
do {
System.out.println("1.Push 2.Pop 3.Display 4.Exit");
System.out.println("Enter your choice:");
ch = Integer.parseInt(br.readLine());
switch (ch) {
case 1:
stk.push();
break;
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
case 4:
System.exit(0);
}
} while (ch != 4);
}

Page No: 57
}

Execution Results - All test cases have succeeded!

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

RMK Engineering College


1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
30
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
40
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Elements are: 10 <-- 20 <-- 30 <-- 40 <--
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
2
Popped element: 40
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3

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:

RMK Engineering College


4
Exp. Name: Program to calculate area Date: 2025-01-
S.No: 13

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

RMK Engineering College


width.
• For Triangle: Prompt the user to take two double values representing base and
height.
• For Circle: Prompt the user to take one double value representing radius.

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;

abstract class Shape {

ID: T0236
//Type your content here
protected double dimension1;
protected double dimension2;

// Abstract method to calculate and print the area of the shape


public abstract void printArea();

2024-50-Faculty
class Rectangle extends Shape {

//Type your content here

// Constructor to initialize dimensions

RMK Engineering College


// Constructor to initialize dimensions
public Rectangle(double length, double width) {
this.dimension1 = length;
this.dimension2 = width;
}

// Implementation of printArea for Rectangle


@Override
public void printArea() {
double area = dimension1 * dimension2;
System.out.println("Area of Rectangle: " + area);
}
}

class Triangle extends Shape {

//Type your content here


// Constructor to initialize dimensions
public Triangle(double base, double height) {
this.dimension1 = base;

Page No: 61
this.dimension2 = height;
}

// Implementation of printArea for Triangle


@Override

ID: T0236
public void printArea() {
double area = 0.5 * dimension1 * dimension2;
System.out.println("Area of Triangle: " + area);
}

class Circle extends Shape {

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

RMK Engineering College


}

// Implementation of printArea for Circle


@Override
public void printArea() {
double area = Math.PI * dimension1 * dimension1;
System.out.println("Area of Circle: " + area);
}

public class Main {


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

System.out.print("Length and Width of Rectangle: ");


double length = scanner.nextDouble();
double width = scanner.nextDouble();
Rectangle rectangle = new Rectangle(length, width);
rectangle.printArea();
Page No: 62
System.out.print("Base and Height of Triangle: ");
double base = scanner.nextDouble();
double height = scanner.nextDouble();
Triangle triangle = new Triangle(base, height);
triangle.printArea();

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

RMK Engineering College


Length and Width of Rectangle:
5.5 3.5
Area of Rectangle: 19.25
Base and Height of Triangle:
10 20
Area of Triangle: 100.00
Radius of Circle:
6.25
Area of Circle: 122.72

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:

Area of Circle: 5026.55

RMK Engineering College 2024-50-Faculty ID: T0236 Page No: 63


Exp. Name: Designing a Robust File Date: 2025-01-
S.No: 14

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.

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

RMK Engineering College


Source Code:

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);
}

// Check if destination file already exists


File destinationFile = new File(destinationFilePath);
if (destinationFile.exists()) {
throw new IOException("Destination file already exists: " +

2024-50-Faculty
destinationFilePath);
}

// Perform file copy operation


try (InputStream inputStream = new FileInputStream(sourceFile);
OutputStream outputStream = new
FileOutputStream(destinationFilePath)) {

RMK Engineering College


byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
}

public static void main(String[] args) {


BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
try {
System.out.print("Source file: ");

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

RMK Engineering College


Hello !! Welcome to CodeTantra.

CT.txt

This is a simple example of file copying.

Execution Results - All test cases have succeeded!


Test Case - 1

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

RMK Engineering College


Date: 2025-01-
S.No: 15 Exp. Name: Producer Consumer Concept

Page No: 68
18

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

ID: T0236
consumerconcept.

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


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

The problem revolves around coordinating these threads such that:


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

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:

RMK Engineering College


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

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

q28802/ProducerConsumerDemo.java
package q28802;

Page No: 69
import java.util.LinkedList;
import java.util.Scanner;

// Write your code here...


class SharedBuffer {

ID: T0236
private LinkedList<Integer> buffer = new LinkedList<>();
private int capacity;

public SharedBuffer(int capacity) {


this.capacity = capacity;
}

public synchronized void produce(int item) {


while (buffer.size() == capacity) {
try {
wait();

2024-50-Faculty
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

buffer.add(item);
System.out.println("Produced: " + item);

RMK Engineering College


notify();
}

public synchronized int consume() {


while (buffer.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

int item = buffer.remove();


System.out.println("Consumed: " + item);
notify();
return item;
}
}

class Producer extends Thread {


private SharedBuffer buffer;
private int itemsToProduce;
Page No: 70
public Producer(SharedBuffer buffer, int itemsToProduce) {
this.buffer = buffer;
this.itemsToProduce = itemsToProduce;
}

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
}

class Consumer extends Thread {


private SharedBuffer buffer;
private int itemsToConsume;

public Consumer(SharedBuffer buffer, int itemsToConsume) {

RMK Engineering College


this.buffer = buffer;
this.itemsToConsume = itemsToConsume;
}

@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();
}
}
}
}

public class ProducerConsumerDemo {


// Write your code here...
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number of items to produce

Page No: 71
System.out.print("Enter the number of items to produce: ");
int itemsToProduce = scanner.nextInt();

SharedBuffer buffer = new SharedBuffer(3); // Buffer with


capacity 3

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

RMK Engineering College


User Output
Enter the number of items to produce:
3
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3

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

RMK Engineering College 2024-50-Faculty ID: T0236 Page No: 72


Exp. Name: Reverse the Words and Date: 2025-01-
S.No: 16

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

RMK Engineering College


package q42718;

Page No: 74
import java.util.Scanner;

public class ReverseAndCount {

// write the code..

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();

// Reverse the order of words


for (int i = words.length - 1; i >= 0; i--) {
reversedSentence.append(words[i]).append(" ");
}

2024-50-Faculty
return reversedSentence.toString().trim(); // Remove trailing
space
}

// Function to count the frequency of each letter in the string


(case-insensitive)
public static void countLetterFrequency(String str) {

RMK Engineering College


// Create an array of size 26 to store frequency of each letter
(case-insensitive)
int[] letterFrequency = new int[26];

// Convert string to lower case and iterate over each character


for (char c : str.toLowerCase().toCharArray()) {
if (Character.isLetter(c)) { // Ignore non-alphabetic
characters
letterFrequency[c - 'a']++; // Increment the count for
the corresponding letter
}
}

// Print the letter frequencies


for (int i = 0; i < 26; i++) {
if (letterFrequency[i] > 0) {
System.out.println((char) (i + 'a') + ": " +
letterFrequency[i]);
}
}
}
public static void main(String[] args) {

Page No: 75
Scanner sc = new Scanner(System.in);

// Take input sentence


//System.out.println("Enter a sentence:");
String sentence = sc.nextLine();

ID: T0236
// Reverse the order of words
String reversedSentence = reverseWords(sentence);

// Display the reversed sentence


System.out.println(reversedSentence);

// Count and display the frequency of each letter in the


reversed string
//System.out.println("Letter Frequency in Reversed String:");
countLetterFrequency(reversedSentence);

2024-50-Faculty
sc.close();
}
}

RMK Engineering College


Execution Results - All test cases have succeeded!
Test Case - 1

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

RMK Engineering College


Test Case - 4

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

RMK Engineering College 2024-50-Faculty ID: T0236 Page No: 77


Date: 2025-01-
S.No: 17 Exp. Name: Number of Patterns

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

RMK Engineering College


package q42741;

Page No: 79
import java.util.Scanner;

public class PatternRecognition {

// write the code..

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();

// Loop through the string and check for the pattern


for (int i = 0; i < n - 1; i++) {
// Check if the current character is '1'
if (binaryString.charAt(i) == '1') {
// Look for a subsequent '1' after at least one '0'
for (int j = i + 1; j < n; j++) {

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++;
}

RMK Engineering College


break;
}
}
}
}
return count;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Take input binary string


String binaryString = sc.nextLine();

// Call the function to count patterns and print the result


int result = countPatterns(binaryString);
System.out.println(result);

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

RMK Engineering College


Exp. Name: Remove all the Occurrences Date: 2025-01-
S.No: 18

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

RMK Engineering College


package q42742;

Page No: 82
import java.util.Scanner;
public class RemoveOccurrences {

// write the code..


// Function to remove all occurrences of the substring from the main

ID: T0236
string
public static String removeOccurrences(String mainString, String
subString) {
// Replace all occurrences of subString with an empty string
return mainString.replace(subString, "");
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Take the main string as input

2024-50-Faculty
String mainString = sc.nextLine();

// Take the substring to remove as input


String subString = sc.nextLine();

// Call the function to remove occurrences and print the result


String result = removeOccurrences(mainString, subString);

RMK Engineering College


System.out.println(result);

sc.close();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
mississippi
iss
mippi

Test Case - 2
gh
abcdef
abcdef
User Output

RMK Engineering College 2024-50-Faculty ID: T0236 Page No: 83


Date: 2025-01-
S.No: 19 Exp. Name: Longest Repeating Sequence

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

RMK Engineering College


package q42743;

Page No: 85
import java.util.Scanner;

public class LongestSequence {

// write the code..

ID: T0236
// Function to find the longest repeating subsequence in the string
public static String longestRepeatingSubsequence(String str) {
String longestSeq = "";
int n = str.length();

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


for (int j = i + 1; j < n; j++) {
String lrs = getLongestCommonPrefix(str.substring(i),
str.substring(j));
if (lrs.length() > longestSeq.length()) {
longestSeq = lrs;

2024-50-Faculty
}
}
}
return longestSeq.isEmpty() ? "No repeating sequence" :
longestSeq;
}

RMK Engineering College


// Helper function to find the longest common prefix
private static String getLongestCommonPrefix(String s1, String s2)
{
int i = 0;
while (i < s1.length() && i < s2.length() && s1.charAt(i) ==
s2.charAt(i)) {
i++;
}
return s1.substring(0, i);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println(longestRepeatingSubsequence(sc.nextLine()));
}

Execution Results - All test cases have succeeded!


Test Case - 1

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

RMK Engineering College


package q42744;

Page No: 88
import java.util.Scanner;

public class UniquePermutations {

// write the code..

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;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

2024-50-Faculty
// Take input string from the user
String inputString = sc.nextLine();

// Get the length of the string


int length = inputString.length();

RMK Engineering College


// Calculate the number of distinct permutations, which is
factorial of the length
long distinctPermutations = factorial(length);

// Output the result


System.out.println(distinctPermutations);

sc.close();
}
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
abc
6
24
fast
User Output
Test Case - 2

RMK Engineering College 2024-50-Faculty ID: T0236 Page No: 89


Exp. Name: String Operation on Date: 2025-01-
S.No: 21

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.

RMK Engineering College


• For the Insert String at index operation, the user provides both an index and a
string, and the program inserts the string at the specified index in the list.
• For the Search String operation, the program will output whether the string is
found in the list or not.
• For the List Strings Starting with Letter operation, the program will print each
string from the list that starts with the given letter.
• For the Display List operation, the program will print all strings currently stored in
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;

public class StringOperations {

ID: T0236
// ArrayList to store strings
private ArrayList<String> stringList;

// Constructor to initialize the ArrayList


public StringOperations() {
stringList = new ArrayList<>();
}

// Function to append a string at the end


public void appendString(String str) {
stringList.add(str);

2024-50-Faculty
//System.out.println("Appended: " + str);
}

// Function to insert a string at a specific index


public void insertString(int index, String str) {
if (index >= 0 && index <= stringList.size()) {
stringList.add(index, str);

RMK Engineering College


//System.out.println("Inserted: " + str + " at index " +
index);
} else {
System.out.println("Invalid index");
}
}

// Function to search for a string


public void searchString(String str) {
if (stringList.contains(str)) {
System.out.println(str + " found");
} else {
System.out.println(str + " not found");
}
}

// Function to list all strings that start with a given letter


public void listStringsStartingWith(char letter) {
boolean found = false;
for (String str : stringList) {
if (str.charAt(0) == letter) {
System.out.println(str);
found = true;

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");

RMK Engineering College


System.out.println("3. Search String");
System.out.println("4. Strings Starting with Letter");
System.out.println("5. Display List");
System.out.println("6. Exit");
int choice = sc.nextInt();
sc.nextLine(); // Consume newline

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
}
}
}
}

RMK Engineering College


Execution Results - All test cases have succeeded!
Test Case - 1

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

RMK Engineering College


1. Append String
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
4. Strings Starting with Letter
5. Display List
6. Exit
2
Index to insert at:
2
String to insert:
Four
1. Append String
2. Insert String at index

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

RMK Engineering College


3. Search String
4. Strings Starting with Letter
5. Display List
6. Exit
5
[One, Two, Four, Three, Five]
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:
7
String to insert:
six
Invalid index
1. Append String
2. Insert String at index
3. Search String

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

RMK Engineering College


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
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
4. Strings Starting with Letter
5. Display List
6. Exit

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:

RMK Engineering College


Two
Two found
1. Append String
2. Insert String at index
3. Search String
4. Strings Starting with Letter
5. Display List
6. Exit
3
String to search:
Four
Four not found
1. Append String
2. Insert String at index
3. Search String
4. Strings Starting with Letter
5. Display List
6. Exit
6
Test Case - 3

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

RMK Engineering College


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:
Three
1. Append String
2. Insert String at index
3. Search String
4. Strings Starting with Letter
5. Display List
6. Exit
4
Enter a letter:
T
Two
Three
1. Append String

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

RMK Engineering College


4. Strings Starting with Letter
5. Display List
6. Exit
6
Date: 2025-01-
S.No: 22 Exp. Name: Frequency of Words

Page No: 100


11

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:

RMK Engineering College


WordFrequency.java
import java.util.ArrayList;

Page No: 101


import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class WordFrequency {

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<>();

// write the code..


Map<String, Integer> wordFrequency = new HashMap<>();

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,

RMK Engineering College


wordFrequency.getOrDefault(word, 0) + 1);
}
}

// Display the word frequencies in the order they first appear


for (String word : wordList) {
// Only print the word if it has not been printed before
if (wordFrequency.containsKey(word)) {
System.out.println(word + ": " +
wordFrequency.get(word));
wordFrequency.remove(word); // Remove to avoid
reprinting
}
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a line of text


//System.out.print("Enter a line of text: ");
String text = scanner.nextLine();
Page No: 102
// Call the method to find the word frequency
findWordFrequency(text);

scanner.close();

ID: T0236
}

Execution Results - All test cases have succeeded!


Test Case - 1

User Output
Hello world! This is a test. Hello

2024-50-Faculty
world.
hello: 2
world: 2
this: 1
is: 1

RMK Engineering College


a: 1
test: 1

Test Case - 2

User Output
Sun sun rises Rises in the East
east!!
sun: 2
rises: 2
in: 1
the: 1
east: 2

You might also like