Arithmetic on int constants overflows before the result is widened
What it finds
long year = 1000 * 60 * 60 * 24 * 365; is 1471228928, not 31536000000: the product of int literals is computed as an int and overflows before it is widened. Writing the first factor as a long, 1000L, makes the whole product a long.
Reported are sums, differences and products of int literals whose value does not fit in an int, where the result becomes a long, float or double: as the value of a variable or assignment of such a type, in a cast to one, returned from a method that returns one, or as an operand next to one. An overflowing constant that stays an int, as in hash functions, is left alone. The fix makes the first literal a long, which changes the value, so it is offered as unsafe.
From the rule's source, constant_overflow.rs.
class Durations { static final long YEAR = 1000 * 60 * 60 * 24 * 365;tx0 reports: 1000 * 60 * 60 * 24 * 365 overflows int static final long YEAR_LONG = 1000L * 60 * 60 * 24 * 365; static final long DAY = 1000 * 60 * 60 * 24; static final int HASH = 0x9E3779B9 * 31; static final double BIG = 65536 * 65536;tx0 reports: 65536 * 65536 overflows int long nanos(long start) { long a = start + 3_000_000 * 1_000;tx0 reports: 3_000_000 * 1_000 overflows int long b = (long) (2_000_000_000 + 2_000_000_000);tx0 reports: overflows int String c = "" + 65536 * 65536; return a + b + c.length(); } long year() { return 365 * 24 * 60 * 60 * 1000;tx0 reports: overflows int }} Turn it on, off or suppress it
The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:
[rules]
"tx0/java:constant-overflow" = "off"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:constant-overflow] reason="..."tx0 explain tx0/java:constant-overflow shows the same in the terminal. Found a false positive? Report it.