If Statement in Java

Decision making conditional statements allow a program to take a different path depending on some condition(s). Decision making statements(like if, if-else, if-else ladder, switch statement) lets us evaluate one or more conditions and then take decision whether to execute a block of code or not, or to execute which block of code.

It allow a java program to perform a test and then take action based on the result of that test. Using decision making statements, we can change the behaviour of our program based on certain condition. In other words, using decision making statements, we can specify different action items for different situations to make our application more agile and adaptive.

Java supports different types of decision making statements
  • If Statement
  • If else statement
  • If else Ladder
  • Nested If Statement
  • Switch case Statement

If Statement in Java

If statement in java first evaluates a conditional expression. If conditional expression evaluates to true then only block of code inside if gets executed otherwise control goes to the statement after if block.

If block is used to execute a set of statements only if some condition(s) becomes true.

Syntax of if statement
if(condition_expression) {
    statements;
}

condition_expression is a boolean expression (evaluates to true or false like i > 100)

  • If condition_expression evaluates to true, statements are executed.
  • If condition_expression evaluates to false, statements are skipped.

Java If Statement Program Control flow Diagram

Java If Statement Example Program

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

        if (num > 0) {
            System.out.println("Positive Number");
        }
        System.out.println(num);
    }
}
Output
Positive Number
10

Points to Remember about If Statement

  • condition_expression must evaluate to true or false.

  • We can combine multiple conditions to using logical operators(&& and ||) to form a compound conditional expression.
    For Example:
         
    if(condition_one && condition_two) {
        /* if code block */
    }

  • Opening and Closing Braces are optional, If the block of code of if statement contains only one statement.
    For Example:
         
    if(condition_expression)
        statement1;
    statement2;
    
    In above example only statement1 will gets executed if condition_expression is true.