Tuesday 26 May 2009

Chunk 11 - Ternary operator (Draft)

Ternary operator

In Chapter 9 you learned to use the basic Processing operators and Chapter 10 introduced to Processing’s conditional structures. In this chapter we will take a look at the ternary operator, an operation of arity three, that is, an operation that takes three arguments, a boolean value and two statements.

It is used as follows: variable = (condition)? value if true : value if false;

If the condition is true, the first value is assigned to the variable otherwise the second value is assigned to the variable.

The ternary operator is also referred to as conditional operator as it lets you assign a value to a variable based on a boolean decision; you might think of it as a short-hand alternative to an if-then-else statement.

The ternary operator is derived from early programming languages where storage and memory space was still an issue and this is why it seems a little cryptic and sometimes confusing at first sight . Programmers often need some time to get used to it and some even choose not to use it at all opting for the more verbose if-then-else syntax.

Let us consider the following example:

int aNumber = 7;

String aMessage;

if (aNumber%2 == 0 )

{

aMessage="The number is even";

}

else

{

aMessage="The number is odd";

}

println(aMessage);

Executing the code above will print “The number is odd” at the bottom of the Processing window as the condition (7%2 == 0) is not met. 7 modulo 2 is equal to 1 thus the condition is false and the code in the else statement is executed.

The equivalent of this statement using the ternary operator looks like the following:

int aNumber = 7;

String aMessage = (aNumber%2 == 0 ) ? "The number is even" : "The number is odd";

println (aMessage);


First, the condition is tested, in our case, is the modulo 2 of aNumber equal to 0 ? If the condition is true then the value before the “:” is returned and assigned to the variable aMessage otherwise the value after the “:” is returned and assigned to the variable aMessage.

In our case, the condition (7%2 == 0) evaluates to false as 7 modulo 2 is equal to 1 thus the String “The number is odd” is returned and assigned to aMessage which is then printed at the bottom of the Processing window.

The difference between the ternary operator and the if-then-else statement is that the if-then-else syntax executes a block of code based on the condition it evaluates and the ternary or conditional operator is an expression which returns a value based on the condition it evaluates.

The advantage of the ternary operator is that it let’s you assign a value to a variable based on a condition with a single line of code; however if you find yourself having trouble in understanding its syntax you can still use the more long-winded if-then-else statement to achieve the same thing.

No comments: