Skip to content
C

if-else

if-else extends the basic if statement by adding an alternative block of code that runs when the condition is false. Exactly one of the two blocks will run — never both, never neither.


1. What is if-else?

if-else extends the basic if statement by adding an alternative block of code that runs when the condition is false. Exactly one of the two blocks will run — never both, never neither.

2. Why is it used?

Many decisions have exactly two outcomes — pass or fail, eligible or not eligible. if-else handles both possibilities cleanly in one structure.

3. Real-Life Example

Think of an exam result: "If marks are 35 or above, you pass; otherwise, you fail." Both outcomes are covered — there's always a result either way.

4. Syntax

java
if (condition) { // runs if condition is true } else { // runs if condition is false }

5. Example Program

java
public class IfElseDemo { public static void main(String[] args) { int marks = 20; if (marks >= 35) { System.out.println("Pass"); } else { System.out.println("Fail"); } } }

Output:

Fail

6. Key Points to Remember

  • Exactly one block runs — if or else — never both.
  • The else block has no condition of its own; it simply handles "everything else."
  • Great for situations with only two possible outcomes.