English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Java other topics

Java program to find all the roots of a quadratic equation

Comprehensive Java Examples

In this program, you will learn to find all the roots of a quadratic equation and use Java's format() to print them.

The standard form of a quadratic equation is:

ax2 + bx + c = 0, where
a, b and c are real numbers,
a ≠ 0

The b2-4ac is called the determinant of the quadratic equation. The determinant explains the nature of the roots.

  • If the determinant is greater than 0, then the roots are real and different.

  • If the determinant is equal to 0, then the roots are real and equal.

  • If the determinant is less than 0, then the roots are complex and different.

Example: Java program to find the roots of a quadratic equation

public class Quadratic {
    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;
        //The condition for real 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);
        }
        //The condition for real equal roots
        else if(determinant == 0) {
            root1 = root2 = -b / (2 * a);
            System.out.format("root1 = root2 = %.2f;", root1);
        }
        //If the root is not a real number
        else {
            double realPart = -b / (2 *a);
            double imaginaryPart = Math.sqrt(-determinant) / (2 * a);
            System.out.format("root1 = %.2f+%.2fi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart, imaginaryPart);
        }
    }
}

When running the program, the output is:

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

In the above program, the coefficients a, b, and c are set to2.3,4and5.6. Then, calculate the determinant as b2 - 4ac.

According to the value of the determinant, calculate the root as shown in the formula. Note that we have already used the library functionMath.sqrt()to calculate the square root of a number.

Use the format() function in Java to print the calculated root (real root or complex root) on the screen. The format() function can also be replaced with printf():

System.out.printf("root1 = root2 = %.2f;", root1);

Comprehensive Java Examples