Java Reference
In-Depth Information
Building Boolean Expressions
You can combine two Boolean expressions using the “and” operator, which is spelled
&&
in Java. For example, the following Boolean expression is
true
provided
number
is
greater than 2 and
number
is less than 7:
&&
means
“and”
(number > 2) && (number < 7)
When two Boolean expressions are connected using
&&,
the entire expression is
true
,
provided both of the smaller Boolean expressions are
true
; otherwise, the entire
expression is
false
.
The “and” Operator
&&
You can form a more elaborate Boolean expression by combining two simpler Boolean
expressions using the “and” operator
&&
.
SYNTAX (FOR A BOOLEAN EXPRESSION USING
&&
)
(
Boolean_Exp_1
) && (
Boolean_Exp_2
)
EXAMPLE (WITHIN AN
if-else
STATEMENT)
if
( (score > 0) && (score < 10) )
System.out.println("score is between 0 and 10.");
else
System.out.println("score is not between 0 and 10.");
If the value of
score
is greater than 0 and the value of
score
is also less than 10, then the first
System.out.println
statement is executed; otherwise, the second
System.out.println
statement is executed.
||
means “or”
You can also combine two Boolean expressions using the “or” operator, which is
spelled
||
in Java. For example, the following is
true
provided
count
is less than 3 or
count
is greater than 12:
(count < 3) || (count > 12)
When two Boolean expressions are connected using
||
, the entire expression is
true
,
provided that one or both of the smaller Boolean expressions are
true
; otherwise, the
entire expression is
false
.
You can negate any Boolean expression using the
!
operator. If you want to negate
a Boolean expression, place the expression in parentheses and place the
!
operator in
front of it. For example,
!(savings < debt)
means “savings is not less than debt.”
The
!
operator can usually be avoided. For example,
!(savings < debt)
is equivalent to
savings >= debt
. In some cases, you can safely omit the parentheses,
but the parentheses never do any harm. The exact details on omitting parentheses are
given in the subsection entitled “Precedence and Associativity Rules.”