Java Program to Find all Roots of a Quadratic Equation

In this program, you’ll learn to find all roots of a quadratic equation and print them using format() in Java.

The standard form of a quadratic equation is:

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

The term b2-4ac is known as the determinant of a quadratic equation. The determinant tells the nature of the roots.

  • If determinant is greater than 0, the roots are real and different.
  • If determinant is equal to 0, the roots are real and equal.
  • If determinant is less than 0, the roots are complex and different.

Example: Java Program to Find Roots of a Quadratic Equation

  1. public class Quadratic {
  2. public static void main(String[] args) {
  3. double a = 2.3, b = 4, c = 5.6;
  4. double root1, root2;
  5. double determinant = b * b - 4 * a * c;
  6. // condition for real and different roots
  7. if(determinant > 0) {
  8. root1 = (-b + Math.sqrt(determinant)) / (2 * a);
  9. root2 = (-b - Math.sqrt(determinant)) / (2 * a);
  10. System.out.format("root1 = %.2f and root2 = %.2f", root1 , root2);
  11. }
  12. // Condition for real and equal roots
  13. else if(determinant == 0) {
  14. root1 = root2 = -b / (2 * a);
  15. System.out.format("root1 = root2 = %.2f;", root1);
  16. }
  17. // If roots are not real
  18. else {
  19. double realPart = -b / (2 *a);
  20. double imaginaryPart = Math.sqrt(-determinant) / (2 * a);
  21. System.out.format("root1 = %.2f+%.2fi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart, imaginaryPart);
  22. }
  23. }
  24. }

When you run the program, the output will be:

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

In the above program, the coefficients a, b and c are set to 2.3, 4 and 5.6 respectively. Then, the determinant is calculated as b2 - 4ac.

Based on the value of determinant, the roots are calculated as given in the formula above. Notice we’ve used library function Math.sqrt() to calculate the square root of a number.

The calculated roots (either real or complex) are printed on the screen using format() function in Java. The format() function can also be replaced by printf() as:

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