devxlogo

Generate Random Numbers in Java

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 andhttp://java.sun.com/people/linden/faq_b2.html#Core

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist