I'd like to know that if I try to get a random integer using the following method, should it return negative value?
int value = new Random().nextInt(bound);
I'd like to know that if I try to get a random integer using the following method, should it return negative value?
int value = new Random().nextInt(bound);
No, Random().nextInt(bound)
only produces positive numbers from 0 to the number you have specified. If you want an negative number, you will need to multiply the random number by -1.
int number = new Random().nextInt(bound) * -1;
Random().nextInt()
on the other hand can return you a negative number.
If you need mix of positive and negative you could use something like this:
int number = new Random().nextInt(bound);
if (number % 2 == 0) {
number *= -1;
}
If you use Random class from java.util package you are supposed to mention the type of numbers you expect, meanwhile setting an upperbound. Your answer will be anywhere from 0 to less than upperbound. nextInt() from Random class returns and integer value from 0 to the argument-1. Similarly we can use methods as nextDouble and nextLong(). The values returned are always positive or zero. Now if you need negative values we can randomly set a counter for negative numbers. Say, one another integer value which is randomly generated and checking it is odd/even to negate the number.
The other approach is to use Math.random() method. This method returns a number equal to or greater than 0 and less than 1. We can use typecasting for integer random values else by default we get double values. P.S. Check the oracle documentation for better understanding of these classes and methods.