0% found this document useful (0 votes)
2 views3 pages

Java Exp6

The document contains two Java programs. The first program defines a custom exception for numbers out of range (less than 10 or greater than 50) and displays the square of valid numbers. The second program demonstrates creating and using a user-defined package with a class that provides a greeting and a method to calculate the square of a number.

Uploaded by

aagnikali
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)
2 views3 pages

Java Exp6

The document contains two Java programs. The first program defines a custom exception for numbers out of range (less than 10 or greater than 50) and displays the square of valid numbers. The second program demonstrates creating and using a user-defined package with a class that provides a greeting and a method to calculate the square of a number.

Uploaded by

aagnikali
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

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

You might also like