Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Perfect Square Check in Java

Search for a perfect square in Java by trying integers and comparing (long) i * i with the input. Zero matches, negative inputs fail, and break stops a match.

BeginnerJava Loop ProgramsExample 23 of 25
perfect-square-check.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 int n = sc.nextInt();
8
9 boolean isPerfect = false;
10 for (int i = 0; (long) i * i <= n; i++) {
11 if ((long) i * i == n) {
12 isPerfect = true;
13 break;
14 }
15 }
16
17 if (isPerfect) {
18 System.out.println(n + " is a Perfect Square");
19 } else {
20 System.out.println(n + " is not a Perfect Square");
21 }
22 sc.close();
23 }
24}

Sample Output

Enter a number: 49
49 is a Perfect Square

The search reaches i=7, where the square equals 49. The flag changes to true and the loop ends.

In this one

  • Search for an exact square
  • Use a true-or-false flag
  • Widen before multiplication

How it works

  1. 1

    Read n and start isPerfect as false.

  2. 2

    Try i starting at zero while its long square is <= n.

  3. 3

    Set the flag and break on equality.

  4. 4

    Print the result from the flag.

Edge cases

Zero square

Enter 0

The first trial is 0 * 0, so zero is accepted.

Negative value

Enter -4

No non-negative square is <= -4, and the result is not a perfect square.

What's going on

Check whether an integer is the square of another integer. For example, 49 is a perfect square because 7 * 7 equals 49. This loop-based approach is useful for tracing a search without relying on a square-root function.

Scanner is the keyboard reader. A boolean is a value that is true or false; isPerfect starts false. The loop tries i from zero upwards and compares (long) i * i with n. Converting before multiplication gives the product enough room. On an exact match, the flag becomes true and break ends the loop.

Starting at zero correctly accepts zero as 0 squared. Negative inputs cannot match any squared integer, so they are rejected naturally. Using i * i in int arithmetic can exceed its size near the largest int input; widening one operand first avoids that problem. The final if prints a message based on the flag.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which integer squares to 49?

Pick an answer to check it.

Question 2

Is zero a perfect square?

Pick an answer to check it.

Questions people ask

Why begin at zero instead of one?

Zero is a perfect square too, because 0 * 0 is 0.

Why is long used in the comparison?

It prevents the multiplication from exceeding the int range before the comparison.

Why break after finding a match?

There is no need to search further once an integer square equals n.