Decision Making in Java
Well, this happens many times in our lives that we need to make some decisions depending upon some conditions. This means that we are going to do something, but it depends on some conditions. Let’s understand this thing with help of an informal example here –
Let’s say you go to some class, let’s say a class for java crash course, and there are only 2 – 3 students today in the class, out of some 40 students. Now the teacher says that we will wait for 10 minutes. If nobody attends the class today, then it will be a holiday. Read the previous sentence again. Here it is told that there is going to be a holiday, but it depends on one condition, that nobody should attend the class.
So, in the end, the students which are there just disappear and hence, no one is attending the class, and hence there is a holiday. We did it during our school time. Our teacher used to come and we would request her a games period, and she would say… ok, go and play on the ground. But if anybody is spotted in the class, I will take the lecture.
So, here also the teacher had made some decision, that she will take class, but only if anyone is spotted inside the class.
This happens in programming life as well. Just for an example, you want to print on the console that… “The number is even”, but only if the number is even. So, here also we want to do something. But on the basis of a certain condition. This is like … I am going to do this only if this happens… This is interesting and important as well, because at times we may need to make a decision based on some conditions.
So, here we are going to discuss how can we make decisions in java. Basically, you just need to concentrate on two words now, that is if and else. Just a few moments ago you have read that if nobody attends the class today, then it will be a holiday. This clears the picture a little bit, right? This means there is a condition that nobody should attend the class today, then only there will be a holiday.
So, in short, we are going to make some decisions based on some conditions. But wait… we did not see or use the else part in the examples above? This is because the else part is optional.
We are supposed to write else part if it is supposed to be there. So this concludes that the if block can be used whenever required, even if you don’t bother about the else part. But writing else without an if can prove to be a nightmare (simply speaking, we get an error). You cannot write else without an if.
This is because the else block is executed if the condition that we are checking with the if is false. This might be confusing because we have been using a lot of if and else in this section, and this is why I have written that if and else in bold which are in the context of java.