1. Introduction
A perfect square is a number that can be expressed as the product of an integer with itself. For example, 1, 4, 9, and 16 are perfect squares, but 8 and 14 are not. In this blog post, we will create a Java program that checks whether a given number is a perfect square.
2. Program Steps
1. Define a class named PerfectSquare.
2. Inside the main method, initialize a variable num with the number to be checked.
3. Calculate the square root of num and store it in a variable sqrt.
4. Check whether the square of sqrt is equal to num.
5. If it is, print that num is a perfect square; otherwise, print that it is not.
3. Code Program
public class PerfectSquare { // Step 1: Define a class named PerfectSquare
public static void main(String[] args) { // Main method
int num = 25; // Step 2: Initialize variable num with the number to be checked
// Step 3: Calculate the square root of num and store it in variable sqrt
int sqrt = (int) Math.sqrt(num);
// Step 4: Check whether the square of sqrt is equal to num
if (sqrt * sqrt == num) {
// Step 5: Print that num is a perfect square
System.out.println(num + " is a perfect square.");
} else {
// Print that num is not a perfect square
System.out.println(num + " is not a perfect square.");
}
}
}
Output:
25 is a perfect square.
4. Step By Step Explanation
– Step 1: A class named PerfectSquare is defined.
– Step 2: Inside the main method, a variable num is initialized with the number to be checked.
– Step 3: The square root of num is calculated using Math.sqrt() method and the result is stored in a variable sqrt. The value is cast to int to compare it with num later.
– Step 4: The program checks whether the square of sqrt is equal to num.
– Step 5: Depending on the condition in Step 4, the program prints whether num is a perfect square or not.