← Back to Chapters

Java if Statement

? Java if Statement

? Quick Overview

The if statement in Java is used to make decisions. It allows a program to execute a block of code only when a specified condition evaluates to true.

? Key Concepts

  • Conditions must return a boolean value
  • Commonly used with comparison operators
  • Controls the flow of program execution

? Syntax / Theory

The if statement checks a condition. If the condition is true, the code inside the block runs.

? View Code Example
// Basic syntax of if statement
if (condition) {
    // statements
}

? Code Example

? View Code Example
// Program to check if a number is positive
int number = 10;

if (number > 0) {
    System.out.println("Number is positive");
}

? Live Output / Explanation

Output

If the value of number is greater than 0, the message Number is positive will be printed.

✅ Tips & Best Practices

  • Always use meaningful conditions
  • Use curly braces for clarity, even for single statements
  • Keep conditions simple and readable

? Try It Yourself

  • Modify the number to a negative value
  • Check if a number is even using an if statement
  • Combine multiple conditions using logical operators