Control Flow

Java Program to Find Roots of a Quadratic Equation

A Java program to find the roots of a quadratic equation.

Problem Description

Write a Java program to find the roots of a quadratic equation ax^2 + bx + c = 0.

Code

QuadraticRoots.java
public class QuadraticRoots {
    public static void main(String[] args) {
        double a = 2.3, b = 4, c = 5.6;
        double root1, root2;

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

        // condition for real and different roots
        if (determinant > 0) {
            root1 = (-b + Math.sqrt(determinant)) / (2 * a);
            root2 = (-b - Math.sqrt(determinant)) / (2 * a);
            System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);
        }

        // condition for real and equal roots
        else if (determinant == 0) {
            root1 = root2 = -b / (2 * a);
            System.out.format("root1 = root2 = %.2f;", root1);
        }

        // if roots are not real
        else {
            double real = -b / (2 * a);
            double imaginary = Math.sqrt(-determinant) / (2 * a);
            System.out.format("root1 = %.2f+%.2fi", real, imaginary);
            System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
        }
    }
}

Output

root1 = -0.87+1.30i
root2 = -0.87-1.30i

Explanation

  1. Determinant: Calculated as b^2 - 4ac.
  2. determinant > 0: Two distinct real roots.
  3. determinant == 0: Two equal real roots.
  4. determinant < 0: Two complex roots.