1. Create a package named mathop.
Define class MathsOperations with static methods to find
the maximum and minimum of n numbers. Create another package statop. Define class
StatsOperations with methods to find the average and median of n numbers. Import these
packages to use the above methods to perform above operations on n numbers.
import [Link];
public class DivisionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter numerator: ");
int numerator = [Link]();
[Link]("Enter denominator: ");
int denominator = [Link]();
try {
int result = numerator / denominator;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
[Link]();
}
}
Output:-
2. Define an array of size n and set some values to it. Show an
ArrayIndexOutOfBoundException when trying to access the index that is more
than size of the array.
public class ArrayExample {
public static void main(String[] args) {
// Define an array of size 5
int[] numbers = new int[5];
// Set values to the array
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
try {
// Trying to access index 5 (which is out of bounds)
[Link]("Accessing element at index 5: " + numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Index is out of array bounds!");
}
}
}
Output:-
3. Write a program to show the use of NullPointerException.
public class NullPointerExample {
public static void main(String[] args) {
String str = null; // str is not pointing to any object
try {
// Attempting to call a method on a null reference
[Link]("Length of the string: " + [Link]());
} catch (NullPointerException e) {
[Link]("Error: Cannot call methods on a null object (NullPointerException).");
}
}
}
Output:-