public class PerfectSquareChecker {
public static boolean isPerfectSquare(int num) {
int sqrt = (int) Math.sqrt(num);
return sqrt * sqrt == num;
}
public static void main(String[] args) {
int num = 16;
if (isPerfectSquare(num)) {
System.out.println(num + " is a perfect square");
} else {
System.out.println(num + " is not a perfect square");
}
}
}
In this program, we define a method isPerfectSquare that takes an integer
num as input and returns a boolean value indicating whether or not
num is a perfect square.
To check ifnum is a perfect square, we calculate the square root of
num using the Math.sqrt method, cast it to an integer, and assign it to the variable
sqrt. If sqrt * sqrt is equal to num, then
num is a perfect square and we return true. Otherwise, we return
false.
In the main method, we test the isPerfectSquare method with the number 16 and print out a message indicating whether or not 16 is a perfect square. You can replace 16 with any other number to test the program with a different input.
The following Java program checks whether the given number is a perfect square or not:
public class CheckPerfectSquare {
public static void main(String[] args) {
int num = 25;
if (isPerfectSquare(num))
{
System.out.println(num + " is a perfect square.");
}
else
{
System.out.println(num + " is not a perfect square.");
}
}
public static boolean isPerfectSquare(int num)
{
int sqrt = (int) Math.sqrt(num);
return sqrt * sqrt == num;
}
}
Output = Enter a number: 25
25 is a perfect square.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In this program, we define a method isPerfectSquare that takes an integer num as input and returns a boolean value indicating whether or not num is a perfect square.
To check if num is a perfect square, we calculate the square root of num using the Math.sqrt method, cast it to an integer, and assign it to the variable sqrt. If sqrt * sqrt is equal to num, then num is a perfect square and we return true. Otherwise, we return false.
In the main method, we test the isPerfectSquare method with the number 16 and print out a message indicating whether or not 16 is a perfect square. You can replace 16 with any other number to test the program with a different input.
The following Java program checks whether the given number is a perfect square or not: