Java Reference
In-Depth Information
11. &&
12. ||
13. ? :
14. =, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, |=
15. , (Comma operator)
I will discuss a few of the operators in this section. These operators in Nashorn are
either not in Java or work very differently:
== ) and strict equality operator ( === )
The equality operator (
&& ) and Logical OR ( || ) Operators
The == operator works almost the same way as it works in Java. It checks both
operands for equality, performing the type conversions such as string to number, if
possible. For example, "2" == 2 returns true because the string "2" is converted to the
number 2 and then both operands are equal. The expression 2 == 2 also returns true
because both operands are of type number and they are equal in values. By contrast, the
=== operator checks the types as well as values of both operands for equality. If either of
them are not the same, it returns false . For example, “2” === 2 returns false because
one operand is a string and another is a number. Their types do not match, even though
their values, when converted to either string or number, match.
In Java, the && and || operators work with Boolean operands and they return true or
false . In Nashorn, that is not the case; these operators return one of the operands' value
that can be of any type. In Nashorn, any type of values can be converted to the Boolean
value true or false . Values that can be converted to true are called truthy and values that
can be converted to false are called falsy . I will provide the complete list of truthy and
falsy values in the next section of this chapter.
The && and || operators work with truthy and falsy operands and return one of the
operands value that may not be necessarily a Boolean value. The && and || operators also
known as short circuit operators because they do not evaluate the second operand if the
first operand itself can determine the result.
The && operator returns the first operand if it is falsy. Otherwise, it returns the second
operand. Consider the following statement:
The Logical AND (
var result = true && 120; // Assigns 120 to result
The statement assigns 120 to result . The first operand to && is true, so it evaluates
the second operand and returns it. Consider another statement:
var result = false && 120; // Assigns false to result
The statement assigns false to result. The first operand to && is false , so it does not
evaluate the second operand. It simply returns the first operand.
Search WWH ::




Custom Search