Java operators compute values, compare operands, and combine boolean conditions.
Java operators and numeric promotion
Working model
Integer division discards the fractional part. Cast an operand before division when the fraction matters; casting the result afterward cannot recover what was already discarded.
Code
int completedJobs = 7;
int submittedJobs = 10;
double completionRate = (double) completedJobs / submittedJobs;
boolean shouldRetry = submittedJobs > 0 && completionRate < 0.9;
System.out.println(completionRate);
System.out.println(shouldRetry);The output is 0.7 and true. The cast changes the division to floating-point arithmetic. In a general method, check submittedJobs before computing the rate.
Cost and design choices
The && and || operators short-circuit. A guard on the left can prevent an unsafe expression on the right from executing. A single & on boolean operands evaluates both sides.
Promotion before assignment
For byte and short arithmetic, most ordinary numeric operations promote operands to int. A narrowing assignment needs an explicit conversion or a compound-assignment rule, and narrowing can lose information. The destination type does not select the intermediate expression type.
&& and || short-circuit: the right operand may not execute. Avoid hiding required side effects there. Integer division truncates toward zero; switching the final assigned variable to double does not undo division that already happened as int arithmetic.
Connected lessons
Continue with Java conditions and loops, Java Tutorial.
Common Mistakes
Guard against a zero denominator before division. Do not use == to compare string contents. Parentheses are cheap; use them when precedence would force a reader to pause.
Evaluate types before trusting the final value
Two int operands produce int arithmetic unless a conversion changes the operand types first. A long destination does not fix an overflow inside an earlier int addition. Use a widened operand or checked arithmetic when a rejected overflow is the business rule.
Integer division discards the fractional part toward zero. Floating-point division introduces its own rounding and special values; it is not an automatic substitute for decimal money. BigDecimal arithmetic still needs a declared scale and rounding policy at the operation boundary.
Short-circuit boolean operators can skip the right operand. That is useful for a null check followed by a dereference, but it also means a right-hand side effect might never happen. Keep required state changes out of boolean conditions, and parenthesize a compound business rule when precedence could hide its intent.
