A program may need to execute different sets of statements depending upon a condition. As an example, if we were to search for a painter of a painting from a list of painters and if it finds the painter, then the program should indicate that it has found the painter. Else, it should continue its search. Java handles such cases using conditional expressions.
Let us understand conditional expression using the following flow-chart. The flow-chart starts with a condition that can evaluate to True or False. If the condition evaluates to True, then the program executes task pertaining to that condition otherwise it executes other task. Needless to say, the location of putting a condition expression is dictated by the application logic.
/* Format of a single if expression */ if (condition) { Execute some statements } /* Format of an if-else expression */ if (condition) { Execute statements pertaining to the "condition" } else { Execute Alternative statements } /* Format of an if-"else if"-else expression */ if (condition) { Execute statements pertaining to the "condition" } else if (condition1) { Execute statements pertaining to the "condition1" } else if (condition2) { Execute statements pertaining to the "condition2" } else { Execute Alternative statements }
Before we go any further, let us spend some time thinking about what it takes to make the condition evaluate to True or False. We can broadly put such expressions into two categories.
The first category is one that is purely boolean in nature. Let us say, we have a variable, var_x, with a value of 2. Thus, an expression " if (var_x == 2) " would evaluate to True since value of var_x is indeed 2. Further, expressions like " if (x > 0)" or "if (x != 4)" would also evaluate to True. On the other hand, some of the expressions would evaluate to False, like " if (x < 0)" or "if (x != 2)". So, basically, relational expressions that compare a variable for equality, greater than, less than, etc.
The second category is more subtle. Java also evaluates expressions with non-zero value as True. Thus, "if (var_x)" would be True because var_x is not equal to zero and so it has some value! As an example, "if (!var_x)" would be False since negation of 2 would be a 0, which is not a value.
If the conditions form an if-"else if"-else clause are always integer values and belong to a set of closely-related values, then we can use a special conditional expression, the "switch" statement.
Let us first see a pseudo-code that shows a typical format of the switch expression. A switch handles each clause by comparing to different case values, where each case value must be a constant. If the expression matches any of the case values, then it runs the corresponding the statements; else, it runs the default case (if we have one). We also have a break statement present for each cases. This means that once we are done running the statements, we break out of the switch expression.
switch (expression) { If needed, declare Variables case constant0: Execute statements pertaining to the "constant0" break; case constant1: Execute statements pertaining to the "constant1" break; default: Execute Alternative statements break; }
It is important to keep two things in mind for a switch statement.
First, the above constant expressions cannot be variables themselves; replacing these case constants, "constant0" or "constant1" with expressions (even if that leads to an integer) would lead to a compilation error. Let us say that we have an integer variable, temp_var that equals 100. In this case, it is not allowed to replace a constant by temp_var, instead they should be 100 or other integer value (often, we use macros or enums to achieve this).
Second, the "expression" should also evaluate to an integer value, otherwise that would also lead to a compilation error. This "expression" value can be either 100 or temp_var since both are of type integer and they both evaluate to an integer value. In addition to an integer, the expression can also evaluate to the related types of short, long, or char.
A note about the default case. It is not mandatory for a switch statement to have a default case but keeping one is a good practice. Basically, the default case can catch all values (perhaps, error cases) that are not covered by individual cases. Alternatively, there could also be scenarios, where most of the cases intentionally go to default and only a few specialized values get the preferential treatment.
Java also provides a handy conditional operator for "if-else" clause: "if (condition) ? do_this_1 : do_this2". If the "condition" is True, then Java runs "do_this_1", else, it runs "do_this_2".
A conditional statement or switch statement could be nested. A nested statement goes like this if (condition)-if(inside the first if condition)-if(inside the 2nd if condition). A switch statement could also be nested and a nested statement could be on any depth and any combination. For example, if statement inside a switch statement or vice versa. Let us understand nested statements using the following flow-chart.
/* Format of a single nested-if expression * Notice the scope of these if-condition. */ if (condition) { // Start of outer if-condition Execute some statements if (condition) { // Start of inner if-condition Execute some statements if (condition) { // Start of inner most if-condition Execute some statements } // End of inner most if-condition } // End of inner if-condition } // End of outer if-condition /* Format of a nested if-"else if"-else expression */ if (condition) { Execute statements pertaining to the "condition" if (condition-0-1) { Execute statements pertaining to the "condition0-1" } else { Execute some statements switch (expression) { case 1: Execute statements switch (expression) { case constant0: Execute statements break; case constant1: Execute statements break; default: Execute statements break; } break; case 2: Execute statements break; default: Execute statements break; } Execute alternative statements pertaining to the "condition0-1" } } else if (condition1) { Execute statements pertaining to the "condition1" if (condition-1-1) { Execute statements pertaining to the "condition1-1" } else if (condition-1-2) { Execute statements pertaining to the "condition1-2" } else { Execute alternative statements pertaining to the "condition11" } } else if (condition2) { Execute statements pertaining to the "condition2" } else { Execute Alternative statements }
Let us write a program using all the concepts we have see so far in this section.
public class ConditionalExample { public static void main(String[] args) { int var1 = 880; int var2 = 101; int var3 = 237; if (var1 > var2) { System.out.println( " Var 1 ("+ var1 + ") is bigger that Var 2 (" + var2 + ")"); } if (var2 > var1) { System.out.println( " Var 1 ("+ var1 + ") is bigger that Var 2 (" + var2 + ")"); } else if (var2 < var1){ System.out.println( " Var 2 ("+ var2 + ") is smaller that Var 1 (" + var1 + ")"); } else { System.out.println(" Var1 and var2 are same"); } // Alternate way of writing if else using conditional operator. System.out.println(" The bigger number among 101 and 880 is " + (var1 > var2 ? var1 : var2)); // Switch statement int option = var1; switch (option) { case 237: System.out.println(" Number 237"); break; case 880: System.out.println(" Number 880"); // Notice the usage of if-else inside switch. We can mix and match. if (880 < var2) { System.out.println (" 880 less than var2"); } else { System.out.println (" 880 greater than or equal to var2"); } break; case 680: System.out.println(" Number 680"); break; default: System.out.println(" No Match Found"); } } }
Compile/Run this program and here is the output:
Var 1 (880) is bigger that Var 2 (101) Var 2 (101) is smaller that Var 1 (880) The bigger number among 101 and 880 is 880 Number 880 880 greater than or equal to var2