Checking Whether a Number is a Perfect Square Number in Java

A number is known as a square number or perfect square if the number is a square of another number. That is an number n is square if it can be expressed as n = a * a where a is an integer. Some examples of perfect numbers (square numbers) are ,

9 = 3 * 3,   25 = 5 * 5, 100 = 10 * 10

An interesting property of square number is that it can only end with 0, 1, 4, 6, 9 or 25.

Java Program to Find Whether a Number is a Perfect Square Number

The following Java program checks whether a given number is a perfect square number or not. We take the square root of the passed in number and then convert it into an integer. Then we take a square of the value to see whether it is same as the number given. If they are same, we got a perfect square number!

// Finding whether a number is a perfect square number in Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PerfectSquareNumber {
    
    public static void main(String[] args) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please enter an integer : ");
        int number = Integer.parseInt(reader.readLine());
        
        int sqrt = (int) Math.sqrt(number);
        if(sqrt*sqrt == number) {
            System.out.println(number+" is a perfect square number!");
        }else {
            System.out.println(number+" is NOT a perfect square number!");
        }
        
    }
}

Leave a Reply