Java If-else Statement
if-else is how a program chooses. Real life is not one straight list of steps. Marks can be pass or fail. A number can be even or odd. The program must look at a condition and pick one path. That condition in Java must be true or false — not a lone number like old C. Write if (marks >= 40), not if (marks).
if (condition) { ... } runs only when the condition is true. else is the backup when it is false. else if adds more checks from top to bottom. The first match wins; later else if lines are skipped. Think of it as a teacher checking a paper: first 40+ pass, else fail. Don’t check fail before pass if your story starts at 40.
Let’s take this tiny example on the board. int n = 7; if (n % 2 == 0) print Even; else print Odd. % is remainder. 7 divided by 2 leaves 1, not 0, so the if is false. else runs. Output: Odd. Now change n to 8 in your head. 8 % 2 is 0, if is true, output Even. If you can do that without compiling, you understand if-else.
Same idea with marks. int marks = 35; if (marks >= 40) Pass; else Fail. 35 is not >= 40, so Fail. marks = 72 → Pass. Always pick a sample value and say the branch out loud before you type. That is the classroom habit. Jumping into code with no dry-run is how bugs multiply.
Two mistakes I see every year. One: a semicolon after if (n % 2 == 0); — that empty if ends immediately, and the next { } always runs. Two: writing = inside if when you meant ==. = assigns. == compares. if (n = 2) is not what you wanted, and Java often refuses it because it is not boolean.
else if is for more than two buckets: if marks >= 75 Distinction else if marks >= 40 Pass else Fail. Check from the top. A student with 80 matches the first if and never looks at else if. Order matters. Put the strictest check first when the ranges overlap.
marks >= 40 ?
/ \
yes no
│ │
Pass FailTake marks = 35 and 72. Say which branch runs, then write the if-else.