if Statement
An if statement lets a program run a block of code only when a certain condition is true. If the condition is false, that block is simply skipped.
1. What is an if Statement?
An if statement lets a program run a block of code only when a certain condition is true. If the condition is false, that block is simply skipped.
2. Why is it used?
Programs rarely do the exact same thing every time — they need to react differently depending on the situation. The if statement is the most basic way to make a program take a decision.
3. Real-Life Example
Think of a simple rule: "If it is raining, carry an umbrella." You only pick up the umbrella when the condition (raining) is true. If it's not raining, you simply skip that action.
4. Syntax
javaif (condition) { // code runs only if condition is true }
5. Example Program
javapublic class IfDemo { public static void main(String[] args) { int marks = 80; if (marks >= 35) { System.out.println("You passed!"); } } }
Output:
You passed!6. Key Points to Remember
- The condition inside
ifmust evaluate to aboolean(true or false). - Curly braces are optional for a single statement, but using them is a good habit that avoids bugs later.
- If the condition is false and there's no
else, the program simply moves to the next line.