How to calculate the square root of a number in Java
Java provides a very simplified and easy way to enable users to input values through the keyboard using java.util.Scanner and for mathematical operations java.lang.Math class will be used. To use this object, an import of the java.util.Scanner is required.
import java.lang.Math;
Next, we have created a public class with the name of ‘SqurareRoot’ where all the calculations will be performed:
………
}
We also need to create a scanner object that is used to scan the input provided by the user:
Now if you want to print anything on the screen then you can do that by typing:
If you want to take input from the user then you can do that by typing:
In the above command, we have used an integer data type that will store the input in a variable x. Next, we need to write a code that can be used to calculate the square root, and for that, we have used an if-else conditional statement. The above-mentioned condition shows that if a variable has a value less than zero then the square root would not be a real number. So it is recommended to provide a positive number for this example:
The above-mentioned condition shows that if a variable has a value less than zero then the square root would not be a real number. So it is recommended to provide a positive number for this example:
The else condition shows that if a number is greater than zero then calculate the square root by using a function:
Here we have used a data type double because a square root can be an infraction as well and the result will be saved in a new variable with a name of ‘r’. So, the complete if-else conditional statement is mentioned below.
Now we are going to show you the complete code that we have written to calculate the square root:
Complete Code
import java.lang.Math;
public class SquareRoot {
public static void main(String[] args)
{
//Define a Scanner object for data input.
Scanner in=new Scanner(System.in);
System.out.println("Java Square Root. Example 1");
System.out.println("Please enter an integer (whole number) ");
int x=in.nextInt();
//Display error message if x is a negative integer
if(x<0)
{
System.out.println("Error! Square root of a negative number is not a real number");
}
else
{
double r=Math.sqrt(x);
System.out.println("Square root of " + x +" is "+ r);
}
}
}
Note: To execute a java code you need to first install the java development kit (JDK) by typing
How to compile a java code in Linux OS
You can create a java file by using any text editor in the Linux operating system for example.
After writing and saving the code, you need to compile it by typing:
And after compiling you can execute the code by using:
Conclusion
In this article, we have calculated the square root of any number using the Java programming language. The Math.sqrt(x) that is used for this purpose and we have calculated the square root of a positive number as a negative number will not have a real value.