Although calculating a square root in Java isn’t such a common question for software development interviews, sometimes, an interview might ask you something like: “You have an integer x. Create a Java program that would calculate its square root”. To make sure that such a basic question doesn’t catch you off guard, let’s take a look at how to do square root in Java.

Square and Square Root: Reviewing Math Concepts

To make sure you have no confusion when dealing with squares and roots, let’s review the theory of this concept. A square of a number is that number multiplied by itself. If n = 4, then n^2 = 4 4 = 16. The square root of a number is the number that, if multiplied by itself, gives a given value X. For example, you have to find the square root of n = 16, by finding a number that, if elevated to the power of two gives 16, you will solve the problem. In the case of n, the square root of the number 16 is 4 (since 4 * 4 = 16).

How to Do Square Root in Java Using java.lang.Math.sqrt()

The most common way to find a square root of a number in Java is by applying the java.lang.Math.sqrt() method. Here’s the general syntax of the java.lang.Math.sqrt() method:
public static double sqrt(double a)
In the method, a is a value elevated to the power of two you want to get square root for. Onc a developer applies java.lang.Math.sqrt(), the method will return the positive square root of a (if the a is greater than 0). For negative arguments, java.lang.Math.sqrt returns a NaN output.

Special cases of java.lang.Math.sqrt() returns

As mentioned above, in most cases, the method returns positive values. However, there are a few specific cases a developer should be aware of when creating a root-finding program.
  • For arguments that have NaN values or are negative, the method will return a NaN result.
  • For arguments that are positive infinitely, the method will return an infinitely positive result.
  • For arguments consisting of a positive or negative zero, the square root of a will equal a.

Example of using java.lang.Math.sqrt()

package MyPackage;

public class SquareRoot2 {

    public static void main(String args[])
    {
        double a = 100;

        System.out.println(Math.sqrt(a));
        // For positive values, the output is the square root of x

        double b = -81.00;

        System.out.println(Math.sqrt(b));
        // For negative values as input, Output NaN

        double c = 0.0/0;
        // Input NaN, Output NaN

        System.out.println(Math.sqrt(c));

        double d = 1.0/0;
        // For inputs containing  positive infinity, Output positive infinity

        System.out.println(Math.sqrt(d));

        double e = 0.0;
        // Input positive Zero, Output positive zero

        System.out.println(Math.sqrt(e));
    }

}

Finding Square Roots in Java Practice Problem

Now that you know how to create a program that calculates square roots in Java, let’s take a look at how the concept fits into more advanced practice problems. For example, an interviewer might ask you to solve a quadratic equation. Let’s take a look at how to handle such a problem. Problem: solve a quadratic equation where a = 1, b = 5, c = 2. Solution:
import java.util.Scanner;
public class Exercise2 {


  public static void main(String[] Strings) {

        Scanner input = new Scanner(System.in);

            System.out.print("Input a: ");
            double a = input.nextDouble();
            System.out.print("Input b: ");
            double b = input.nextDouble();
            System.out.print("Input c: ");
            double c = input.nextDouble();

            double result = b * b - 4.0 * a * c;

            if (result > 0.0) {
                double r1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
                double r2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
                System.out.println("The roots are " + r1 + " and " + r2);
            } else if (result == 0.0) {
                double r1 = -b / (2.0 * a);
                System.out.println("The square root is " + r1);
            } else {
                System.out.println("There are no real square roots in the equation.");
            }

    }
}
Math.sqrt Method - Square Root in Java - 2

Conclusion

This was a brief rundown on finding a square root of a number in Java. For a software development beginner, it’s a good idea to practice different scenarios (a>0, a<0, a = 0) to get a solid grasp of the concept. Once you understand the ins and outs of the java.lang.Math.sqrt method, start applying the method in complex programs, handling tasks like solving quadratic equations.