Java Program to solve quadratic equations

In this post, we will find all root of quadratic equation and print them using format() in Java.

To understand this program. we should have the knowledge of:

How the program will work?

  • if the determinant is greater than 0, the root is real and different.
  • if the determinant is equal to 0, the roots are real and equal.
  • if the determinant is less than 0, the roots are complex and different

Lets write this logic in Java Program.

Example : Program to solve quadratic equations

In this program, we will coefficients a, b, and c are set 2.3, 4, and 5.6 respectively. Then, the determinant is calculated as b2 – 4ac.

Based on the above value of the determinant, the roots are calculated as given in the formula above. Notice we’ve used library function Math.sqrt() to calculate the square root of a number.

import java.util.Scanner;
public class quadratic_equations {
    public static void main(String[] args) {
        Scanner sc = new Scanner(;
        double a = sc.nextDouble();
        double b = sc.nextDouble();
        double c = sc.nextDouble();
        double root1, root2;

        double determinant = b * b - 4 * a * c;

        // for real and different roots
        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);
        // Condition for real and equal roots
        else if(determinant == 0) {
            root1 = root2 = -b / (2 * a);

            System.out.format("root1 = root2 = %.2f;", root1);
        // If roots are not real
        else {
            double realPart = -b / (2 *a);
            double imaginaryPart = Math.sqrt(-determinant) / (2 * a);

            System.out.format("root1 = %.2f+%.2fi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart, imaginaryPart);


  1. Java program to get birth dates and find who is older
  2. Check if the given number is prime or not in Java
  3. Java Program Count invalid Mobile numbers form list
  4. Java program Fill a bucket with water using a mug
  5. Java Program to Check if Number is Positive or Negative

Leave a Comment

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