This is the Java Program to Find the Roots of a Quadratic Equation.

Given the coefficients of the quadratic equation, write a Java Program to Find the roots of the quadratic equation.

Calculate the determinant using the formula B^{2} – 4*A*C, and then according to its value calculate the roots, whether they are real and unequal, real and equal, or imaginary.

Here is the source code of the Java Program to Find the Roots of a Quadratic Equation. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

`//Java Program to Find the Roots of a Quadratic Equation`

import java.io.BufferedReader;

import java.io.InputStreamReader;

public class Quadratic {

`// Function to find and display the roots of the equation.`

public static void main(String[] args) {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

double a,b,c;

try{

System.out.println("Enter the coefficients of the quadratic equation");

a = Double.parseDouble(br.readLine());

b = Double.parseDouble(br.readLine());

c = Double.parseDouble(br.readLine());

}catch (Exception e){

System.out.println("An error occurred");

return;

`}`

double determinant = Math.pow(b,2) - 4*a*c;

if(determinant > 0){

System.out.println("Roots are " + (-b+Math.sqrt(determinant))/(2*a)

+ " and " + (-b-Math.sqrt(determinant))/(2*a));

}else if (determinant == 0){

System.out.println("Roots are " + -b/(2*a));

`}`

else{

System.out.println("Roots are " + -b/(2*a) + "+i" +

Math.sqrt(-determinant)/(2*a) + " and "

+ -b/(2*a) + "-i" + Math.sqrt(-determinant)/(2*a));

`}`

`}`

`}`

In the function main(), firstly the coefficients are entered in the variables a,b and c respectively. Then the determinant is calculated (double determinant = Math.pow(b,2) – 4*a*c;). Now, according to the value of the determinant, the roots are displayed using an if-else ladder.

**Time Complexity: O(1)**.

Case 1 (Simple Test Case - Real and Unequal Roots): Enter the coefficients of the quadratic equation 1 -5 6 Roots are 3.0 and 2.0 Case 2 (Simple Test Case - Real and Equal Roots): Enter the coefficients of the quadratic equation 1 -2 1 Roots are 1.0 Case 3 (Simple Test Case - Imaginary roots): Enter the coefficients of the quadratic equation 1 1 1 Roots are -0.5+i0.8660254037844386 and -0.5-i0.8660254037844386

**Sanfoundry Global Education & Learning Series – Java Programs.**.

**Next Steps:**

- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

**Related Posts:**

- Buy Java Books
- Practice Information Technology MCQs
- Apply for Java Internship
- Apply for Information Technology Internship
- Practice Programming MCQs