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

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

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42``` ```public class Main { public static void main(String[] args) { // value a, b, and c double a = 2.3, b = 4, c = 5.6; double root1, root2; // calculate the determinant (b2 - 4ac) double determinant = b * b - 4 * a * c; // check if determinant is greater than 0 if (determinant > 0) { // two real and distinct roots root1 = (-b + Math.sqrt(determinant)) / (2 * a); root2 = (-b - Math.sqrt(determinant)) / (2 * a); System.out.format("root1 = %.2f and root2 = %.2f", root1, root2); } // check if determinant is equal to 0 else if (determinant == 0) { // two real and equal roots // determinant is equal to 0 // so -b + 0 == -b root1 = root2 = -b / (2 * a); System.out.format("root1 = root2 = %.2f;", root1); } // if determinant is less than zero else { // roots are complex number and distinct 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); } } } ```

### Final output

1. public class Main {
2.   public static void main(String[] args) {
3.     // value a, b, and c
4.     double a = 2.3, b = 4, c = 5.6;
5.     double root1, root2;
6.     // calculate the determinant (b2 – 4ac)
7.     double determinant = b * b  4 * a * c;
8.     // check if determinant is greater than 0
9.     if (determinant > 0) {
10.       // two real and distinct roots
11.       root1 = (+ Math.sqrt(determinant)) / (2 * a);
12.       root2 = ( Math.sqrt(determinant)) / (2 * a);
13.       System.out.format(“root1 = %.2f and root2 = %.2f”, root1, root2);
14.     }
15.     // check if determinant is equal to 0
16.     else if (determinant == 0) {
17.       // two real and equal roots
18.       // determinant is equal to 0
19.       // so -b + 0 == -b
20.       root1 = root2 = / (2 * a);
21.       System.out.format(“root1 = root2 = %.2f;”, root1);
22.     }
23.     // if determinant is less than zero
24.     else {
25.       // roots are complex number and distinct
26.       double real = / (2 * a);
27.       double imaginary = Math.sqrt(determinant) / (2 * a);
28.       System.out.format(“root1 = %.2f+%.2fi”, real, imaginary);
29.       System.out.format(\nroot2 = %.2f-%.2fi”, real, imaginary);
30.     }
31.   }
32. }