Java Programs›Numbers›Find Roots of a Quadratic Equation

Find Roots of a Quadratic Equation in Java

beginner·  Numbers  ·  Math

Problem

The discriminant d = b² − 4ac decides the nature of a quadratic's roots: two real roots when d > 0, one repeated root when d = 0, and a pair of complex roots when d < 0.

Given the coefficients a, b and c of a quadratic equation, find its roots for each of the three discriminant cases.

Input
a=2, b=-7, c=3
Output
3.0 and 0.5

Java Program

Java
public class QuadraticRoots { public static void main(String[] args) { solve(2, -7, 3); solve(1, -6, 9); solve(1, 2, 5); } static void solve(int a, int b, int c) { double d = (double) b * b - 4.0 * a * c; // the discriminant decides which case we're in System.out.print("a=" + a + ", b=" + b + ", c=" + c + " -> "); if (d > 0) { double r1 = (-b + Math.sqrt(d)) / (2.0 * a); double r2 = (-b - Math.sqrt(d)) / (2.0 * a); System.out.println("two real roots: " + r1 + " and " + r2); } else if (d == 0) { System.out.println("one repeated root: " + (-b / (2.0 * a))); } else { double real = -b / (2.0 * a); double imag = Math.sqrt(-d) / (2.0 * a); System.out.println("complex roots: " + real + " + " + imag + "i and " + real + " - " + imag + "i"); } } }

Output

a=2, b=-7, c=3 -> two real roots: 3.0 and 0.5 a=1, b=-6, c=9 -> one repeated root: 3.0 a=1, b=2, c=5 -> complex roots: -1.0 + 2.0i and -1.0 - 2.0i

Core Logic

Computing the discriminant first splits the problem into three cases, and each case applies its own form of the quadratic formula.

How It Works
  1. 1d = b² − 4ac is computed as a double, so large coefficients don't overflow int.
  2. 2When d > 0, the two roots are (−b ± √d) / 2a.
  3. 3When d == 0, both roots collapse to −b / 2a.
  4. 4When d < 0, the roots are complex: the real part is −b / 2a and the imaginary part is √(−d) / 2a.
For a=1, b=2, c=5, d = 4 − 20 = −16, so the roots are −1 ± (4 / 2)i, that is −1 + 2i and −1 − 2i.
💡

Key Point: Dividing by 2.0 * a instead of 2 * a forces floating-point division — with ints, -b / (2 * a) would truncate 1.5 to 1.

Key Concepts

Math.sqrt()if-else-if ladderstatic methodtype casting

Interview Questions

What happens if a is 0?

The equation is linear, not quadratic, and the formula divides by zero. Handle it separately: x = −c / b.

What's the sum and product of the roots?

The sum is −b/a and the product is c/a — a quick way to check computed roots.

Learn the Concept

Related Programs