Back to Study Material Java

Decision Making in Java

Decision making is the ability of a program to choose different execution paths based on conditions evaluated at runtime. Without conditional logic, every ...

Decision Making in Java

Controlling Program Flow with Conditional Logic

Decision making is the ability of a program to choose different execution paths based on conditions evaluated at runtime. Without conditional logic, every program would execute the same sequence of statements every time, making it impossible to respond to user input, handle errors, or implement business rules. Java provides several constructs for decision making: the if statement, the if-else statement, the if-else-if ladder, the switch statement, and the ternary operator.

The simplest form is the if statement: if (condition) { // code to execute when condition is true }. The condition must be a boolean expression — something that evaluates to either true or false. Only when the condition is true does the enclosed block execute; otherwise the program skips it and continues with the next statement after the closing brace.

Adding an else clause provides an alternative path: if (temperature > 30) { System.out.println("It is hot."); } else { System.out.println("It is not hot."); }. One of the two blocks always executes — never both, never neither. The else clause is optional.

When multiple mutually exclusive conditions need to be checked, an if-else-if ladder is appropriate. Java evaluates conditions from top to bottom and executes only the first block whose condition is true. For example: if (score >= 90) { grade = "A"; } else if (score >= 80) { grade = "B"; } else if (score >= 70) { grade = "C"; } else { grade = "F"; }. The final else serves as a catch-all for all cases not matched above.

Conditions can be compound boolean expressions built with logical operators. if (age >= 18 && hasID) means both conditions must be true. if (isMember || hasCoupon) means at least one must be true. Complex conditions should be written clearly, and consider extracting them into named boolean variables (boolean isEligible = age >= 18 && hasID;) to make the if statement readable.

Braces are technically optional when an if or else body contains only a single statement, but omitting them is a common source of bugs. The classic example is: if (x > 0) System.out.println("positive"); System.out.println("done"); where only the first println is conditional; "done" always prints. Always use braces even for single-statement bodies.

Interview tip: Interviewers sometimes present code with nested if-else statements and ask which branch executes. The key rule is that an else always pairs with the nearest preceding if that lacks an else. Use braces consistently to make the pairing unambiguous and avoid this source of confusion.