Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Feb 18, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Generate Random Numbers in Java

You can generate Random numbers in Java using the Random class available in java.util package. The following is a code which generates Random numbers between 0 and 100:
import java.util.Random ;

public class RandomGenerator {

   public static void main(String args[]){
	int value = 101;
	Random  rm = new Random();
	// rm.nextInt() can return Integer.MIN_VALUE (i.e -2147483648) and  
Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE
  int randInt = (rm.nextInt() & Integer.MAX_VALUE) % value;
	System.out.println( " Random Number : " + randInt );

You can define seed value using setSeed(long seedValue). There is also get random boolean using nextBoolean() method .

For complete listing visit: http://java.sun.com/products/jdk/1.2/docs/api/java/util/Random.html

Editor's Note: The text has been changed from the original. Thanks to Kevin Mukhar for pointing out a bug in the original version and for suggesting the following links:
http://www.mindprod.com/gotchas.html#RANDOM and http://java.sun.com/people/linden/faq_b2.html#Core
Nilesh Shah
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date