In this tutorial, we will write a java program to check if a given number is perfect square.
Java Example to check if a number is perfect square
In this program, we have created a user-defined method checkPerfectSquare()
that takes a number as an argument and returns true if the number is perfect square else it returns false.
In the user defined method we are using two methods of the Math class, sqrt()
method and floor()
method. The Math.sqrt()
method finds the square root of the given number and the floor()
method finds the closest integer of the square root value returned by sqrt()
method. Later we have calculated the difference between these two to check whether the difference is zero or non-zero. For a perfect square number this difference should be zero as the square root of perfect square number is integer itself.
package com.beginnersbook; import java.util.Scanner; class JavaExample { static boolean checkPerfectSquare(double x) { // finding the square root of given number double sq = Math.sqrt(x); /* Math.floor() returns closest integer value, for * example Math.floor of 984.1 is 984, so if the value * of sq is non integer than the below expression would * be non-zero. */ return ((sq - Math.floor(sq)) == 0); } public static void main(String[] args) { System.out.print("Enter any number:"); Scanner scanner = new Scanner(System.in); double num = scanner.nextDouble(); scanner.close(); if (checkPerfectSquare(num)) System.out.print(num+ " is a perfect square number"); else System.out.print(num+ " is not a perfect square number"); } }
Output:
Related Java Examples
1. Java program to break integer into digits
2. Java program to check Armstrong number
3. Java program to check prime number
4. Java program to check leap year
Leave a Reply