Roots of Quadratic Equation
Find the roots of a quadratic equation ax^2 + bx + c = 0 using discriminant.
Java Roots of Quadratic Equation Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a: ");
double a = sc.nextDouble();
System.out.print("Enter b: ");
double b = sc.nextDouble();
System.out.print("Enter c: ");
double c = sc.nextDouble();
double d = b * b - 4 * a * c;
if (d > 0) {
double r1 = (-b + Math.sqrt(d)) / (2 * a);
double r2 = (-b - Math.sqrt(d)) / (2 * a);
System.out.println("Two real and distinct roots: " + r1 + " and " + r2);
} else if (d == 0) {
double r = -b / (2 * a);
System.out.println("Two equal real roots: " + r + " and " + r);
} else {
double real = -b / (2 * a);
double imag = Math.sqrt(-d) / (2 * a);
System.out.println("Complex roots: " + real + " + " + imag + "i and " + real + " - " + imag + "i");
}
sc.close();
}
}Enter a: 1 Enter b: -3 Enter c: 2 Two real and distinct roots: 2.0 and 1.0
Understanding Roots of Quadratic Equation
We use discriminant d = b² - 4ac to decide if roots are real distinct, real equal, or complex.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.
Practical Learning Notes for Roots of Quadratic Equation
This Java program is part of the "Module 2: Conditional Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.