Friday, May 17, 2013

How to Generate Random Numbers in Java between Range - Example Tutorial

In software development and programming world we often needs to generate random numbers, some time random integers in a range e.g. 1 to 100 etc. Thankfully, Random number generation in Java is easy as Java API provides good support for random numbers via java.util.Random class, Math.random() utility method and recently ThreadLocalRandom class in Java 7, along with more popular features like String in Switch and ARM blocks. While random() method seems most convenient way of generating randoms in Java it only return random doubles, on the other hand by using Random,  you can generate pseudo-random integer, floating point numbers e.g. double and even random boolean values. In this article Java tutorial, we will see how to generate random numbers in Java, examples to generating random integers and real numbers, and random numbers within a range e.g. between 1 to 6. we will also explore difference between Math.random() and java.util.Random class in Java.


Random Numbers in Java with Example

As I said earlier Random class in Java is used to create random numbers. you can create instance of java.util.Random class by default seed or you can  provide your own seed by calling special constructor of this class, Random(long seed). This class provides methods to return random integers, doubles, float and  boolean values. here is an simple example of generating random numbers in Java using java.util.Random class:
Random random = new Random();
      
 for(int i =0; i<5; i++){
      int randomInteger = random.nextInt();
      System.out.println("Random Integer in Java: " + randomInteger);
 }

Output:
Random Integer in Java: -1194538938
Random Integer in Java: -973476571
Random Integer in Java: -1283186469
Random Integer in Java: 1176677327
Random Integer in Java: 265551019

You can see 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. By the way, you can also use Math.random() to create random numbers, here is an example of generating random numbers using Math.random() in Java:  
for(int i =0; i<3; i++){
     double randomDouble = Math.random();
     System.out.println("Random Number in Java: " + randomDouble);
}

Output:
Random Number in Java: 0.767752638941705
Random Number in Java: 0.482517390182052
Random Number in Java: 0.28243911879792283

As you can see Math.random() code will return random numbers which are greater than or equal to 0.0 and less than 1.0


How to generate random Integers in Java
If you want to create random numbers in the range of integers in Java than best is to use random.nextInt() method it will return all integers with equal probability. You can also use Math.random() method to first create random number as double and than scale that number into int later. So you can create random integers in two step process.

Generating random Double in Java
Similar to random integers in Java, java.util.Random class provides method nextDouble() which can return uniformly distributed pseudo random double values between 0.0 and 1.0.

Generating random Boolean values in Java
Use java.util.Random method nextBoolean() to generate random boolean values in Java. here is an example of generating boolean values randomly in Java:

Generating random number in a range in Java – between two numbers

You can use both Math.random() and java.util.Random to generate random numbers between a range. Most of the time we need Integer values and since Math.random() return a floating point number, precisely a double value,  we need to change that into an integer by casting it. Here is a Java code example of using both Random class and random() method for generating random number in range: 
for(int i =0; i<3; i++){
    int randomInteger = random.nextInt(10);
    System.out.println("pseudo random int in a range : " + randomInteger);
}

Output:
pseudo random int in a range : 7
pseudo random int in a range : 1
pseudo random int in a range : 3

Random.nextInt(10) method returns random numbers between 0 (included) and 10 (excluded)


Random number between 0 and 10 – Java Example
Here is a code snippet, which can be used to generate random numbers in a range between 0  to 10, where 0 is inclusive and 10 is exclusive. This code uses Math.random() method, which returns pseudo-random number in a range 0.0 to 1.0, where later is exclusive, by multiplying output with and then type casting into int, we can generate random integers in any range. If you need pseudo random number between 1 to 100, you can simply multiply output of random() method with 100 and then cast it into int for integer result. 
for(int i =0; i<3; i++){
      int randomInt = (int)(10.0 * Math.random());
      System.out.println("pseudo random int between 1 and 10 : " + randomInt );
}

Output:
pseudo random int between 1 and 10 : 4
pseudo random int between 1 and 10 : 0
pseudo random int between 1 and 10 : 2


Difference between Math.random() and java.util.Random class in Java

Though you can generate random numbers by using either ways in Java , there is slight difference in terms of usage and behavior between Math.random() method and java.util.Random class:

1) In order to generate random numbers, these are actually pseudo random numbers, by using java.util.Random class you need to create an instance of this class, while in case of Math.random() method, instance of Random number generator is created, when you first call it. This pseudo random number generator is equivalent to new Random(), and only used exclusively here.

2) 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.

3) 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. By the way, you can also use ThreadLocalRandom from JDK 1.7 for better performance, it you need to create random numbers simultaneously in multiple threads.

4) Math.random() is more of utility method while java.util.Random is actual random number generator class, which provides range of method to generate numbers in different data types.

Summary

1. Random numbers in Java can be generated using either java.util.Random , ThreadLocalRandom class or by using Math.random() method. ThreadLocalRandom is only available from Java 7.

2. Random class can generate random integer, double, float and booleans.

3. Random numbers generated are pseudo random,  created with equal probabilities and in attempt of uniformly distribution. So Random.nextInteger() can return any random integer number between 2^32 values with equal probability.

4. Math.random() only generates double value greater than or equal to 0.0 and less than 1.0.

5. Math.random() is a thread-safe method and can be called form multiple threads but its good idea to have separate random number  generators for separate thread to reduce contention. ThreadLocalRandom from Java 1.7 could be another choice if you are sharing your Random number generator among multiple threads.

6. Though Random number can accept a long seed(64 bits) it only uses 48 bits for generating random numbers.

7. Random is not a final class and you can extends it to implement your own algorithm or to use all 64 bits of seed.

8. Easy and convenient way to create random numbers in java is Math.random() method.

That’s all on How to generate random numbers in Java. We have seen examples of generating random integers in a range say 1 to 10, which is quite common and very useful as well. You can even use ThreadLocalRandom from Java 1.7, which is a Random number generator isolated to a particular thread, which reduces contention, if used in multi-threaded environment.  You can even employ the method here to generate random number in a range or without repetition by adding those extra logic on top of this.

1 comment :

parthi ban said...

/** USE THIS
AUTHOR: parthy
**/

Random r = new Random();
int ii = r.nextInt(100000-50000)+50000;
String k = Integer.toString(ii);
System.out.println(k);

// want to learn more about java: http://parthhy.wordpress.com //

Post a Comment