R.M.D. ENGINEERING COLLEGE (An Autonomous Institution) R.S.M Nagar, Kavaraipettai, GummidipoondiTaluk, ThiruvallurDt- 601 206. Regulation 2024 24CS202 - JAVA PROGRAMMING (LAB INTEGRATED) LABORATORY MANUAL B.E./B.TECH - FIRST YEAR COMMON FOR ALL BRANCHES SYLLABUS 24CS202 Java Programming 2 24CS202 JAVA PROGRAMMING (Common to All Branches) L T P C 3 0 3 4.5 OBJECTIVES: The Course will enable learners to: To explain object oriented programming concepts and fundamentals of Java To apply the principles of packages, interfaces and exceptions To develop a Java application with I/O streams, threads and generic programming To build applications using strings and collections. To apply the JDBC concepts List of Exercise/Experiments: 1. Develop a Java application to generate Electricity bill. You must use one super class called EB Bill and must have two sub classes namely Domestic Bill and Commercial Bill. Create a class with the following members: Consumer no., consumer name, previous month reading, current month reading, type of EB connection (i.e domestic or commercial). Compute the bill amount using the following tariff a. If the type of the EB connection is domestic, calculate the amount to be paid as follows: First 100 units - Rs. 1 per unit b. 101-200 units - Rs. 2.50 per unit 201 -500 units - Rs. 4 per unit c. 501 units - Rs. 6 per unit d. If the type of the EB connection is commercial, calculate the amount to be paid as follows: First 100 units - Rs. 2 per unit e. 101-200 units - Rs. 4.50 per unit 201 -500 units - Rs. 6 per unit f. 501 units - Rs. 7 per unit 2. Arrays Manipulations: (Use Methods for implementing these in a Class) a. Find kth smallest element in an unsorted array b. Find the sub array with given sum c. Matrix manipulations – Addition, Subtraction, Multiplication d. Remove duplicate elements in an Array e. Accept an integer value N and print the Nth digit in the integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 and so on till infinity. Example: The 11th digit in the sequence 12345678910111213.... is 0. 3. Develop a Java application to implement currency converter (Dollar to INR, EURO to INR, 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. 4. Develop a Java application with Employee class with Emp_name, Emp_id, Address, 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, 0.1% of BP for staff club fund. Generate pay slips for the employees with their gross and net salary. 5. Design a Java interface for ADT Stack. Implement this interface using array and built-in classes. Provide necessary exception handling in both the implementations. 6. Write a Java Program to create an abstract class named Shape that contains two integers and an empty method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one of the classes contains the methods print Area () that prints the area of the given shape and Numberofsides() that prints the number of sides of the given shape. 7. Write a Java program to apply built-in and user defined exceptions. 8. String Manipulation: a. Reversing a set of words and count the frequency of each letter in the string. 24CS202 Java Programming 3 b. Pattern Recognition - Find the number of patterns of form 1[0]1 where [0] represents any number of zeroes (minimum requirement is one 0) there should not be any other character except 0 in the [0] sequence in a given binary string. c. Remove all the occurrences of string S2 in string S1 and print the remaining. d. Find the longest repeating sequence in a string e. Print the number of unique string values that can be formed by rearranging the f. letters in the string S. 9. Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication. 10. Collections: a. Write a program to perform string operations using ArrayList. Write functions for the following i. Append - add at end ii. Insert – add at particular index iii. Search iv. List all string starts with given letter b. Find the frequency of words in a given text. 11. Mini Proje ct (using JDBC) OUTCOMES: Upon completion of the course, the students will be able to: CO1: Solve core Java programming concepts. CO2: Utilize object-oriented programming (OOP) principles. CO3: Demonstrate competency in handling exceptions and implementing multithreading. CO4: Develop expertise in input/output (I/O) operations and file handling. CO5: Apply advanced Java programming concepts with generics and lambda expressions. CO6: Implement database connectivity using JDBC. 24CS202 Java Programming 4 INDEX Ex. No. Name of the Experiment Page No. 1 Electricity Bill Generator 5 2 Kth Smallest Element 9 3 Sub Array with Given Sum 11 4 Matrix Addition 13 5 Matrix Subtraction 15 6 Matrix Multiplication 17 7 Duplicates in Array 22 8 Infinite Sequence 24 9 Currency, Distance and Time Convertor 26 10 Square Root Checker 37 11 Employee Payroll System 39 12 Stack ADT using Java Interface 46 13 Area of Shapes using Abstract Class 50 14 Designing a Robust File Copying Program 53 15 Producer Consumer Problem using Thread 56 16 Word Reverse and Word Count 60 17 Number of Patterns 63 18 Remove all the Occurrences of the Substring in a String 65 19 Longest Repeating Sequence 66 20 Unique String Values 68 21 String Operations using ArrayList 69 22 Frequency of Words 78 23 Mini Project using JDBC Connectivity 80 24CS202 Java Programming 5 Ex.No. 1 Electricity Bill Generator Aim 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: 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 ElectricityBill.java import java.util.Scanner; public class ElectricityBill { private int consumerNo; 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; this.currentMonthReading = currentMonthReading; this.ebConnectionType = ebConnectionType.toLowerCase(); } // Method to calculate the bill amount public double calculateBillAmount() { int unitsConsumed = currentMonthReading - previousMonthReading; double billAmount = 0; if (ebConnectionType.equals("domestic")) { billAmount = calculateDomesticBill(unitsConsumed); } else if (ebConnectionType.equals("commercial")) { billAmount = calculateCommercialBill(unitsConsumed); 24CS202 Java Programming 6 } else { System.out.println("Invalid connection type. Please specify 'Domestic' or 'Commercial'."); } return billAmount; } private double calculateDomesticBill(int units) { if (units <= 100) { return units * 1.00; } else if (units <= 200) { return 100 * 1.00 + (units - 100) * 2.50; } else if (units <= 500) { return 100 * 1.00 + 100 * 2.50 + (units - 200) * 4.00; } else { return 100 * 1.00 + 100 * 2.50 + 300 * 4.00 + (units - 500) * 6.00; } } private double calculateCommercialBill(int units) { if (units <= 100) { return units * 2.00; } else if (units <= 200) { return 100 * 2.00 + (units - 100) * 4.50; } else if (units <= 500) { return 100 * 2.00 + 100 * 4.50 + (units - 200) * 6.00; } else { return (100 * 2.00 + 100 * 4.50 + 300 * 6.00 + (units - 500) * 7.00)-100; } } 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: "); String consumerName = input.nextLine(); System.out.print("Previous Month Reading: "); int previousMonthReading = input.nextInt(); System.out.print("Current Month Reading: "); int currentMonthReading = input.nextInt(); input.nextLine(); System.out.print("Domestic/Commercial: "); String ebConnectionType = input.nextLine(); // Creating ElectricityBill object with user-input data 24CS202 Java Programming 7 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(); } } Test Case - 1 User Output Consumer Number: 12345 Consumer Name: Swathi Previous Month Reading: 200 Current Month Reading: 450 Domestic/Commercial: Domestic 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 24CS202 Java Programming 8 Domestic/Commercial: Commercial Electricity Bill Details: Consumer Number: 2563 Consumer Name: Sangeetha Previous Month Reading: 100 Current Month Reading: 690 EB Connection Type: Commercial Bill Amount: Rs. 2980.0 24CS202 Java Programming 9 Ex.No. 2 Kth Smallest Element Aim Write a Java program that takes an unsorted array of n integers and an integer k from the user and finds the kth smallest element in the array. The array can contain duplicate 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: • The output is the integer which represents the kth 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 package q42211; import java.util.Arrays; import java.util.Scanner; public class KthSmallest { public static void main(String[] args) { Scanner s = new Scanner(System.in); // Input the number of elements in the array int n = s.nextInt(); // Input the elements of the array int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = s.nextInt(); } // Input the position int k = s.nextInt(); // Check if k is a valid position if (k < 1 || k > n) { System.out.println("Invalid input"); return; } // Sort the array Arrays.sort(array); // Find the k-th smallest element System.out.println(array[k-1]); 24CS202 Java Programming 10 s.close();} } Test Case - 1 User Output 5 5 8 9 4 6 2 5 Test Case - 2 User Output 6 14 852 625 742 351 748 8 Invalid input 24CS202 Java Programming 11 Ex.No. 3 Sub Array with Given Sum Aim Write a Java program to find a first continuous subarray in a given unsorted array of n 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. 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 package q42212; import java.util.Scanner; public class SubarrayWithSum { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); // Input the array elements int[] array = new int[n]; // System.out.println("Enter " + n + " space-separated integers:"); for (int i = 0; i < n; i++) { array[i] = scanner.nextInt(); } // Input the target sum // System.out.print("Enter the target sum: "); int targetSum = scanner.nextInt(); // Find the subarray with the given sum boolean subarrayFound = false; for (int start = 0; start < n; start++) { int currentSum = 0; for (int end = start; end < n; end++) { currentSum += array[end]; // Check if currentSum equals the targetSum if (currentSum == targetSum) { System.out.println(start + " " + end); subarrayFound = true; break; 24CS202 Java Programming 12 } } if (subarrayFound) { break; } } if (!subarrayFound) { System.out.println("No subarray"); } scanner.close(); } } Test Case - 1 User Output 5 1 2 3 7 5 12 1 3 Test Case - 2 User Output 10 4 5 96 2 3 5 3 4 8 5 100 No subarray 24CS202 Java Programming 13 Ex.No. 4 Matrix Addition Aim Write a Java program to add two matrices of size n×n. The program should print the 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 package q42213; import java.util.Scanner; public class MatrixAddition { // write the code.. public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the size of the square matrices //System.out.print("Enter the size of the square matrices (n): "); int n = scanner.nextInt(); if (n <= 0) { System.out.println("Invalid matrix size"); return; } // Input the elements of the first matrix int[][] matrix1 = new int[n][n]; //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(); } } // Input the elements of the second matrix int[][] matrix2 = new int[n][n]; // 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 two matrices 24CS202 Java Programming 14 int[][] resultMatrix = new int[n][n]; 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("Resulting Matrix after addition:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(resultMatrix[i][j] + " "); } System.out.println(); } scanner.close(); } } Test Case - 1 User Output 2 1 2 3 4 4 5 5 6 5 7 8 10 Test Case - 2 User Output 3 4 5 4 2 3 4 2 5 6 1 2 3 3 2 1 2 1 3 5 7 7 5 5 5 4 6 9 24CS202 Java Programming 15 Ex.No. 5 Matrix Subtraction Aim Write a Java program to subtract two square matrices of size n×n. The program should 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 package q42214; import java.util.Scanner; public class MatrixSubtraction { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the size of the square matrices // System.out.print("Enter the size of the square matrices (n): "); int n = scanner.nextInt(); if (n <= 0) { System.out.println("Invalid matrix size"); return; } // Input the elements of the first matrix int[][] matrix1 = new int[n][n]; //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(); } } // Input the elements of the second matrix int[][] matrix2 = new int[n][n]; //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 second matrix from the first matrix int[][] resultMatrix = new int[n][n]; 24CS202 Java Programming 16 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("Resulting Matrix after subtraction:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(resultMatrix[i][j] + " "); } System.out.println(); } scanner.close(); } } Test Case - 1 User Output 3 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 -8 -6 -4 -2 0 2 4 6 8 Test Case - 2 User Output 2 5 6 7 8 1 2 3 4 4 4 4 4 24CS202 Java Programming 17 Ex.No. 6 Matrix Multiplication Aim Write a class MultiplicationOfMatrix with a public method multiplication which 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 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 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 Source Code package q11106; public class MultiplicationOfMatrix{ public int[][] multiplication(int[][] matrix1, int[][] matrix2) { 24CS202 Java Programming 18 /*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 if (matrix1[0].length != matrix2.length) { return null; // Return null if multiplication is not possible } // Initialize the result matrix with appropriate dimensions int rows = matrix1.length; int cols = matrix2[0].length; int[][] result = new int[rows][cols]; // Perform matrix multiplication for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result[i][j] = 0; // Initialize each element of result matrix for (int k = 0; k < matrix1[0].length; k++) { result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } return result; // Return the resulting matrix } // Helper method to display a matrix public void displayMatrix(int[][] matrix) { for (int[] row : matrix) { for (int value : row) { System.out.print(value + " "); } System.out.println(); } } public static void main(String[] args) { MultiplicationOfMatrix matrixMultiplication = new MultiplicationOfMatrix(); // Example 1: Multiplication is possible int[][] matrix1 = { {1, 2}, {4, 5}, {7, 8} 24CS202 Java Programming 19 }; int[][] matrix2 = { {1, 2, 3}, {4, 5, 6} }; int[][] result = matrixMultiplication.multiplication(matrix1, matrix2); if (result != null) { System.out.println("Multiplication of the two given matrices is:"); matrixMultiplication.displayMatrix(result); } else { System.out.println("Multiplication of matrices is not possible"); } // Example 2: Multiplication is not possible int[][] matrix3 = { {1, 2}, {3, 4} }; int[][] matrix4 = { {1, 2}, {4, 5}, {2, 3} }; result = matrixMultiplication.multiplication(matrix3, matrix4); if (result != null) { System.out.println("Multiplication of the two given matrices is:"); matrixMultiplication.displayMatrix(result); } else { System.out.println("Multiplication of matrices is not possible"); } } } package q11106; import java.util.Scanner; public class MultiplicationOfMatrixMain { public static void main(String[] args) { Scanner s = new Scanner(System.in); MultiplicationOfMatrix multiplier = new MultiplicationOfMatrix(); System.out.println("Matrix 1:"); int[][] m1 = readMatrix(s); System.out.println("Matrix 2:"); 24CS202 Java Programming 20 int[][] m2 = readMatrix(s); int[][] multi = multiplier.multiplication(m1, m2); if (multi == null) { 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; 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(); } } return m; } } Test Case - 1 User Output Matrix 1: Enter number of rows: 2 Enter number of columns: 3 Enter 3 numbers separated by space Enter row 1: 1 2 3