Java if else Statement


The if-else statement in Java allows you to execute one block of code if a specified condition is true and a different block of code if the condition is false. This control structure is useful for making decisions in your program based on certain conditions.

Syntax of if-else Statement

if (condition) { // Block of code to be executed if the condition is true } else { // Block of code to be executed if the condition is false }
  • condition: A boolean expression that evaluates to either true or false.
  • True Block: The code inside the first set of braces {} executes if the condition is true.
  • False Block: The code inside the second set of braces {} executes if the condition is false.

Example of if-else Statement

Here’s a simple example demonstrating the use of an if-else statement:

public class IfElseStatementExample { public static void main(String[] args) { int number = 5; // Using if-else statement to check if the number is positive or negative if (number > 0) { System.out.println("The number is positive."); } else { System.out.println("The number is not positive."); } } }

Explanation

  1. Declaration: The variable number is declared and initialized with the value 5.
  2. Condition Check: The if statement checks whether number > 0. Since 5 is greater than 0, the condition evaluates to true.
  3. Execution: Because the condition is true, the code inside the if block (System.out.println("The number is positive.");) is executed.
  4. Output: The output will be:
    The number is positive.

Example with Different Conditions

Here’s another example that checks if a number is positive, negative, or zero using an if-else statement:

public class IfElseStatementMultipleConditions { public static void main(String[] args) { int number = 0; // Using if-else statement to check if the number is positive, negative, or zero if (number > 0) { System.out.println("The number is positive."); } else if (number < 0) { System.out.println("The number is negative."); } else { System.out.println("The number is zero."); } } }

Explanation

In this example:

  • The program checks three different conditions:
    • If number is greater than 0 (positive).
    • If number is less than 0 (negative).
    • If number is equal to 0 (zero).
  • Since number is 0, the output will be:
    The number is zero.

Summary

The if-else statement is a fundamental control structure in Java that allows you to implement conditional logic in your programs. It enables you to choose between two paths of execution based on whether a certain condition is true or false. This makes your applications more dynamic and responsive to various input scenarios.