Java if Statement


The if statement in Java is a conditional control statement that allows you to execute a block of code only if a specified condition evaluates to true. If the condition is false, the code block will not be executed. This is useful for making decisions in your program based on certain conditions.

Syntax of if Statement

if (condition) { // Block of code to be executed if the condition is true }
  • condition: A boolean expression that evaluates to either true or false.
  • Block of code: The code inside the braces {} will execute only if the condition is true.

Example of if Statement

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

public class IfStatementExample { public static void main(String[] args) { int number = 10; // Using if statement to check if the number is positive if (number > 0) { System.out.println("The number is positive."); } } }

Explanation

  1. Declaration: The variable number is declared and initialized with the value 10.
  2. Condition Check: The if statement checks whether number > 0. Since 10 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, and the output will be:
The number is positive.

Example with Multiple Conditions

You can also use the if statement with various conditions. Here's an example that checks if a number is positive, negative, or zero:

public class IfStatementMultipleConditions { public static void main(String[] args) { int number = -5; // Using if statement to check if the number is positive, negative, or zero if (number > 0) { System.out.println("The number is positive."); } if (number < 0) { System.out.println("The number is negative."); } if (number == 0) { 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.
  • Since number is -5, the output will be:
The number is negative.

Summary

The if statement is a fundamental control structure in Java that enables you to implement conditional logic in your programs. It helps you execute code selectively based on whether a certain condition holds true, making your applications more dynamic and responsive to different inputs and states.