In our everyday life we have to take one or the other decision.
To reach our office we have to take the decision that if we get a bus we will ride in it else we will be hiring a cab.
Even java has to make some decisions. And there are ways to write it :
So, when we write the above 'going to office by bus or cab' scenario in java, it would be :
In the above code we have created a String type variable 'vehicle' and assigned the value "Bus" to it.
Then we are telling java. If it finds that the String type variable 'vehicle' has value 'Bus'. Get into the block of 'if' statement and print 'Will go to office by Bus.':
Now, let us make a small change in code :
In the above code there is no output.
It is because, in this case the variable 'vehicle' is having the value 'Car'.
Now, using the 'if' statement, when java checks, if the value of 'vehicle' is 'Bus' or not. It does not find because the value of the 'vehicle' is 'Car'.
And thus it does not enter the 'if' block and 'Will go to office by Bus.' is not printed.
It is just like, if you don't get a bus. You go by a cab.
Since, the 'if' condition didn't meet :
It came to the 'else' statement and printed the value 'Will take a Cab.' inside the 'else' statement.
Even in the 'else' statement we can put an 'if' condition. Just to check if the second condition meets or not.
Say there can be a situation that if we do not get a 'Bus', we will try to go by a cab. And if the cab is also not available. Simple, we won't go to the office.
In the above code, we have initialized the variable 'vehicle' with 'No Vehicle'(Suppose no vehicle is available).
The first condition doesn't meet, as we are checking 'vehicle' variable is holding the value 'Bus' or not.
Then it comes to the else part, where there is an if statement again, checking if 'vehicle' variable is holding 'Cab' or not.
It doesn't match, and it comes to the final else and prints the contents inside the 'else' block.