Skip to main content

If Statement in Java

  • An if statement in Java is a control flow statement that allows your program to execute a certain block of code only if a specified condition is true.

  • Think of it as giving your program a choice: "If this condition is true, then do this."

  • if statements is crucial because they allow your programs to make decisions based on certain conditions.

Syntax of an if Statement

Here is the basic syntax of an if statement in Java:

if (condition) {
// code to be executed if the condition is true
}
  • condition: A boolean expression (an expression that evaluates to either true or false).

  • code block: The set of statements that will be executed if the condition is true. This block is enclosed in curly braces {}.

How It Works

When an if statement is encountered, the condition inside the parentheses is evaluated:

  • If the condition is true, the code block inside the curly braces {} is executed.

  • If the condition is false, the code block is skipped, and the program continues with the next statement after the if block.

Example of an if Statement

Let's look at a simple example to understand how an if statement works. Consider the following code:

public class Main {
public static void main(String[] args) {
int number = 10;

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

Explanation:

  1. Declaration of the variable: We declare an integer variable number and assign it a value of 10.

  2. The if statement: We check if number is greater than 0 using the condition number > 0.

  3. Code block: If the condition is true, the code inside the curly braces {} will execute, printing "The number is positive."

Since number is indeed greater than 0, the output of this program will be:

The number is positive.

Summary

  • if statement: Executes a block of code if a condition is true.

  • Condition: A boolean expression that determines whether the code block will be executed.

  • Code block: The statements that run if the condition is true, enclosed in curly braces {}.

The if statement is a powerful tool for making decisions in your Java programs.