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

Formula:

Equation: ax^2 + bx + c

Discriminant = b^2 – 4*a*c

Root1= (-b + sqrt(d))/2*a

Root2= (-b – sqrt(d))/2*a

Formula:

Equation: ax^2 + bx + c

Discriminant = b^2 – 4*a*c

Root1= (-b + sqrt(d))/2*a

Root2= (-b – sqrt(d))/2*a

Enter the Quadratic Equation as an input. Now we use the given formulas to calculate the roots of the equation.

Here is the source code of the Java Program to Find the Roots of Quadratic Equation. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

import java.util.Scanner;

public class Quadratic_Equation

`{`

public static void main(String[] args)

`{`

int a, b, c;

double root1, root2, d;

Scanner s = new Scanner(System.in);

System.out.println("Given quadratic equation:ax^2 + bx + c");

System.out.print("Enter a:");

a = s.nextInt();

System.out.print("Enter b:");

b = s.nextInt();

System.out.print("Enter c:");

c = s.nextInt();

System.out.println("Given quadratic equation:"+a+"x^2 + "+b+"x + "+c);

d = b * b - 4 * a * c;

if(d > 0)

`{`

System.out.println("Roots are real and unequal");

root1 = ( - b + Math.sqrt(d))/(2*a);

root2 = (-b - Math.sqrt(d))/(2*a);

System.out.println("First root is:"+root1);

System.out.println("Second root is:"+root2);

`}`

else if(d == 0)

`{`

System.out.println("Roots are real and equal");

root1 = (-b+Math.sqrt(d))/(2*a);

System.out.println("Root:"+root1);

`}`

`else`

`{`

System.out.println("Roots are imaginary");

`}`

`}`

`}`

Output:

$ javac Quadratic_Equation.java $ java Quadratic_Equation Given quadratic equation:ax^2 + bx + c Enter a:2 Enter b:3 Enter c:1 Given quadratic equation:2x^2 + 3x + 1 Roots are real and unequal First root is:-0.5 Second root is:-1.0

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

Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms.