Java Program to Find Roots of Quadratic Equation

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 SNIPPET
public 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); 

    } 

  } 

}

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(). 

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024