Java Reference
In-Depth Information
The
||
operator returns the first operand if it is truthy. Otherwise, it returns the
second operand. Consider the following statement:
var result = true || 120; // Assigns true to result
The statement assigns true to
result
. The first operand to
||
is
true
, so it returns the
first operand. Consider another statement:
var result = false || 120; // Assigns 120 to result
The statement assigns
120
to result. The first operand to
||
is
false
, so it evaluates
the second operand and returns its value.
Type Conversion
Things that are not allowed in Java are allowed in Nashorn, such as using a number or
a string where a Boolean value is expected. Consider the following snippet of code in
Nashorn, which adds a Boolean value to a number:
var n1 = true + 120;
var n2 = false + 120;
print("n1 = " + n1);
print("n2 = " + n2);
n1 = 121
n2 = 120
The expression
true + 120
is not allowed in Java. However, it is allowed in Nashorn.
Notice that Nashorn implicitly converts
true
is to the number 1 and
false
to the number
0. There are a lot of implicit conversions performed by Nashorn. You need to have a
good understanding of them to write a bug-free code in Nashorn. The following sections
explain those conversions in detail.
To Boolean Conversion
In Nashorn, you can use a truthy or falsy value whenever a Boolean value is required. For
example, the condition in an
if
statement does not need to yield a Boolean value. It can
be any truthy or falsy value. Table
4-6
lists the types of values and their corresponding
converted Boolean values.
Search WWH ::
Custom Search