Java Reference
In-Depth Information
int i = 10;
int j = 15;
boolean b = (i > 5 && j > 10); // Assigns true to b
In this expression,
i > 5
is evaluated first and it returns
true
. Because the left hand operand evaluated to
true
,
the right hand operand was also evaluated. The right-hand operand,
j > 10
, is evaluated, which also returns
true
.
Now, the expression is reduced to
true && true
. Because both operands are
true
, the final result is
true
.
Consider another example.
int i = 10;
int j = 15;
boolean b = (i > 20 && j > 10); // Assigns false to b
The expression
i > 20
returns
false
. The expression reduces to
false && j > 10
. Because the left-hand
operand is
false
, the right-hand operand,
j > 10
, is not evaluated and
&&
returns
false
. However, there is no way to
prove in the above example that the right-hand operand, which is
j > 10
, was not evaluated.
Let's consider another example to prove this point. I have already discussed the assignment operator (=). If
num
is
a variable of type
int
,
num = 10
returns a value 10.
int num = 10;
boolean b = ((num = 50) > 5); // Assigns true to b
Note the use of parentheses in this example. In the expression
((num = 50) > 5)
, the expression,
(num = 50)
,
is executed first. It assigns
50
to
num
and returns
50
, reducing the expression to
(50 > 5)
, which in turn returns
true
. If
you use the value of
num
after the expression
num = 50
is executed, its value will be
50
.
Keeping this point in mind, consider the following snippet of code:
int i = 10;
int j = 10;
boolean b = (i > 5 && ((j = 20) > 15));
System.out.println("b = " + b);
System.out.println("i = " + i);
System.out.println("j = " + j);
This piece of code will print
b = true
i = 10
j = 20
Because the left-hand operand, which is
i > 5
, evaluated to
true
, the right-hand of operand
((j = 20) > 15)
was evaluated and the variable
j
was assigned a value
20
. If you change the above piece of code so the left-hand
operand evaluates to
false
, the right-hand operand would not be evaluated and the value of
j
will remain
10
. The
changed piece of code is as follows:
int i = 10;
int j = 10;
// ((j = 20) > 5) is not evaluated because i > 25 returns false
boolean b = (i > 25 && ((j = 20) > 15));