EXPERIMENT 6
Program 1- Write a program in java if number is less than 10 and greater
than 50 it generate the exception out of range. Else it displays the
square of number.
import [Link].*;
// 1. Define a Custom Exception class
class OutOfRangeException extends Exception {
public OutOfRangeException(String message) {
super(message);
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter a number: ");
int num = [Link]();
// 2. Check the condition (less than 10 OR greater than 50)
if (num < 10 || num > 50) {
// Throw the exception manually
throw new OutOfRangeException("Number is Out of Range!");
} else {
// 3. Display the square if the number is within range
int square = num * num;
[Link]("The square of " + num + " is: " + square);
// 4. Catch and handle the custom exception
catch (OutOfRangeException e) {
[Link]("Caught Exception: " + [Link]());
// Catch input errors (like typing a letter instead of a number)
catch (InputMismatchException e) {
[Link]("Error: Please enter a valid integer.");
finally {
[Link]();
}
Program 2- Write a program to create a user-defined package in Java
and demonstrate how to import and use it in another class.
import [Link].*;
// This class acts like it's in a package
class Calculations {
public void showMessage() {
[Link]("Hello from the 'Calculations' class!");
public int square(int n) {
return n * n;
// This is your entry point
public class Main {
public static void main(String[] args) {
// We create the object directly since it's in the same file
Calculations obj = new Calculations();
[Link]();
[Link]("Square of 5 is: " + [Link](5));