Home > Using operators and decision constructs > Using operators and decision constructs in Java

Using operators and decision constructs in Java

 

Module 1: Using operators and decision constructs.

  

Objectives:

  • Identify relational and conditional operators.
  • Create if and if / else constructs.
  • Use the switch construct.

 

1. Identify relational and conditional operators:

In everyday life, we make many decisions. For instance, if its raining I will use umbrella so that I dont get wet. This is a type of branching. If one condition is true, that’s if raining,  I take my umbrella. If the condition is not true but false, then I will not take my umbrella. This type of branching decision making can be implemented in Java programming using ‘if’ statements.

 

 

Identify relational and conditional operators 

 

But before we can discuss about “if” statements, we need to know about relational operators. Because in Java to make a decisions you have to test the relationship between things.

  

Relational operators:

The following is the relational table which shows the relational operators in Java. As the name relational implies, it says how 2 things are related to each other. All the operators listed here are binary operators. What this means is, they always work on 2 things which are left and right operands. These operators will compare the 2 operands together and returns is a boolean value, a true or false value. For ex, the == operator tells us if the 2 operands are equal, if they are it returns a true value, if not it returns a false value.  

 Relational operators

 

In the above example,
int i=1;
if(i==1), will return true.

Similarly we have different operators such as not equal to, less than, less than or equal to, is greater than and greater than or equal to operators. These operators are not going to sit by themselves and we are going to use them in the “if” statements.

  

Conditional operators:

A lot of times in Java we just want to ask very simple question, such as ‘is x greater than 2’. But there are other times when we want to ask bit complicated questions. For example, in real life we might want to ask something like “if its raining and if its muddy outside, i will take my umbrella and my boots”. To do this in Java we use the conditional operators. We have AND, OR and NOT operators to implement the conditional operations as shown in the table.

 Conditional operators

 

The AND and the OR are binary operators just like the relational operators were, that means that they have left and right operands and they also return true / false. The NOT is a unary operator, it only takes 1 operand and it also returns a true / false.

For the AND operator to return true, both the left and the right operand have to evaluate to true. If either one of them are false, it will return a false. For the OR operator, if either side of the operator evaluate to true, then the operator returns a true. If both of the operands are false, then it will return false. For the NOT operator, it basically just reveres the boolean value of the single operand. That is if a NOT value is applied to a true value then it returns false, and if its applied to a false value then it returns true. We shall take a look at some examples to better understand them.

Lets start with the AND operator represented by double ampersand (&&)

ex:
int i = 2;
int j = 8;
An && operator needs a true/false value on the left hand side and a true/false value on the right hand side. So one way to do that is using relational expressions, because we know relational operators return true or false.
((i<1)&&(j>6))
So, here on the left hand side we have, “is i < 1”, and as i = 2 and hence i is not less than 1, we get false. So the whole expression now will be false. Java doesnt even have to evaluate the expression on the right hand side here because for && operator to return true, both the operands have to be true. So, the minute it finds a false value, it returns false.

true && true = true
true && false = false
false && false = false
false && true = false

 

Lets take a look at the OR example represented by (||)

ex:
int i = 2;
int j = 8;
Again, || operator needs both sides to be true / false values.
((i<1)||(j>=10))
So here, i<1 is false. At this point it cant determine if it has to return true / false for the whole expression. So, it also has to check the right hand side. So j>=10, this is false. So both sides of the OR expression is false. so it returns false.

true || true = true
true || false = true
false || false = false
false || true = true

 

Lets take a look at the NOT operator represented by (!)

ex:
int i = 2;
(!(i>3))
Here we are first asking the question, i>3. it is not. so its false. But here we are applying the NOT operator. So, NOT operator returns reverse which is true.

!true = false
!false = true

  

  

2. Creating if  and if / else constructs:

We will now use the relational and the conditional operators that we discussed about. We will use it with “if” statements. The “if” statements are branching statements. It allows the program to make a decision. The “if” statement is going to evaluate a expression (relational / conditional) and it it returns true, it executes one branch of the code and if not then executes a different branch of code.

 

 Creating if  and if - else constructs

 

We will first look at a basic form of “if” statement first. We start with a simple “if” keyword, and in paranthesis we put a boolean expression i.e., some expression which returns true / false (which can be either relational / conditional). After this we have a left curly bracket which opens the code block and a right curly bracket which closes the code block. And the code block is the code which we put, so that it executes if the boolean expression is true. If the expression is true, then the code block executes else the it skips the code block and continues with the rest of the program. We can see this  in the flow chart to the right.

 

IF example: 

Lets take a look at an example of “if” statement. In the top left window we see, that if x is greater than 7, then “x is greater than 7” is displayed in the console. So in this case if x is greater than 7, then this code block will be executed, if not then this code block will be skipped and the rest of the program will be executed.

Lets consider this for 2 scenarios. First for x = 8 and next for x = 3.

 

For x = 8:

 IF example 1

 

So, as we see in the flow chart, if x is 8 then the test boolean expression x > 7 evaluates to true, and hence the code block is executed printing the output to the console and after the execution it exits the code block and continues with the rest of the program.

 

For x = 3: 

 

 IF example 2 

Here we see in the flow chart, that if x = 3, then the test boolean expression of x>7 will return false, and hence we follow the false path, and will not execute the code block and continues with the rest of the program. So, nothing will be printed to the console.

 

Nested if statements:

Here we will see an example of nesting if statements, that is nesting one if statement into another. You can here see that we have the if statement from the previous section (x > 7), and inside that now we have another if statement (y < 3 ). So to print the statement inside the code block that is “x is greater than 7” and “y is less than 3”, both the expression statements have to return true ie., x > 7 and y < 3. Again, lets consider 2 scenarios for true / false path.

 

For x = 8, y = 2:

 

Nested if statements 1

 

So here we have x = 8 which satisfies x > 7, so it enters into the immediate code block and then we have y = 2 which satisfies y < 3, which is also true so it enters into the code block where we are printing the statements to the console. So both the statements get printed. So as you can see from the flow chart, the true path is followed.

 

For x = 3, y = 5:

 

 Nested if statements 2

 

So here we have x = 3 which doesnt satisfies x > 7, so it doesnt enters into the immediate code block so the next expression y < 3 doesnt get evaluated at all as it is within the code block, so none of the statements are printed to the console. As you can see from the flow chart, the false path is followed.

 

The if / else construct:

So far in our if statements we have only executed the code when the expressions evaluated to true, but sometimes we might want to execute a perticular code block when an expression is true and another piece of code when its false. This happens in the real worls, for example, “if its raining, i will take my umbrella, if not, i will take my sunscreen”. In order to do this, all we need to do is add an else block at the end of the if block.

 

 The if - else construct

 

You can see in the syntax block, we have our if statement from before and an else keyword with a second code block. This code block will be executed if the expression in the if statement evaluates to false. This is also stated in the flow chart to the right. We will test the expression first, if it evaluates to true, then we take the true path and execute code block 1. If it evaluates to false, then we we take the false path and execute code block 2.

 

If / else example:

Lets take a look at an example of if / else statement. We have our if statement example from before that is x > 7. And now we have added on else block. So, if value of x is greater than 7, then we print “x is greater than 7” to the console. But if the value of x is not greater than 7, then we will execute the else code block, which prints “x is not greater than 7” to the console. Lets see 2 scenarios in this.

 

For x = 8:

 

If - else example 1 

 

Here we can see that x = 8, and we start with testing the boolean expression x > 7, and indeed it is here, so this will be true. So the code block in the if statement gets executed hence printing “x is greater than 7” to the console. Here in the flow chart, we see that the true path is followed.

 

For x = 5:

 

 

 If - else example 2 

 

Here we can see that x = 5, and we again start with testing the boolean expression x > 7, and ist not so, so this will be false. Hence the code block in the if statement will not be executed but the else block code will be executed hence printing out “x is not greater than 7” to the console. Here in the flow chart, we see that the false path is followed.

 

Chaining if / else constructs:

Many times in our code, we have to handle more than true / false situation. For example in the real world, “if its raining, i will take my umbrella, but if its snowing, i will ear winter jacket, otherwise i will wear sunscreen. ” So here we have 3 situations to test for. We can also do this in code using if statements, but now we are going to chain them together.

 

 Chaining if - else constructs

 

Here above in the left, you can see the syntax, we have our first if statement and first boolean expression1, if this is true then we will execute code  block 1. If it is false, then we will go to the else part of the if statement. And the else part as here has a if statement as well. This is the second if statement with second boolean expression 2, if this expression is true then it will execute code block 2. If the boolean expression is false, then it will go to its else part and execute code block 3.

The last code block  in the last else statement will be executed if none of the expressions are evaluated to true so far. You can chain as many as these if / else statements as you want. We can see this situation illustrated in the flow chart to the right. Based on the true / false evaluation of the test boolean expression, true / false path will be taken and corresponding code blocks will be executed.

Chaining if / else example:

Lets take a look at an example of  if / else chaining. Here in this code, we have a method called as calculateNumDays(), whose functionality is that when given a month it will specify how many days the month has and print that out to the console.  

 Chaining if - else constructs 1

 

As we can see, in the first if statement checks if the month is 1, 3, 5, 7, 8, 10, or 12. And if it is, then it prints “There are 31 days in that month”. And if it isnt one of those months, then we go to the else if part, and check if the month is equal to 2. If it is, then we print out “There are 28 days in that month”. If it is not, then we go to the next else if block, and here we check if the month is 4, 6, 9 or 11. If it is then we print “There are 30 days in that month” statement. And if it doesnt match any of those, then it must be an invalid month, so we go to the final else block and we print “Invalid month”.

In our example, we have set the month as 9, it will check the first if and see that its not one of those months, it will check the next if statement and find that its not that as well, and in the next else if block where it finds 9, and hence prints out “There are 30 days in that month”.

We can also see the flow chart illustration of this example down here:

 

 Chaining if - else constructs 2

 

 

Testing equality between Strings:

We saw earlier that we compared values using equality operator to see if they are equal. This works as it should when comparing primitives. But the equality operator works differently when we use it with objects. Lets take a look at an example.

 

Testing equality between Strings

 

So, as we can see we have String s1 as hello and String s2 as hello and String s3 to be new String of value hello. Now we can see in the chart to the right that s1 == s2 in this case is true, but s1 == s3 or s2 == s3 is false. But why is it so? Arent all the Strings new objects having value hello? This is where the difference of the equality operator in terms of the object comparison comes in. When compared between objects, the equality operator actually checks for the object reference equality, that whether both the references are pointing to the same reference. So how do we apply to this situation?

Here is how the above scenario works. When we created the String s1 with a value of hello, and then created a String s2 of the same value hello, the compiler learnt that both the String refernces contain same textual data. So, the compiler created only one object, and made the String reference variables s1 and s2 point to the same object as represented by the memory address 0x99f311 in our example. And when we used a new operator to create a new String object with the value hello in it, the compiler did not reuse the other hello object, but instead created a new hello object as represented by 0x0340009 in our example. The compiler then sets the s3 reference variable to point to this new object.

So in our example, when we compared s1 == s2, the object references as we see from the figure are the same and hence its true. And we got false when we compared the others as we see from the figure that the object references are not equal. What we can know from this is, when the equality operator is used with objects, its not the value that the objects are compared with, but thier references. But then what if we do want to compare the values in the objects? To do that we have to use the equals() method on objects. 

 Testing equality between Strings 1

 

If we want to compare the textual data within s1, s2, and s3 reference variables and not thier references, then we use the equals() method on them. So, you can see the comparison in the table to the right, and we see that when we are comparing the textual data of all these these reference variables, we get true, because all of them have the same value hello.

 

Example:

 Testing equality between Strings 2

 

Here in this example, we see that we have 2 variables namely, name1 and name2, name1 is set to Fred Smith and name2 is set to Joseph Smith. We have a areNamesqual() method, in which we are asking whether name1 and name2 are equal using the equal() method. And as we see, that they are not equal so we go to the else part of the code, hence printing “Different name” to the console.

 

 

3.  Use the switch construct:

So far we have covered one of the branching statements in Java, the if statement. The if statement is the most used and all purpose used statement. But there might be situations when you want to use another type of branching statements called the Switch statement in Java. Switch statement can be used when we need to compare one variable against multiple values and we want a different code block to execute for each value of that variable. This can be done using if statement, but it will get wordy. Ex: If we have a variable called x, and it could contain any of the values from 1 to 10, and we had to execute a different code for different value, then we had to use if / else 10 times. Here we will be repeating the variable x over and over again.

In the switch statement, we dont have to repeat the variable over and over again, but only mention it once, and have different cases for different values this variable might contain, and each case will have its own code block, that will get executed when the value of the variable matches that case . Let’s take a look at the syntax:

 

 Use the switch construct

 

We start with the keyword switch, and in paranthesis we give the variable that we want to compare to the values to, we then have the left curly brackets, and then we list our different cases that we want to match to the variable. So we give the case keyword and then the value that we want to compare with the variable, followed by a colon (:), and then we have the code block we want to be executed for this case, and then we will have an optional break statement. Similarly we repeat the cases for as many values we want to compare to the variable to. In the end we can have an optional default statement with a default code block. The default code block is like an else statement when used with if. This is the block that will be executed if none of the other cases match.

Here we have come across something called a break statement, this statement is required if want to break out of the code block. Example, if the variable in our example matches the literal_value1, then it executes the code_block1 and with the break statement in this block, it exits this code block, and also the switch statement entirely, and continues with the execution of the rest of the program. And suppose we dint have the break statement, we dont break from the switch statement, what happens is a fall through, that is after execution of code_block1, the following cases and thier code blocks are also executed, in this example literal_value2 and default will also get executed. The flow is illustrated in the flow chart to the right.

 

Switch example:

Let’s demonstrate the use of the switch statement for the same example that we considered before of months /days with the if / else constructs. This example is an appropriate use of switch statement i.e., taking one variable and comparing it with multiple values. We can also see the use of fall throughs i.e., not using break statements. The fall throughs are used in place of OR operator with the if statements. We can see in the example, that we have case1: case3: case5 and so on, that means that for all these cases we have a similar code to be executed, in our case for all these cases, the month will have 31 days so we want to print “There are 31 days in that month” statement if its case 1 or case3 or case 5 etc, where 1, 3, 5 are all values to which we compare teh variable month to.

We also have break statement, when we dont want the same code to execute for a different case, for example in our case we want to print “There are 28 days in that month” and not “There are 31 days in that month” if the value of the month is 2. So we have a different case and hence we break out of the first case and not fall through to this case as well. And finally if the month is not equal to any of these values, then its not a valid month, so we have this to print in our default code block of the switch statement.

 

 Switch example

 

In our case, we have month variable set to 9. so in the switch statement, we specify that month is the variable that we want to compare the values to, and here we have different cases for different values of the month. Its not case 1, 3, 5, 7, 8, 10 or 12 so the first case doesnt get executed, we then go the next case which is 2 and it is also not equal to 9 and hence go to the next case which is 4, 6, 9 or 11. In this case we have the value 9 which is indeed the value of the month, so the code block in this case is executed hence printing “There are 30 days in that month” to  the console. And after execution of the code block, we have a break statement, hence breaking out of the code block of this case and also the switch statement in entirety.

 

 

Note:

 

Source: Sun Microsystems Educational Services Course – Using Decision and Looping Constructs with the Java Programming Language WJ-1103A.

 

 

Advertisements
  1. Anonymous
    February 1, 2016 at 4:59 pm

    Thanks for the resource…

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: