Friday 1 November 2013

The Conditional and Concatent Operator




The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

&& Conditional-AND
|| Conditional-OR
The following program, ConditionalDemo1, tests these operators:

class ConditionalDemo1 {
    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        if((value1 == 1) && (value2 == 2))
            System.out.println("value1 is 1 AND value2 is 2");
        if((value1 == 1) || (value2 == 1))
            System.out.println("value1 is 1 OR value2 is 1");
    }
}
Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

The following program, ConditionalDemo2, tests the ?: operator:
class ConditionalDemo2 {
    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        int result;
        boolean someCondition = true;
        result = someCondition ? value1 : value2;

        System.out.println(result);
    }
}
Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).
<c:set> for this.

<c:set var="promoPrice" value="4.67" />
<c:set var="promoPriceString" value="ONLY $${promoPrice}" />
<p>${not empty promoPrice ? promoPriceString : 'FREE'}</p>
In this particular case, another way is to split the expression in two parts:

<c:set var="promoPrice" value="4.67" />
<p>${not empty promoPrice ? 'ONLY $' : 'FREE'}${promoPrice}</p>
If ${promoPrice} is null or empty, it won't be printed anyway.

In the upcoming EL 3.0 (JSR-341, part of Java EE 7), a new string concatenation operator & will be available. See also EL 3.0 spec - Operators. Your specific use case can then be solved as follows:

<p>${(promoPrice != null) ? ("ONLY" & $${

www.mindqonline.com

No comments:

Post a Comment