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.
