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
- Square root of 25 = 5
- 5 × 5 = 25
- 25 is a Perfect Square.
Example 2: 30
- Square root of 30 ≈ 5.477...
- Not an integer
- 30 is NOT a Perfect Square.
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
- Print all perfect squares between 1 and 500.
- Write a program to check if a number is a perfect square without using
Math.sqrt(). - Given an array, print only those elements which are perfect squares.