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.
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).
First, let's create a new Java file named
SquareRootChecker.javain your~/projectdirectory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typingSquareRootChecker.java.Open the
SquareRootChecker.javafile 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 theScannerclass 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 thenumbervariable.if (number < 0): This is anifstatement that checks if the entered number is negative. If it is, we print an error message.double squareRoot = Math.sqrt(number);: This line uses theMath.sqrt()method to calculate the square root of thenumberand stores the result in adoublevariable calledsquareRoot.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 tosquareRoot. IfsquareRootis a whole number,squareRootandMath.floor(squareRoot)will be equal.System.out.println(...): These lines print the result based on whether the number is a perfect square or not.
Save the file (Ctrl+S or Cmd+S).
Now, compile the program in the Terminal:
javac SquareRootChecker.javaIf there are no errors, a
SquareRootChecker.classfile will be created.Run the compiled program:
java SquareRootCheckerThe program will prompt you to enter an integer. Enter a number like
9and press Enter. You should see output indicating that 9 is a perfect square. Run the program again and enter a number like10. 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)returns3.0Math.sqrt(10.0)returns approximately3.1622776601683795Math.sqrt(0.0)returns0.0Math.sqrt(-9.0)returnsNaN(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
squareRootis a whole number (like 3.0), thenMath.floor(squareRoot)will also be 3.0, and the conditionsquareRoot == Math.floor(squareRoot)will be true. - If
squareRoothas a decimal part (like 3.16...), thenMath.floor(squareRoot)will be 3.0, and the conditionsquareRoot == 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.
Make sure you are in the
~/projectdirectory in the Terminal.Run the compiled program again:
java SquareRootCheckerEnter the number
25and press Enter. Observe the output.Enter an integer: 25 25 is a perfect square.Run the program again:
java SquareRootCheckerEnter the number
15and 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.
Make sure you are in the
~/projectdirectory in the Terminal.Run the compiled program:
java SquareRootCheckerWhen 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.
Run the compiled program again:
java SquareRootCheckerWhen 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 becausescanner.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.



