Java Program to Find all Roots of a Quadratic Equation

In this java program, we will learn about how to find all the roots of a quadratic equation.

In algebra, a quadratic equation is a second order equation having a single variable. Any quadratic equation can be represented as ax2 + bx + c = 0, where a, b and c are constants( a can't be 0) and x is unknown variable.

For Example:
4x2 + 2x + 5 = 0 is a quadratic equation where a, b and c are 4, 2 and 5 respectively.

To understand this java program, you should have understanding of the following Java programming concepts:

To calculate the roots of quadratic equation we can use below formula. There are two solutions of a quadratic equation.
x = (-2a + sqrt(D))/2
x = (-2a - sqrt(D))/2

where, D is Discriminant which is calculated as (b2 - 4ac), it differentiate the nature of the roots of quadratic equation.

Discriminant(D) value Description
D < 0 We will get two complex roots.
D = 0 We will get two equal roots.
D > 0 We will get two real numbers.


Java Program to Find Roots of a Quadratic Equation

public class QuadraticEqRoots {
  public static void main(String[] args) {
    double a, b, c, determinant, root1, root2, real, imag;
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter value of a, b and c");

    a = scanner.nextDouble();
    b = scanner.nextDouble();
    c = scanner.nextDouble();

    // Calculate determinant
    determinant = b*b - 4*a*c;

    if(determinant >= 0) {
      root1= (-b + Math.sqrt(determinant))/(2 * a);
      root2= (-b - Math.sqrt(determinant))/(2 * a);
      System.out.format("Roots are %.2f and %.2f", root1, root2);
    } else {
      real= -b/(2*a);
      imag = Math.sqrt(-determinant)/(2 * a);
      System.out.format("root1= %.2f+%.2fi", real,imag);
      System.out.format("\nroot2= %.2f-%.2fi", real,imag);
    }
  }
}
Output
Enter value of a, b and c
4 9 2
Roots are -0.25 and -2.00

Enter value of a, b and c
1 1 1
root1 = -0.50+0.87i
root2 = -0.50-0.87i

  • In above java program, first of all we take the coefficients a, b and c as input from user.

  • Then, we calculate determinnant as b*b - 4*a*c. Based on the value of determinant, we calculate the square roots of quadratic equation as per the formula mentioned above.

  • We are using Math.sqrt() method to calculate the square root of a number.

  • At last, we print the roots of the quadratic equation using System.out.format() method.