Question

I'm trying to generate the random number which is stored and I need to return the string value.

Here is My method:

public String generateRand() {
    java.util.Random rand = new java.util.Random(System.currentTimeMillis());
    String rnd = "" + Math.abs(rand.nextInt()) + "" +
       Math.abs(System.currentTimeMillis());
    return rnd;
}

The Findbugs plugin of Jenkins is warning me that there is Bad attempt to compute absolute value of signed random integer.

This code generates a random signed integer and then computes the absolute value of that random integer. If the number returned by the random number generator is Integer.MIN_VALUE, then the result will be negative as well, since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE. Same problem arised for long values as well.

What is the best way to to compute absolute value of signed random integer?

Was it helpful?

Solution

Use rand.nextInt(Integer.MAX_VALUE); instead of Math.abs(rand.nextInt())

OTHER TIPS

Consider a byte. Its value ranges from -128 to 127. Say your byte has a value of -100, then Math.abs(-100) will give you 100. But what if the value of your byte is -128? You cannot represent 128 as a byte, since the maximum value it can represent is 127. So Math.abs() simply returns the negative parameter, unchanged.

The moral of the story is that it's possible for Math.abs() to return a negative value.

Sounds like the plugin recognizes the specific case, Math.abs(rand.nextInt()). So write something different.

The plug-in knows that that case doesn't always work: It knows that rand.nextInt() can sometimes return Integer.MIN_VALUE, and it knows that Math.abs(Integer.MIN_VALUE) can not be computed. I would think about writing my own random number function that does not ever return Integer.MIN_VALUE.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top