The analyzer has detected an arithmetic operation that may result in an integer overflow.
The example:
private static long parseHumanLong(String str) {
char tail = str.charAt(str.length() - 1);
long base = 1;
switch (tail) {
case 't':
base *= 1000 * 1000 * 1000 * 1000;
break;
case 'b':
base *= 1000 * 1000 * 1000;
break;
case 'm':
base *= 1000 * 1000;
break;
case 'k':
base *= 1000;
break;
default:
}
if (base != 1) {
str = str.substring(0, str.length() - 1);
}
return Long.parseLong(str) * base;
}
This method reads numbers and converts their suffixes to:
t – trillion;b – billion;m – million;k – thousand.If the 1m string is passed to the method, it is expected to be converted to the long variable with the 1_000_000 value.
When calculating trillions in the 1000 * 1000 * 1000 * 1000 expression, the multiplication is performed within the int range, but the resulting number exceeds the maximum value for the int type. This results in the overflow and incorrect result.
To evaluate the expression correctly, explicitly specify the Long type for it.
base *= 1000L * 1000 * 1000 * 1000;
This diagnostic is classified as:
|
Was this page helpful?
Your message has been sent. We will email you at
If you do not see the email in your inbox, please check if it is filtered to one of the following folders:
Take
a chance!