Wednesday 29 August 2012

Boolean and Conditional Statements - Apex

Declare a variable with the Boolean data type when it should have a true or false value. You've already encountered Boolean values in the previous lesson as return values: the endsWith method returns a Boolean value and the  == and != String operators return a Boolean value based on the result of the string comparison. You can also simple create a variable and assign it a value:
Boolean isLeapYear = true;
There are a number of standard operators on Booleans. The negation operator ! returns true if its argument is false, and vice versa. The && operator returns a logicalAND, and the || operator a logical OR. For example, all of these statements evaluate to false:
Boolean iAmFalse = !true;
Boolean iAmFalse2 = iAmFalse && true;
Boolean iAmFalse3 = iAmFalse || false;
Use the if statement to execute logic conditionally, depending on the value of a Boolean:
Boolean isLeapYear = true;
if (isLeapYear) {
    System.debug ('It\'s a leap year!');
} else {
    System.debug ('Not a leap year.');
}
Escape sequences: In the previous example, notice that there is a backslash (\) character inside the argument of the first System.debug statement: 'It\'s a leap year!'. This is because the sentence contains a single quote. But since single quotes have a special meaning in Apex—they enclose String values— you can’t use them inside a String value unless you escape them by prepending a backslash (\) character for each single quote. This way, Apex knows not to treat the single quote character as the end marker of a String but as a character value within the String. Like the single quote escape sequence, Apex provides additional escape sequences that represent special characters inside a String and they are: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash).
In the previous example, the else part is optional. The blocks, the statements within the curly braces, can contain any number of statements that are executed when the condition is met. For example, this will generate the output of the two debug statements:
if ('Hello'.endsWith('o')) {
    System.debug('me');
    System.debug('me too!');
}
If a block only contains a single statement, the curly braces can be optionally omitted. For example:
if (4 > 2) System.debug ('Yep, 4 is greater than 2');
There is also a ternary conditional operation, which acts as short hand for an if-then-else statement. The syntax is as follows:
x ? y : z
and can be read as: if x, a Boolean, is true, then the result is y; otherwise it is z. Execute the following:
Boolean isIt = true;
String x = 'You are  ' + (isIt ?  'great' : 'small');
System.debug(x);
The resulting string has the value 'You are great'.

No comments:

Post a Comment