CISC-124 20180122 Today we looked at casting, conditionals and loops. Casting Casting is a simple method for converting one type of number to another, when the original type cannot be simply assigned to a variable of the target type. We cast the value to the desired type by putting that type in parentheses just to the left of the value. An example will show exactly what I am talking about: int x; double y = 1.999999999; x = y; // this would fail because we can t assign a double value to an int // variable x = (int) y; // this will work the value of y is converted to an int before // we assign it to x. Note that casting a real number to an integer truncates the number rather than rounds it. So in the example above x ends up with the value 1, even though y is very close to 2. Conditionals Conditionals are statements that let us choose between alternative actions. Of course we all know that the if statement handles this operation, so this section will be more of a review and an exploration of new ideas. In Java, if statements have a couple of slightly different flavours. This material should be very familiar from other languages so I ll just do some examples // example of single operation if { z = c*d; } // example of multiple operations
y = a b; // example of if... if (x == 4) y = a*b; if (x == 5) y = a/b; // example of chained or nested if if (x == 4) y = a*b; if (x == 5) y = a/b; y = a b; // example of chained or nested if with a final // The final is executed if all the boolean // expressions are false We had a very brief discussion about boolean expressions. Boolean expressions can be combinations of simpler expressions, for example if ( x == 3 && z == 4) Here the && means and. We will only execute the if both parts of the boolean expression are true. We can also use & for and (and this operator can also be applied to integers --- more about this later) The difference between && and & for and is that the && uses what we call lazy evaluation. Since the line only executes when both parts of the boolean expression are true, the && starts by evaluating just the first part ( x == 3 ). If this part is false we already know the won t be executed... so we don t need to evaluate the z == 4 part. Using lazy evaluation, Java just evaluates as much of the boolean expression as
it needs to. By contrast, & will always evaluate both sides. Lazy evaluation is a small optimization, but it is also an extremely useful programming tool. Suppose we want to take an action if the value in position 5 of an array is equal to 32. We could try something like this: if (myarray[5] == 32) but if myarray doesn t have a position 5 (ie myarray.length <= 5) then we will get an error. We can guard against this with if (myarray.length > 5) if (myarray[5] == 32) Now the second boolean expression is only tested if the array is long enough. Lazy evaluation simply lets us abbreviate this to if (myarray.length > 5 && myarray[5] == 32) We didn t discuss it in class, but there are two forms of or as well: and. As with the and operators, the first of these ( ) uses lazy evaluation.
There is another form of if that lets us embed the whole thing into a single statement. Consider this y = c*d; Both branches are just an assignment of a new value to the variable y. Java allows us to write this as y = x == 3? a + b : c*d; which looks completely incomprehensible, but everything after y = fits this template: boolean expression? value if the expression is true : value if the expression is false ; If you remember the Collatz sequence program we wrote, we could have replaced if (n%2 == 0) n = n/2; n = 3*n + 1; with n = n%2 == 0? n/2 : 3*n +1; It s shorter but harder to read. My advice: use with caution.
Java also provides a switch statement, which lets us evaluate an expression of almost any kind, then choose different actions based on its value. Here s a simple example: switch (x%6) { } case 0: case 2: default: z = c * d; break; y = a b; z = c + d; break; y = 124; z = 235; break; In this example, x is assumed to be an integer. The expression x%6 will have the value 0, 1, 2, 3, 4, or 5. Java chooses the appropriate instructions to execute. The default case is executed if none of the other cases match the value of the expression. Don t forget to include the break; at the end of each case. Without it, Java just keeps right on going and executes the instructions in the next case too.
Loops We have already seen the While loop, and there isn t much more to say about it. For loops in Java follow the standard C syntax: for (<initial situation> ; <continuation condition> ; <update>) {... } such as for (int i = 0 ; i < anarray.length ; i++) System.out.println(anArray[i]); If you haven t seen i++ before, it is just shorthand for i = i+1 Java also has a for each loop, which lets us iterate over all the values in a collection (for now, just think collection = array ). In a for each loop we define a temporary variable which is assigned each value in the collection, one after the other. for (int val : anarray) System.out.println(val); // assuming anarray is of type int[] produces exactly the same output as the previous for loop. We have seen break in the context of the switch statement. Java actually lets us use break to jump out of any control structure (if, while loop, for loop, etc.) When Java executes a break it jumps to the first line after the end of whatever it is breaking out of. This can be dangerous if over-used because it can make it difficult to follow our program flow, but it can also be very useful if used with caution. In general, you should not have more than one break statement in any control structure except the switch statement. It is entirely possible to code without using any break statements at all.
We also talked about the continue instruction. When executed in a loop, it doesn t break out of the loop but it ends the current iteration and begins the next one. for (int i = 1; i <= 10; i++){ } if (i%4 == 0) continue; System.out.println(i); This will print the values 1 2 3 5 6 7 9 10 The continue instruction is not necessary in any programming language but it can be convenient. You can see how the example just shown could be written without a continue.