Java If-else Statement — Java Technical Interview Questions & Answers

Java If-else Statement

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        Fail

Technical Interview Tip: Take marks = 35 and 72. Say which branch runs, then write the if-else.

Code Examples for Java If-else Statement

Example

// Java If-else
public class Main {
  public static void main(String[] args) {
    int n = 7;
    if (n % 2 == 0) {
      System.out.println("Even");
    } else {
      System.out.println("Odd");
    }
  }
}

Java If-else Statement — take n = 7. 7 % 2 is 1, not 0, so if is false. else runs. Output: Odd. Now n = 8 → Even.

How to Explain Java If-else Statement to an Interviewer

When does the if block run?

Only when the condition is true

What does else do?

Runs when if is false Backup path

How does else if work?

Checks from top to bottom First match wins

What type must the condition be?

boolean true or false

What is the semicolon trap?

if (cond); ends the if early Next block is not part of if