Simple Random Number Example in Java

Random random = new Random();
int r = random.nextInt(10);

The above will generate random number between 0 (included) and 10 (excluded)

Another one is using Math.random()

int randomInt = (int)(10.0 * Math.random());

The above will generate random number between 0 (included) and 10 (excluded) too.

java.util.Random  by default generates random numbers in with range of integers in Java which is -2^31 to 2^31-1, which consists both positive and negative  integers.

Math.random() code will return random numbers which are greater than or equal to 0.0 and less than 1.0. java.util.Random class provides method nextDouble() which can return uniformly distributed pseudo random double values between 0.0 and 1.0.

java.util.Random method nextBoolean() to generate random boolean values in Java.

java.util.Random class has support for generating random integers, longs, float, double and boolean while Math.random() only returns random double values greater than or equal to 0.0 and less than 1.0.

You can not change seed for generating random numbers in case of Math.random(), which is created at first time any one call this method. This method is also synchronized to allow proper use in multithreaded environment, but that can lead to contention, when number of thread grows. You can use ThreadLocalRandom from JDK 1.7 for better performance, if you need to create random numbers simultaneously in multiple threads.


Comments

Popular posts from this blog

Check MySQL query history from command line