Java Program to Calculate Square Root – With Examples and Best Practices
Introduction
Calculating the square root is a common requirement in mathematical and scientific applications. Java provides a simple yet powerful way to calculate square roots using built-in methods from the Math class.
By the end of this guide, you’ll be able to:
- Calculate square roots using
Math.sqrt() - Handle invalid input like negative numbers
- Build user-interactive and reusable Java programs
What is Square Root?
The square root of a number x is a value y such that:
y × y = x
In Java, this is done using the built-in Math.sqrt() method.
Java Program – Hardcoded Input
public class SquareRootExample {
public static void main(String[] args) {
double number = 25;
double result = Math.sqrt(number);
System.out.println("Square root of " + number + " is: " + result);
}
}
Explanation:
Math.sqrt(25)returns5.0.doubleis used for decimal precision.
Java Program – User Input with Scanner
import java.util.Scanner;
public class SquareRootUserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
if (number < 0) {
System.out.println("Error: Cannot calculate square root of a negative number.");
} else {
double result = Math.sqrt(number);
System.out.println("Square root of " + number + " is: " + result);
}
scanner.close();
}
}
Explanation:
- Takes user input.
- Checks for negative values before computing square root.
Java Method – Reusable Function
public class SquareRootUtil {
public static double computeSquareRoot(double number) {
if (number < 0) {
throw new IllegalArgumentException("Negative input is not allowed");
}
return Math.sqrt(number);
}
public static void main(String[] args) {
double value = 16;
System.out.println("Square root: " + computeSquareRoot(value));
}
}
Best for modular code and reusability in larger projects.
Edge Case Warning
double result = Math.sqrt(-9); // NaN
System.out.println(result); // Output: NaN
Math.sqrt() returns NaN (Not-a-Number) for negative inputs, not an exception. Handle it manually for cleaner logic.
Sample Output
Enter a number: 36
Square root of 36.0 is: 6.0
Enter a number: -5
Error: Cannot calculate square root of a negative number.
Summary
In this tutorial, you’ve learned:
- How to calculate the square root in Java using
Math.sqrt() - Handle user input and negative numbers
- Create reusable functions for cleaner code
This logic is widely used in geometry, physics, finance, and UI scaling.
FAQ – Square Root in Java
Can I calculate square root of negative numbers?
No, not directly. Java returns NaN for negative inputs. Use Math.sqrt() with a manual check.
Which data type is best for square root?
Use double for precision. Avoid int, as square roots often result in fractions.
Is there a way to round the square root result?
Yes:
double result = Math.sqrt(50);
System.out.println(Math.round(result)); // Rounds to nearest whole number
Share Now :
