Logout

Home Topic 4 Last Next

Compound Conditions

And Multiple Selection

The following fictitious program is intended to help a company make hiring decisions. There are three divisions in the company, each under different financial constraints. Since both experience and years of education make a difference in the salary scale, different compound conditions are used for each division in its hiring.

This code will be used to highlight several if/else conditional blocks (i.e. "branching") aspects detailed in the notes below.

 1 package compoundconditionspackage;
 2 
 3 import java.io.*;
 4 
 5 public class CompoundConditions {
 6     public static void main(String[] args) {
 7         try{
 8             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 9             System.out.println("Welcome");
10             System.out.println("Please type in your full name.");
11             String fullName = br.readLine();
12             System.out.println("Which division of our company are you applying to"
13                     + "the one with lots of money (a), the one doing ok (b), or the"
14                     + "one that's in a bit of finantial trouble (c)? (type a or b or c");
15             String companyDivision = br.readLine();
16             System.out.println("Please enter your years of experience:");
17             int yearsExp = Integer.parseInt(br.readLine());
18             System.out.println("Please enter your years of university:");
19             int yearsUni = Integer.parseInt(br.readLine());
20             
21             if(companyDivision.equals("a")){
22                 if(yearsExp > 10 && yearsUni > 10){
23                     System.out.println("Our division has lots of money, so we can look for candidates " +
                                 like you with both lots of experience and lots of education: " +
                                 " You are hired, congratuations.");
24                 }
25                 else{
26                     System.out.println("Sorry.");
27                 }
28             }
29             else if(companyDivision.equals("b"))
30             {
31                 if(yearsExp > 10 || yearsUni > 10){
32                     System.out.println(fullName + "Our division sometimes can't afford to hire " +
                                 candidates that have both lots of experience and lots of education, but " +
                                 "fortunately in your case we can consider you: You are hired, congratuations.");
33                 }
34                 else{
35                     System.out.println("Sorry.");
36                 } 
37             }
38             else if(companyDivision.equals("c"))
39             {
40                 if(yearsExp > 10 ^ yearsUni > 10){
41                     System.out.println(fullName + "You are just the kind of candidate we can consider. " + 
                                 " We cannot hire candidates who are too high on our pay scale due to both high " +
                                 "levels of experience and education. So having ONE OR THE " +
                                 " OTHER, BUT NOT BOTH: You are hired, congratuations.");
42                 }
43                 else{
44                     System.out.println("Sorry.");
45                 }
46             }
47             else{
48                 System.out.println("Sorry, you did not type in a or b or c.");
49             }       
50         }
51         catch(Exception e){
52             System.out.println(e.getMessage());
53         }    
54     }
55 }

This program introduces more than just compound conditons and multiple selection, it's also got checking for equality between two Strings, and nested conditionals. The notes which follow will take them one at a time, including a little bit on basic simple conditions. The first thing we'll need to look at is checking for String equality.

Checking For String Equality

With all other data types (like ints and booleans and so on), equality is checked by using the 'equality' operator, which is two equals signs (==). For example for ints x and y, we could go if(x == y).

But for Strings we actually have to use a specific method from the String class called "equals()". It takes the String that is calling the method, and checks to see if it is equal to the String following the call in the parentheses. So for Strings s and s1, we could go if(s.equals(s1));

The "equals()" String method evaluates to either boolean true or boolean false. So if s1 was assigned "hello", s2 was assigned "world", and s3 assigned "hello":

s1.equals(s2) evaluates to false

s1.equals(s3) evaluates to true

Almost always, either == or the String method "equals" will be used in a conditional statement (see next topic).

Conditional Blocks

With if/else conditional blocks, the idea is that as a program is run, it reaches points where it can do one chunck of code or another, depending on a certain condition. We say that the conditional statement of an if/else block controls the "flow of control". The flow of control will normall go from line 1 to line 2 to line 3 and so on. But, generally, three things can disrupt this sequential flow of control: method calling, looping, and conditional blocks. Consider the following lines from the program above:

22         if(yearsExp > 10 && yearsUni > 10){
23             System.out.println("You are hired, congratuations.");
24         }
25         else{
26             System.out.println("Sorry.");
27         }

If the overall evaluation of line 22 is true (so, if both of the conditions are true), then the flow of control goes to line 23 (and on through any other lines that followed within the if block. But if line 22 overall evaluates to false, then the flow of control goes to the else block associated with the if statement, so to line 25, and whatever lines are in the block of code that follows the else.

Nested Conditions

Through a lot of the program above (and as particularly seen in the code segment below), you'll note that inside the "outer" if block, there is another if/else "inner" block. This sort of block within a block situation is referred to as nesting. So this is an example of nested conditional blocks. Whenever you put one block inside another is is most important to be conscious of your braces. In fact, some programmers are in the habit of commenting every single brace when dealing with complex nesting, as seen below, with the same code segment as above.

We would stay that there is an if/else block nested within an outer if block, in this case.

21     if(companyDivision.equals("a")){//begin if division "a"
22         if(yearsExp > 10 && yearsUni > 10){//begin if both conditions over 10
23             System.out.println("You are hired, congratuations.");
24         }//end if conditions over 10
25         else{//begin else for both conditions over 10
26             System.out.println("Sorry.");
27         }//end else for both conditions over 10
28     }//end if division "a"
29     else if(....


Simple if block vs. Multiple conditional selection

It is possible, indeed common, to have a "stand-alone" if statement without an else, or more if/elses. In this case, an if block is either entered or not (depending on whether the condition evaluates to true or false), and that's it. Like in this example:

1  String s1 = "hello";
2  String s2 = "world";
3  if(s1.equals(s2)){
4     System.out.println("The two are equal.");
5     System.out.println("Yes, indeed, they are.");
6  }
7  int x = 999
...

So in this case the code either executes lines 1, 2, 3, 4, 5, 6, 7, or 1, 2, 3, 6, 7. i.e, the flow of control either goes straight on down through each line (when the if condition evaluates to true), or the if block is skipped (when the if condition evaluates to false).

But often the question that determines how the flow of control goes is not simply if something is true or false, but rather if something is true, or if something else is true, or if a third something is true, and so on and so on. That's what we have in the full program above. If the companyDivision is "a", we do something, but if it is "b" we do something else, and if it is "c" we do a third thing, and if it's none of "a" or "b" or "c", then we do a fourth thing. This is an "if/else if/else if/else" situation.

21         if(companyDivision.equals("a")){
22             if(yearsExp > 10 && yearsUni > 10){
23                 System.out.println("You are hired, congratuations.");
24             }
25             else{
26                 System.out.println("Sorry.");
27             }
28         }
29         else if(companyDivision.equals("b"))
30         {
31             if(yearsExp > 10 ^ yearsUni > 10){
32                 System.out.println(fullName + "You are hired, congratuations.");
33             }
34             else{
35                 System.out.println("Sorry.");
36             } 
37         }
38         else if(companyDivision.equals("c"))
39         {
40             if(yearsExp > 10 || yearsUni > 10){
41                 System.out.println(fullName + "You are hired, congratuations.");
42             }
43             else{
44                 System.out.println("Sorry.");
45             }
46         }
47         else{
48             System.out.println("Sorry, you did not type in a or b or c.");
49         }       
50     }

So if the variable companyDivision is equal to "a", then the lines that get executed are 21 - 28, and then the flow of control goes all the way down to the end of the if/elseIf block, to line 50.

Whereas for the other cases, you would have to check the other else/ifs. So, for example, with the case where the variable is neither a nor b nor c, the flow of control would go from line 21 to line 29 to line 38 to line 47, and then 48, 49, 50.

So it goes if, else if, else if, else if (for as many possible times as there are possibilities), and then finally just else. The first one is always just if, the ones inbetween are else if, and the last one is else.

And do be sure, when doing this kind of a multiple selection block to include a "catch-all" last else, to handle all other situations than the particular ones described in the if/else if blocks above.

Compound Conditions

A compound condition is an expression with more than one part that can evaluate to either true or false. So the question is, how do more than one condition ultimately evaluate to one boolean value of either true or false, which determine how the flow of control goes?

It depends on the operators that join multiple conditions. There are three: and (&&), or (||) and xOr (^). First a little clarification of what the symbols are. && is two 'ampersands' which you usually get with Shift-7. ^ is called the 'carat', and is usually typed with Shift-6. || is made of two 'pipes', the symbol usually typed with Shift-backslash.

And (&&) means that the two conditions on either side of it have to both be true for the conditional block to be entered.

Or (||) means that only either of the two (though, indeed both) of the conditions on either side of it need to be true for the condition to be entered.

xOr (^) means that either of the two, but not both of the conditions can be true to enter the conditional block.

The xOr (pronounced 'X'-or), which is called the "exclusive or" is not often seen. But in our case it does indeed make sense to use it. Our intention is that the company division in financial trouble cannot afford to pay their new employees a lot of salary, yet they'd like candidates with at least good work experience or a university degree. So they'll hire in either of those cases, but they cannot hire if the candidate has both a lot of experience and also a university degree, since according to the pay scale, they would have to pay them too much.:

22         if(yearsExp > 10 ^ yearsUni > 10){

Meantime, in terms of explaining our program, for the company division "b" in an ok financial state, they could hire candidates with either qualifications only, but it wouldn't matter if they hired a candidate satisfying both conditions (and consequently having to be paid more), as that didn't happen every time:

31         if(yearsExp > 10 || yearsUni > 10){

And the company "a", with loads of cash can afford to be picky, so they will hire only if both hiring conditions are true:

31         if(yearsExp > 10 && yearsUni > 10){

 

Order of Evaluation of Compound Conditions

The order of evaluation of compound conditions is:

So you evaluate and simplify a complex boolean expression until you are left with either true or false.

Here's an example, taking it one step at a time:


boolean b1 = false;
boolean b2 = true;
boolean b3 = false;
boolean b4 = false;

//Note in the code below, bold indicates the next expresion to be evaluated, and italics indicates the result.
System.out.println(b1 || b2 && b3 && (b2 || b4));
(b1 || b2 && b3 && (b2 || b4));
(b1 || b2 && b3 && (true));
(b1 || false && true);
(b1 || false);
(false);

"Short-cicuiting"

Note in the above example, if b1 had been true, none of the rest of the compound condition would need to be evaluated; a true and an or will result in overall true. This situation is called short-circuiting.

In a similar way, in a compound condition situation, an AND situation that is false can cause immediate short circuiting evaluation of the expression to overall false.

Java Boolean Not: !

The explpanation mark means Not in Java. So !true is false, and !false is true.

With a not, you just make the boolean value to be the opposite of what it was.

Here's an example:

boolean b = true;
boolean c = true;
boolean d = false;
System.out.println(b && c && !d) //would be true, since it ends up true && true && !false 
                                  (i.e. true && true && true)