Java if else

In day to day life , sometimes our action depends on some condition being met. Example: If he has holiday, we will go for movie OR If it is raining , I will open the umbrella OR If I get job, I will give you party etc.

In java there are conditional statements which helps to perform action on some condition being met and those are listed below.

  1. if
  2. if else
  3. switch

Here we will see if else  statement in details. if else is implemented in three ways which are listed below.

  1. if else
  2. Nested ifs
  3. if-else-if ladder

if else is used when you want to perform some action when particular condition is met and you want to perform other action when particular condition is not met. if else  is implemented using keyword if and else.

Note: The group of statements after the if upto and not including the else is called an ‘if block’. Similarly, the statements after the else form the ‘else block’.

How if else works:
If condition is true then statements written within the curly braces or body of if gets executed else statements written within the curly braces or body of else gets executed .General form of if else is given below.

Example of if else is given below:

If we use if else statement within an  body or curly braces of  if statement or within an  body or curly braces of  else statement , then such form of if else statement is called as Nested if else.

How Nested if else works:
If condition 1 is true then condition 2 within the curly braces of if will check. If condition 2 is true then statements within curly braces of condition 2 will gets executed .If condition 2 is false then statements within curly braces of else of condition 2 will gets executed. If condition 1 is false then statements within curly braces of else of condition 1 will gets executed. General form of Nested if else is given below.

Example of Nested if else is given below:

General form of ladder if else is given below.

Example of ladder if else is given below:

You may also like...

Leave a Reply