Java Reference
In-Depth Information
15
if
(number %
2
==
0
|| number %
3
==
0
)
16 System.out.println(number +
" is divisible by 2 or 3."
);
17
18
if
(number %
2
==
0
^ number %
3
==
0
)
19 System.out.println(number +
20
or
exclusive or
" is divisible by 2 or 3, but not both."
);
21 }
22 }
Enter an integer: 4
4 is divisible by 2 or 3.
4 is divisible by 2 or 3, but not both.
Enter an integer: 18
18 is divisible by 2 and 3.
18 is divisible by 2 or 3.
(number % 2 == 0 && number % 3 == 0)
(line 12) checks whether the number is
divisible by both
2
and
3
.
(number % 2 == 0 || number % 3 == 0)
(line 15) checks
whether the number is divisible by
2
or by
3
.
(number % 2 == 0 ^ number % 3 == 0)
(line
18) checks whether the number is divisible by
2
or
3
, but not both.
Caution
In mathematics, the expression
1
<= numberOfDaysInAMonth <=
31
is correct. However, it is incorrect in Java, because
1 <= numberOfDaysInAMonth
is
evaluated to a
boolean
value, which cannot be compared with
31
. Here, two operands
(a
boolean
value and a numeric value) are
incompatible
. The correct expression in
Java is
incompatible operands
(
1
<= numberOfDaysInAMonth) && (numberOfDaysInAMonth <=
31
)
Note
De Morgan's law, named after Indian-born British mathematician and logician Augustus
De Morgan (1806-1871), can be used to simplify Boolean expressions. The law states:
De Morgan's law
!(condition1 && condition2) is the same as
!condition1 || !condition2
!(condition1 || condition2) is the same as
!condition1 && !condition2
For example,
! (number %
2
==
0
&& number %
3
==
0
)
can be simplified using an equivalent expression:
(number %
2
!=
0
|| number %
3
!=
0
)
As another example,
!(number ==
2
|| number ==
3
)
is better written as
number !=
2
&& number !=
3
Search WWH ::
Custom Search