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
javaif (condition) { // runs if condition is true } else { // runs if condition is false }
5. Example Program
javapublic class IfElseDemo { public static void main(String[] args) { int marks = 20; if (marks >= 35) { System.out.println("Pass"); } else { System.out.println("Fail"); } } }
Output:
Fail6. Key Points to Remember
- Exactly one block runs —
iforelse— never both. - The
elseblock has no condition of its own; it simply handles "everything else." - Great for situations with only two possible outcomes.