HOME HTML EDITOR C JAVA PHP

Java If...Else: Decision Making

Java uses conditional statements to perform different actions based on different conditions. This allows your program to "think" and take paths based on user input or data.

Watch Out! A common mistake is using a single equals = (assignment) instead of double equals == (comparison) inside your condition. Always use == to check for equality!

1. The Four Types of Conditions

Java provides several ways to control the flow of your program based on boolean logic:

2. Logical Flow

The program evaluates the condition inside the parentheses. If it is true, the code block inside the curly braces {} runs. If it is false, the program skips that block.

3. Difference: if-else vs ternary operator

For simple conditions, you can choose between standard syntax or a shorter version:

if-else Block

Best for multiple lines of code or complex logic. Easy to read for beginners.

Ternary Operator (?:)

Short-hand if-else that fits in one line. Format: variable = (condition) ? valueTrue : valueFalse;

Nested if

An if inside another if. Used for hierarchical decision making.

4. Comparison Operators in Conditions

Most if statements use these operators to create boolean results:

  1. Less than: a < b
  2. Greater than: a > b
  3. Equal to: a == b
  4. Not Equal to: a != b

5. Comparison: else vs else if

Statement Purpose Quantity
if Initial condition check. Only 1 per block.
else if Check another condition if previous fails. Multiple allowed.
else Final "catch-all" if nothing else is true. Max 1 at the end.

6. Code Example

int time = 22;
if (time < 10) {
  System.out.println("Good morning.");
} else if (time < 20) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening."); // This will run
}

Final Verdict

If...Else statements are the backbone of interactivity. By mastering these, you can create programs that react differently to different users and situations.

Next: Learn Java Switch →