Beginners Programs :

Java Program: Calculate Roots of Quadratic Equation | Java Programs

Java program to calculate roots of the quadratic equation – The following program has been written in 2 simple ways.

A quadratic equation is of the form ax2+bx+c=0 where a,b,c are known numbers while x is the unknown. Our problem statement is to write a code to find the roots of this equation.

Roots of the equation are the values which when substituted in place of x satisfies the condition. For a quadratic expression of this form there are 2 roots.

For this, we required 3 inputs-a, b, c which can be an integer or decimal so, we make use of the double data type. We read these input values at runtime with the help of Scanner class which helps us read any primitive datatype value at runtime. But before that, we need to create an object to instantiate the Scanner class and make use of its methods. These can be done as given below:

Scanner sc = new Scanner(System.in);

a= sc.nextFloat();

b= sc.nextFloat();

c= sc.nextFloat();

After collecting our inputs, we make a method call for a method (names FindRoots). The inputs (a,b,c) are passed as arguments for this method. In this method, we first find the determinant or det. Det can be found using the formula:

det=b * b – 4 * a * c;

Based on this value of det, there are three possible cases.

  1. When det is positive or if det>0 then, the two roots are real and unique. These root values can be found with formula-> root1 = (-b + Math.sqrt(det)) / (2 * a) , root2 = (-b – Math.sqrt(det)) / (2 * a). We make use of the sqrt method of Math package to find the squareroot.
  2. When the value of det is 0 or if d==0 then, the two roots are real and equal. Th roots can be found using the formula -> root1 = root2 = -b / (2 * a).
  3. When the value of det is negative or if det<0 then, the roots are imaginary. One of the root will have realpart+imaginarpart while another will have realpart-imaginarypart. The real and imaginary part can be found using->    imaginaryPart = Math.sqrt(-det) / (2 * a)      whereas the realPart = -b / (2 *a)

This way we can find the roots of any given quadratic equations for the known value of a, b, c. These roots can further be displayed in our console screen.

Output: