In this Java tutorial, you will learn how to find the roots of quadratic equation with a sample code snippet.
How to find the roots of quadratic equation?
RUN CODE SNIPPETpublic class Main { public static void main(String[] args) { double a = 2, b = -5, c = 6; double root1, root2; double determinant = b * b - 4 * a * c; 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); } else if (determinant == 0) { root1 = root2 = -b / (2 * a); System.out.format("root1 = root2 = %.2f;", root1); } 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); } } }
Java
x
43
1
public class Main {
2
3
public static void main(String[] args) {
4
5
double a = 2, b = -5, c = 6;
6
7
double root1, root2;
8
9
double determinant = b * b - 4 * a * c;
10
11
if (determinant > 0) {
12
13
root1 = (-b + Math.sqrt(determinant)) / (2 * a);
14
15
root2 = (-b - Math.sqrt(determinant)) / (2 * a);
16
17
System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);
18
19
}
20
21
else if (determinant == 0) {
22
23
root1 = root2 = -b / (2 * a);
24
25
System.out.format("root1 = root2 = %.2f;", root1);
26
27
}
28
29
else {
30
31
double real = -b / (2 * a);
32
33
double imaginary = Math.sqrt(-determinant) / (2 * a);
34
35
System.out.format("root1 = %.2f+%.2fi", real, imaginary);
36
37
System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
38
39
}
40
41
}
42
43
}
OUTPUT
root1 = 1.25+1.20i root2 = 1.25-1.20i
In the above program the, coefficients of a, b, c are set to 2, -5, 6.
The determinant is calculated using b^2-4ac.
The roots are calculated based on the determinant and to calculate the square root of a number we use the library function Math.sqrt().