In if statement we found that code inside if block is executed only when condition is found to be true. But what to do in case condition is false.
This is where if-else statement comes handy.
First see the syntax given below,
Syntax of if-else
//code to execute for true condtion
//code to execute for false condition
In this case if test condition results in false then else block will get executed. Let’s learn more about it in the example given below.
Example: If I reach bus stop before 9:00AM then I will take public bus else I will book Ola or Uber.
printf("\n enter your time ");
printf("\n Take public bus");
printf("\n Book Ola or Uber");
Book Ola or Uber
This time your code knows what decision should be made in case your test condition is false. It knows if you are late to bus stop, you should "Book Ola or Uber"
Drawback of if-else statement
In both if and if-else statement, we found that our decision making capability is subject to just one test condition.
But real life scenarios is not just about if and else. It is like, if abc is true I will do this else if xyz is true I will do this else if pqr is true and so on. What I mean is there could be multiple test conditions that could be checked and based on it we may make our decision.
Solution to the drawback
if-else-if ladder solves our problem. Let’s learn more about it in next chapter of this java tutorial..