Checker AbsOfRandom   as of Julia version 2.5.0 (built on 4 Jul 2018)

belongs to group Basic

Identify computations of absolute values of random integers


By computing the absolute value of a random integral number, one might actually yield a negative number, if Math.abs() is used. For instance, System.out.println(Math.abs(Integer.MIN_VALUE)) would actually print the negative value -2147483648. As a consequence, this might result in unexpected or erroneous computations.

Action: Check, explicitly, for the minimal integral value, before computing the absolute value.

Examples


Consider the following program:

import java.util.Random;

public class AbsOfRandom {

  public static void main(String[] args) {
    Random r = new Random();
    int i = r.nextInt();
    i = Math.abs(i);

    System.out.println(i);
  }
}

This checker issues the following warning:

AbsOfRandom.java:8: [AbsOfRandom: AbsOfRandomWarning] The absolute value of a random integral value might actually be negative

since i might actually contain a negative value when it is print, at line 10, which is probably not the intent of the programmer.

In this example, the programmer should check for the minimum integral value explicitly and behave accordingly, as in the following example:

    Random r = new Random();
    int i = r.nextInt();
    if (i == Integer.MIN_VALUE)
      i = 0; // any non-negative value would do
    else if (i < 0)
      i = -i;

    System.out.println(i);