Write a Java Program to Find all Roots of a Quadratic Equation

As a Java programmer, you may come across situations where you need to find all the roots of a quadratic equation.

A quadratic equation is of the form ax² + bx + c = 0, where a, b, and c are constants.

There are three possible scenarios for the roots of a quadratic equation:

  1. If the discriminant b² – 4ac is greater than 0, then the equation has two real roots.
  2. If the discriminant is equal to 0, then the equation has one real root.
  3. If the discriminant is less than 0, then the equation has two complex roots.

To find all the roots of a quadratic equation, you can use the quadratic formula:

x = (-b ± sqrt(b² – 4ac)) / 2a

Here’s the Java program to find all the roots of a quadratic equation:

import java.util.Scanner;

public class QuadraticEquation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the values of a, b, and c:");

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

        double discriminant = b * b - 4 * a * c;

        if (discriminant > 0) {
            double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
            double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
            System.out.println("The equation has two real roots: " + root1 + " and " + root2);
        } else if (discriminant == 0) {
            double root = -b / (2 * a);
            System.out.println("The equation has one real root: " + root);
        } else {
            double realPart = -b / (2 * a);
            double imaginaryPart = Math.sqrt(-discriminant) / (2 * a);
            System.out.println("The equation has two complex roots: " + realPart + " + " + imaginaryPart + "i and " + realPart + " - " + imaginaryPart + "i");
        }
    }
}

In this program, we first use the Scanner class to read in the values of a, b, and c from the user.

We then calculate the discriminant and use if-else statements to determine the number and type of roots.

If the discriminant is greater than 0, we calculate the two real roots using the quadratic formula.

If the discriminant is equal to 0, we calculate the one real root.

If the discriminant is less than 0, we calculate the two complex roots.


In conclusion, the above Java program can be used to find all the roots of a quadratic equation.

It uses the quadratic formula and if-else statements to determine the number and type of roots.

By using this program, you can save time and effort in calculating the roots of a quadratic equation.