How to Use If Else in Java: Simple Guide with Examples
In Java, use the
if statement to run code only when a condition is true, and else to run code when it is false. The syntax is if (condition) { ... } else { ... }, where the condition is a true/false check.Syntax
The if else statement lets you choose between two paths based on a condition.
- if (condition): Checks if the condition is true.
- { ... }: Code inside runs if condition is true.
- else: Runs if the condition is false.
- { ... }: Code inside runs if condition is false.
java
if (condition) { // code runs if condition is true } else { // code runs if condition is false }
Example
This example checks if a number is positive or not and prints a message accordingly.
java
public class IfElseExample { public static void main(String[] args) { int number = 5; if (number > 0) { System.out.println("The number is positive."); } else { System.out.println("The number is zero or negative."); } } }
Output
The number is positive.
Common Pitfalls
Common mistakes include missing braces, using = instead of == for comparison, and forgetting the else block when needed.
Always use braces { } to avoid confusion, even for single statements.
java
/* Wrong: Using = instead of == */ if (number == 5) { System.out.println("This is wrong"); } /* Right: Use == for comparison */ if (number == 5) { System.out.println("This is correct"); }
Quick Reference
| Part | Description |
|---|---|
| if (condition) | Checks if condition is true |
| { ... } | Code block for true condition |
| else | Runs if condition is false |
| { ... } | Code block for false condition |
Key Takeaways
Use if else to run different code based on true or false conditions.
Always use == to compare values, not = which assigns values.
Include braces { } to clearly define code blocks for if and else.
The else block is optional but useful for handling the false case.
Test your conditions carefully to avoid logic errors.