CSW2 Assignment3 Soln
CSW2 Assignment3 Soln
package q1;
public class NullPointException {
public static void main(String[] args) {
String str1 = "Anindya2004";
String str2 = "Anindya";
String str3 = null;
try {
extractAndShowNumbers(str1);
extractAndShowNumbers(str2);
extractAndShowNumbers(str3);
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
public static void extractAndShowNumbers(String input) {
if (input == null || input.isEmpty()) {
throw new NullPointerException("Input string cannot be null or
empty.");
}
StringBuilder numChar = new StringBuilder();
for (char ch : input.toCharArray()) {
if (ch >= '0' && ch <= '9') {
numChar.append(ch);
}
}
if (numChar.length() > 0) {
System.out.println("Numeric characters extracted: " +
numChar.toString());
} else {
System.out.println("No numeric characters found in the input
string.");
}
}
}
OUTPUT:
Prepared by MAJI, A.
2. Implement a custom exception class named CustomNullPointerException that
replicates the behavior of the standard NullPointerException. However, instead of relying
on default error messages or null references, this custom exception should accept a String
message as a constructor argument. Your task is to create this custom exception class and
demonstrate its usage in a Java program.
package q2;
class CustomNullPointerException extends Exception {
public CustomNullPointerException(String msg) {
super(msg);
}
}
public class CustomNullPointException {
public static void main(String[] args) {
try {
String str = null;
if (str == null) {
throw new CustomNullPointerException("Custom
NullPointerException: The value is null!");
}
} catch (CustomNullPointerException e) {
System.out.println(e.getMessage());
}
}
}
OUTPUT:
Prepared by MAJI, A.
3. Create a method that accepts a string input and converts it into an integer. Use a try-
catch block to handle NumberFormatException, and if an exception occurs, prompt the
user to enter a valid numeric value.
package q3;
import java.util.Scanner;
public class StringToIntegerConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter a numeric value: ");
int number = Integer.parseInt(sc.nextLine());
System.out.println("You entered the number: " + number);
break;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again.");
}
}
sc.close();
}
}
OUTPUT:
Prepared by MAJI, A.
4. Write a Java program to find the square root of an integer number. Demonstrate the
use of a try-catch block to handle ArithmeticException.
package q4;
import java.util.Scanner;
public class SqRtCalc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer:");
try {
int num = sc.nextInt();
if (num < 0) {
throw new ArithmeticException("Cannot calculate the square root
of a negative number.");
}
double sqRt = Math.sqrt(num);
System.out.println("The square root of " + num + " is: " + sqRt);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
sc.close();
}
}
}
OUTPUT:
Prepared by MAJI, A.
5. Demonstrate the use of a nested try-catch block. Write a Java program where the outer
try-catch block handles a NumberFormatException, while the inner try-catch block
handles an ArithmeticException.
package q5;
import java.util.Scanner;
public class NestedTryCatch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter two numbers: ");
String input1 = sc.next();
String input2 = sc.next();
try {
int num1 = Integer.parseInt(input1);
int num2 = Integer.parseInt(input2);
try {
int result = num1 / num2;
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format. Please enter valid
integers.");
}
sc.close();
}
}
OUTPUT:
Prepared by MAJI, A.
6. Implement a Java program that performs complex manipulations on an array of
integers, including operations such as sorting, searching, and accessing elements at
various indices. Introduce scenarios where accessing elements beyond the array bounds
leads to an ArrayIndexOutOfBoundsException. Handle these exceptions gracefully to
ensure the program continues execution without crashing.
package q6;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayManipulation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = {15, 8, 25, 5, 18, 30, 10};
System.out.println("Original Array: " + Arrays.toString(array));
Arrays.sort(array);
System.out.println("Sorted Array: " + Arrays.toString(array));
System.out.print("Enter an element to search: ");
int searchElement = sc.nextInt();
int searchIndex = Arrays.binarySearch(array, searchElement);
if (searchIndex >= 0) {
System.out.println("Element " + searchElement + " found at index: "
+ searchIndex);
} else {
System.out.println("Element " + searchElement + " not found in the
array.");
}
System.out.print("Enter an index to access: ");
int index = sc.nextInt();
try {
System.out.println("Element at index " + index + ": " +
array[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Attempted to access an index out of
bounds.");
}
System.out.println("Program execution completed!");
sc.close();
}
}
OUTPUT:
Prepared by MAJI, A.
7. Design a Java program to perform matrix operations such as addition, multiplication,
and transpose. Introduce scenarios where accessing elements beyond the matrix bounds
results in an ArrayIndexOutOfBoundsException. Handle these exceptions effectively and
provide meaningful error messages that clearly indicate the nature of the exception.
package q7;
public class MatrixOperations {
public static void main(String[] args) {
int[][] matrixA = {
{1, 2},
{3, 4}
};
int[][] matrixB = {
{5, 6},
{7, 8}
};
System.out.println("Matrix A:");
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[0].length; j++) {
System.out.print(matrixA[i][j] + " ");
}
System.out.println();
}
System.out.println("Matrix B:");
for (int i = 0; i < matrixB.length; i++) {
for (int j = 0; j < matrixB[0].length; j++) {
System.out.print(matrixB[i][j] + " ");
}
System.out.println();
}
System.out.println("Matrix Addition:");
int[][] additionResult = new int[matrixA.length][matrixA[0].length];
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[0].length; j++) {
additionResult[i][j] = matrixA[i][j] + matrixB[i][j];
System.out.print(additionResult[i][j] + " ");
}
System.out.println();
}
System.out.println("Matrix Multiplication:");
int[][] multiplicationResult = new
int[matrixA.length][matrixB[0].length];
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixB[0].length; j++) {
for (int k = 0; k < matrixA[0].length; k++) {
multiplicationResult[i][j] += matrixA[i][k] * matrixB[k][j];
}
System.out.print(multiplicationResult[i][j] + " ");
}
System.out.println();
}
System.out.println("Transpose of Matrix A:");
int[][] transposeA = new int[matrixA[0].length][matrixA.length];
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[0].length; j++) {
transposeA[j][i] = matrixA[i][j];
}
}
for (int i = 0; i < transposeA.length; i++) {
for (int j = 0; j < transposeA[0].length; j++) {
System.out.print(transposeA[i][j] + " ");
}
System.out.println();
Prepared by MAJI, A.
}
try {
System.out.println("Accessing an out-of-bounds element to
demonstrate exception handling:");
System.out.println(matrixA[2][2]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Attempted to access elements beyond
matrix bounds. ");
}
}
}
OUTPUT:
Matrix A:
1 2
3 4
Matrix B:
5 6
7 8
Matrix Addition:
6 8
10 12
Matrix Multiplication:
19 22
43 50
Transpose of Matrix A:
1 3
2 4
Accessing an out-of-bounds element to demonstrate exception handling:
Error: Attempted to access elements beyond matrix bounds.
Prepared by MAJI, A.
8. Create a custom-checked exception class named CustomCheckedException. Use this
exception in your program to handle a specific error condition and demonstrate its usage
with a try-catch block.
package q8;
class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
public class CustomException {
public static void main(String[] args) {
try {
checkValue(15);
} catch (CustomCheckedException e) {
System.out.println("Caught CustomCheckedException: " +
e.getMessage());
}
}
public static void checkValue(int value) throws CustomCheckedException {
if (value > 10) {
throw new CustomCheckedException("The value " + value + " exceeds
the allowed limit of 10.");
}
System.out.println("Value " + value + " is within the allowed limit.");
}
}
OUTPUT:
Prepared by MAJI, A.
9. Implement a method that reads an integer from the user and handles
InputMismatchException using a try-catch block.
package q9;
import java.util.InputMismatchException;
import java.util.Scanner;
public class InputMismatch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter an integer: ");
int num = sc.nextInt();
System.out.println("You entered: " + num);
break;
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a valid
integer.");
sc.next();
}
}
sc.close();
}
}
OUTPUT:
Prepared by MAJI, A.
10. Implement a Java program that reads a file path from the command-line argument
and attempts to read its contents. If the file path is null or points to a non-existent file,
throw a custom FileNotFoundException. If the file exists but cannot be read due to
permission issues, throw a custom FileReadPermissionException. Your task is to create
these custom exception classes and handle them appropriately in your program.
package q10;
import java.io.File;
import java.io.FileNotFoundException;
class FileReadPermissionException extends Exception {
public FileReadPermissionException(String message) {
super(message);
}
}
public class FileHandler {
public static void main(String[] args) {
try {
if (args.length == 0 || args[0] == null)
throw new FileNotFoundException("File path is null. Please
provide a valid file path.");
File file = new File(args[0]);
if (!file.exists())
throw new FileNotFoundException("File not found: " + args[0]);
if (!file.canRead())
throw new FileReadPermissionException("Permission denied: Cannot
read the file " + args[0]);
System.out.println("File exists and can be read: " + args[0]);
} catch (FileNotFoundException | FileReadPermissionException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
OUTPUT:
Prepared by MAJI, A.
11. Write a program that reads data from a file and performs some processing. Handle
checked IOException by using try-catch block to catch and handle the exception.
package q11;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileProcessor {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new
FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Processed: " + line.toUpperCase());
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
OUTPUT:
Prepared by MAJI, A.