Java Program to Check if a Given Number is Perfect Square

1. Introduction

A perfect square is an integer that is the square of an integer. For example, 16 is a perfect square because it is 4^2. Checking if a given number is a perfect square is a common problem in computer science and mathematics. This blog post will use a straightforward mathematical approach to demonstrate a Java program that checks if a given number is a perfect square.

2. Program Steps

1. Read an integer number from the user.

2. Calculate the square root of the given number.

3. Check if the square of the square root (when rounded to the nearest integer) equals the original number.

4. Display whether the number is a perfect square or not.

5. Ensure proper cleanup of resources, if any are used.

3. Code Program

import java.util.Scanner;

public class CheckPerfectSquare {
    public static void main(String[] args) {
        // Scanner object for capturing user input
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter an integer:");
        int number = scanner.nextInt();

        // Calculating the square root of the given number
        int sqrt = (int) Math.sqrt(number);

        // Checking if the number is a perfect square
        if (sqrt * sqrt == number) {
            System.out.println(number + " is a perfect square.");
        } else {
            System.out.println(number + " is not a perfect square.");
        }

        // Closing the scanner
        scanner.close();
    }
}

Output:

Enter an integer:
25
25 is a perfect square.

Explanation:

1. The program starts by importing the Scanner class for reading user input. A Scanner object is created to read an integer number entered by the user.

2. It calculates the square root of the given number using the Math.sqrt() method. The result is cast to an integer (int) to remove any decimal part, effectively rounding the square root to the nearest integer.

3. The program then checks if the square of this integer square root equals the original number. This is done by multiplying the square root (sqrt) by itself and comparing the result with the original number. If they are equal, the original number is a perfect square.

4. Depending on the result of this comparison, the program prints a message indicating whether the entered number is a perfect square.

5. Finally, the Scanner object is closed to prevent resource leaks, adhering to best practices in handling user input.

Comments