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 **b ^{2} – 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(System.in); 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); } } }

**Recommended:**

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