Java Math: Square Root

To square a number you multiply it by itself. For example if you multiply 4 by itself – 4×4 – you are squaring the number 4. Another way to say this is to raise 4 to the power of 2, or 42. is the same as 4×4 which equals 16.
To get the square root of a number you have to think of the square in reverse:
4 squared is 16, so a square root of 16 is 4
Question, what is the 3 squared?
3 squared, or 32, is 3×3 = 9
Question: What is the square root of 9?
To get the square root of 9 we need to find the number that we can multiply by itself to get 9, so:
1×1 = 1 ✖
2×2 = 4 ✖
3×3 = 9 ✔
So, the square root of 9 is 3.

So, a square root of a number is a value that can be multiplied by itself to give the original number.
As you might expect, Java has a method for this so you don’t need to calculate square roots for your self. This is called the sqrt() method and the general syntax (where x is the number you wish to find the square root of) is:
Math.sqrt(x)
Let’s see how we might use the sqrt() method in Java:
//Output the square root of 9 System.out.println(Math.sqrt(9)); //Output the square root of 16 System.out.println(Math.sqrt(16)); //Output the square root of 25 as an integer System.out.println((int)Math.sqrt(25));
The output should be 82, 83 and 84:
run: 3.0 4.0 5 BUILD SUCCESSFUL (total time: 0 seconds)
Note that sqrt() will return a double value, so if you would like to remove the decimal point you can type cast the result to an integer.
Read more about the Math class here: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html