Perfect Square in Java with Explanation, Definition, Examples, and Program

A Perfect Square is a number that can be expressed as the square of an integer. This guide explains the concept with examples and provides a simple Java program to check if a number is a perfect square.

Perfect Square in Java

A Perfect Square is a number that can be written as the square of an integer. In simple terms, a number N is a Perfect Square if:

N = a², for some integer a

For example, 16 = 4² and 49 = 7², so both are perfect squares.


Examples

Example 1: 25

Example 2: 30


Java Program to Check Perfect Square


public class PerfectSquare {

    // Function to check if a number is a perfect square
    static boolean isPerfectSquare(int num) {
        if (num < 0) return false; // negative numbers cannot be perfect squares

        int root = (int) Math.sqrt(num);
        return root * root == num;
    }

    public static void main(String[] args) {
        int num = 49;

        if (isPerfectSquare(num)) {
            System.out.println(num + " is a Perfect Square");
        } else {
            System.out.println(num + " is NOT a Perfect Square");
        }
    }
}

How the Program Works

We calculate the square root of the number using Math.sqrt() and cast it to an integer. If squaring that integer gives us back the original number, then it is a perfect square.


Practice Challenges

  1. Print all perfect squares between 1 and 500.
  2. Write a program to check if a number is a perfect square without using Math.sqrt().
  3. Given an array, print only those elements which are perfect squares.