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.

Here is the flow Diagram of general decision making statement:

C Decision Making flow Diagram If statement
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) {
    /* code to be execute if the condition_expression is true */
C If Statement Program Control flow Diagram
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:
    In above example only statement1 will gets executed if condition_expression is true.