The logical && operator combines boolean conditions and returns true only when both operands are true. Its most dangerous mistakes arise when it is confused with || or read without considering precedence. section 2.2.1 section 2.8
Precedence can defeat a guard
Because && has higher precedence than ||, this condition groups as (index >= 0 && str.charAt(index) == ' ') || str.charAt(index) == '\t'. The second charAt call can therefore receive a negative index. Parenthesize the OR alternatives: index >= 0 && (str.charAt(index) == ' ' || str.charAt(index) == '\t'). A named helper such as isWhitespace can make the condition clearer. section 2.2.1
AND cannot express an outside range
A check such as byteValue < 0 && byteValue > 255 can never be true: no value is simultaneously below 0 and above 255. To reject values outside the range, use byteValue < 0 || byteValue > 255. The same distinction matters when checking that a character is outside an allowed interval. section 2.8
Negating a compound condition requires changing both the operators and the individual terms. De Morgan’s laws give !(a || b) == !a && !b and !(a && b) == !a || !b. Removing parentheses while changing only one part can cause every input to follow the wrong branch. section 2.8
Reduce logical-AND mistakes with these practices:
- Parenthesize expressions that combine && and ||, even when precedence technically gives the intended result. section 2.2.1
- Split complex conditions into nested if statements or named predicates when the grouping is difficult to verify. section 2.2.1
- Test boundary values and contradictory conditions; static analyzers may detect some cases, but they cannot replace reasoning about intended logic. section 2.8
Table 2.2 Comparison of logical && and multiplication
|
Logical
&&
|
Multiplication
|
|---|---|
false && false == false
|
0 * 0 == 0
|
false && true == false
|
0 * 1 == 0
|
true && false == false
|
1 * 0 == 0
|
true && true == true
|
1 * 1 == 1
|
Compare logical && with multiplication to remember that false behaves like 0 and true like 1 in its truth table. section 2.2.1






