How to Check If a Number Is a Perfect Square in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to determine if a given integer is a perfect square in Java. We will explore the use of the Math.sqrt() method to calculate the square root of a number and then check if the result is a whole number.

Through hands-on coding exercises, you will implement a Java program that takes user input, calculates the square root, and determines if the original number is a perfect square. We will also test the program with various inputs, including negative numbers and numbers that are not perfect squares, to ensure its robustness.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/BasicSyntaxGroup -.-> java/math("Math") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("User Input") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("Exceptions") java/SystemandDataProcessingGroup -.-> java/math_methods("Math Methods") subgraph Lab Skills java/if_else -.-> lab-559958{{"How to Check If a Number Is a Perfect Square in Java"}} java/math -.-> lab-559958{{"How to Check If a Number Is a Perfect Square in Java"}} java/user_input -.-> lab-559958{{"How to Check If a Number Is a Perfect Square in Java"}} java/exceptions -.-> lab-559958{{"How to Check If a Number Is a Perfect Square in Java"}} java/math_methods -.-> lab-559958{{"How to Check If a Number Is a Perfect Square in Java"}} end

Calculate Square Root and Check Integer

In this step, we will write a Java program to calculate the square root of a number and determine if the original number is a perfect square. A perfect square is an integer that is the square of an integer; in other words, it is the product of an integer with itself. For example, 9 is a perfect square because it is 3 * 3.

We will use the Math.sqrt() method provided by Java to calculate the square root. This method returns a double value, which might have decimal places. To check if the original number is a perfect square, we need to see if its square root is a whole number (an integer).

  1. First, let's create a new Java file named SquareRootChecker.java in your ~/project directory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typing SquareRootChecker.java.

  2. Open the SquareRootChecker.java file in the editor and paste the following code:

    import java.util.Scanner;
    
    public class SquareRootChecker {
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("Enter an integer: ");
            int number = scanner.nextInt();
    
            if (number < 0) {
                System.out.println("Cannot calculate the square root of a negative number.");
            } else {
                double squareRoot = Math.sqrt(number);
    
                // Check if the square root is an integer
                if (squareRoot == Math.floor(squareRoot)) {
                    System.out.println(number + " is a perfect square.");
                } else {
                    System.out.println(number + " is not a perfect square.");
                }
            }
    
            scanner.close();
        }
    }

    Let's look at the new parts of this code:

    • import java.util.Scanner;: We import the Scanner class again to read user input.
    • System.out.print("Enter an integer: ");: This prompts the user to enter a number.
    • int number = scanner.nextInt();: This reads the integer entered by the user and stores it in the number variable.
    • if (number < 0): This is an if statement that checks if the entered number is negative. If it is, we print an error message.
    • double squareRoot = Math.sqrt(number);: This line uses the Math.sqrt() method to calculate the square root of the number and stores the result in a double variable called squareRoot.
    • if (squareRoot == Math.floor(squareRoot)): This is the core logic to check if the square root is an integer. Math.floor(squareRoot) returns the largest integer less than or equal to squareRoot. If squareRoot is a whole number, squareRoot and Math.floor(squareRoot) will be equal.
    • System.out.println(...): These lines print the result based on whether the number is a perfect square or not.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Now, compile the program in the Terminal:

    javac SquareRootChecker.java

    If there are no errors, a SquareRootChecker.class file will be created.

  5. Run the compiled program:

    java SquareRootChecker
  6. The program will prompt you to enter an integer. Enter a number like 9 and press Enter. You should see output indicating that 9 is a perfect square. Run the program again and enter a number like 10. You should see output indicating that 10 is not a perfect square.

    Enter an integer: 9
    9 is a perfect square.
    Enter an integer: 10
    10 is not a perfect square.

You have successfully written a Java program that calculates the square root and checks if a number is a perfect square!

Use Math.sqrt() for Perfect Square

In this step, we will focus on understanding how Math.sqrt() works and how we used it in the previous step to determine if a number is a perfect square.

The Math.sqrt() method is part of Java's built-in Math class, which provides many mathematical functions. Math.sqrt(double a) takes a double value a as input and returns its square root as a double.

For example:

  • Math.sqrt(9.0) returns 3.0
  • Math.sqrt(10.0) returns approximately 3.1622776601683795
  • Math.sqrt(0.0) returns 0.0
  • Math.sqrt(-9.0) returns NaN (Not a Number)

In our SquareRootChecker.java program, we read an integer from the user, but Math.sqrt() expects a double. Java automatically converts the int number to a double when we pass it to Math.sqrt().

The key to checking for a perfect square lies in comparing the calculated square root (double squareRoot) with its floor value (Math.floor(squareRoot)).

  • If squareRoot is a whole number (like 3.0), then Math.floor(squareRoot) will also be 3.0, and the condition squareRoot == Math.floor(squareRoot) will be true.
  • If squareRoot has a decimal part (like 3.16...), then Math.floor(squareRoot) will be 3.0, and the condition squareRoot == Math.floor(squareRoot) will be false.

This simple comparison allows us to effectively check if the original integer was a perfect square.

Let's re-run the program a couple of times to observe the output for different inputs and solidify your understanding.

  1. Make sure you are in the ~/project directory in the Terminal.

  2. Run the compiled program again:

    java SquareRootChecker
  3. Enter the number 25 and press Enter. Observe the output.

    Enter an integer: 25
    25 is a perfect square.
  4. Run the program again:

    java SquareRootChecker
  5. Enter the number 15 and press Enter. Observe the output.

    Enter an integer: 15
    15 is not a perfect square.

By running the program with different inputs, you can see how the Math.sqrt() and Math.floor() comparison correctly identifies perfect squares.

Test Negative and Non-Integer Inputs

In this step, we will test our SquareRootChecker.java program with negative numbers and consider what happens if the user enters something that is not an integer.

In the code we wrote, we included a check for negative numbers:

if (number < 0) {
    System.out.println("Cannot calculate the square root of a negative number.");
}

This if statement handles the case where the user enters a negative integer. Let's test this part of the code.

  1. Make sure you are in the ~/project directory in the Terminal.

  2. Run the compiled program:

    java SquareRootChecker
  3. When prompted, enter a negative number, for example, -4, and press Enter.

    Enter an integer: -4
    Cannot calculate the square root of a negative number.

    As expected, the program correctly identifies that it cannot calculate the square root of a negative number and prints the appropriate message.

Now, let's consider what happens if the user enters input that is not an integer, such as text or a decimal number. Our program uses scanner.nextInt() to read the input. This method is designed to read only integer values. If the user enters something that cannot be parsed as an integer, a InputMismatchException will occur, and the program will crash.

Handling such errors gracefully is an important part of writing robust programs. For this introductory lab, we won't implement full error handling for non-integer input, but it's important to be aware that this can happen. In future labs, you will learn techniques like try-catch blocks to handle exceptions and make your programs more resilient to unexpected user input.

For now, let's just observe what happens when you enter non-integer input.

  1. Run the compiled program again:

    java SquareRootChecker
  2. When prompted, enter some text, for example, hello, and press Enter.

    Enter an integer: hello
    Exception in thread "main" java.util.InputMismatchException
        at java.base/java.util.Scanner.throwFor(Scanner.java:939)
        at java.base/java.util.Scanner.next(Scanner.java:1594)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
        at SquareRootChecker.main(SquareRootChecker.java:9)

    You will see an error message indicating an InputMismatchException. This is because scanner.nextInt() expected an integer but received "hello".

This step highlights the importance of considering different types of user input and how your program will handle them. While our current program is simple, understanding these potential issues is crucial for developing more complex applications.

Summary

In this lab, we learned how to determine if a given integer is a perfect square in Java. We utilized the Math.sqrt() method to calculate the square root of the input number.

The core logic involved checking if the calculated square root is a whole number by comparing it to its floor value using Math.floor(). We also handled the case of negative input numbers, as their square roots are not real numbers. This process allowed us to effectively identify perfect squares.