Java If Statement

The if statement is a conditional statement that allows you to execute a block of code only if a certain condition is met.

Here’s the basic syntax for an if statement in Java:

if (condition) {
  // code to be executed if condition is true
}

The condition is a boolean expression that is evaluated to either true or false. If the condition is true, the code inside the curly braces will be executed. If the condition is false, the code inside the curly braces will be skipped.

Here’s an example of an if statement in action:

int x = 10;

if (x > 5) {
  System.out.println("x is greater than 5");
}

In this example, the condition x > 5 is true because x is equal to 10, which is greater than 5. Therefore, the code inside the curly braces will be executed and the message “x is greater than 5” will be printed to the console.

You can also use an if statement with an else clause to specify what should happen if the condition is false. Here’s an example:

int x = 10;

if (x > 5) {
  System.out.println("x is greater than 5");
} else {
  System.out.println("x is not greater than 5");
}

In this example, the condition x > 5 is still true, so the code inside the first set of curly braces will be executed and the message “x is greater than 5” will be printed to the console. If x were not greater than 5, the code inside the else clause would be executed instead.

You can also use multiple if statements with else if clauses to test multiple conditions. Here’s an example:

int x = 10;

if (x > 15) {
  System.out.println("x is greater than 15");
} else if (x > 10) {
  System.out.println("x is greater than 10");
} else if (x > 5) {
  System.out.println("x is greater than 5");
} else {
  System.out.println("x is not greater than 15, 10, or 5");
}

In this example, the first condition x > 15 is false, so the code inside that block is skipped. The second condition x > 10 is also false, so the code inside that block is skipped as well. The third condition x > 5 is true, so the code inside that block is executed and the message “x is greater than 5” is printed to the console.