Finding Square Roots in Java

Today, we are going to cover how to find a square root in Java using the Math.sqrt method. Math.sqrt is a pre-defined Java method useful for programs such as this.
  1. import java.util.Scanner; //scanner class is needed for user input
  2.  
  3. public class squareroot
  4. {
  5.  
  6. public static void main(String[] args)
  7. {
  8. Scanner input = new Scanner(System.in); //creates new scanner for user input
  9.  
  10. double n; //declares n, a variable that the user will give a value to
  11.  
  12. System.out.print("Enter a number to calculate its square root: ");
  13.  
  14. n = input.nextDouble(); //assigns user input value to n
  15.  
  16. root(n); //runs root method and passes the value of n to it
  17.  
  18. System.out.println(); //linebreak for neatness
  19.  
  20. }
  21.  
  22. public static void root(double x) //root method accepts value passed to it as "x"
  23. {
  24.  
  25. double y = Math.sqrt(x); //uses the Math.sqrt method in Java to calculate the square root and assigns it to y
  26.  
  27. System.out.printf("The square root of " + x + " is approximately %.4f", y); //types out the result, and formats the square root to four decimal places
  28.  
  29. }
  30.  
  31. }
There are a couple of things that should be mentioned here. Two methods aren't really necessary for a program with as few lines as this one, but using multiple methods is a good habit to get into for organizational skills. As you can see, Math.sqrt is already a usable method, with no need to import it. A useful method used for formatting is printf. You can use it limit the number of decimal places shown on the result printed to the screen. In case you want more or less decimal places, just change the 4 in "%.4f" to something else.

Add new comment