Introduce Java How To Find the Square Root of a Number and give examples
In Java, you can find the square root of a number using the Math.sqrt()
method, which is part of the java.lang
package. This method takes a double value as an argument and returns the square root of that value. If the argument is negative, the method will return NaN
(Not a Number).
double result = Math.sqrt(double number);
Here’s a simple example that demonstrates how to find the square root of a positive number:
public class SquareRootExample {
public static void main(String[] args) {
double number = 25.0;
double squareRoot = Math.sqrt(number);
System.out.println("The square root of " + number + " is: " + squareRoot);
}
}
Output:
The square root of 25.0 is: 5.0
If you try to find the square root of a negative number, you will get NaN
:
public class SquareRootNegativeExample {
public static void main(String[] args) {
double number = -16.0;
double squareRoot = Math.sqrt(number);
System.out.println("The square root of " + number + " is: " + squareRoot);
}
}
Output:
The square root of -16.0 is: NaN
You can also find the square root of decimal numbers:
public class SquareRootDecimalExample {
public static void main(String[] args) {
double number = 2.25;
double squareRoot = Math.sqrt(number);
System.out.println("The square root of " + number + " is: " + squareRoot);
}
}
Output:
The square root of 2.25 is: 1.5
You can also take user input to find the square root of a number:
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();
double squareRoot = Math.sqrt(number);
if (Double.isNaN(squareRoot)) {
System.out.println("The square root of " + number + " is: NaN (not a number)");
} else {
System.out.println("The square root of " + number + " is: " + squareRoot);
}
scanner.close();
}
}
Math.sqrt()
to find the square root of a number in Java.NaN
for negative inputs.Scanner
class for dynamic calculations.These examples should give you a good understanding of how to find the square root of a number in Java!