java left logo
java middle logo
java right logo
 

Home arrow Java SE Tips arrow java.util arrow How to generate a random number
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 4091
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
How to generate a random number E-mail
User Rating: / 128
PoorBest 

This Java tip illustrates a method of generating a random number. Developer may use this random generation in their applications such as in a quiz application for picking random questions from a set of questions in a databse.

Random rand = new Random();

// No. 1 Random integers
int randnum = rand.nextInt();
// More random integers may be generated by 
// iteratively executing previous line...

// No. 2 Generating random integers from 0 to 10
int n = 10;
randnum = rand.nextInt(n+1);

// No. 3 Generating random bytes
byte[] bytes = new byte[5];
rand.nextBytes(bytes);

// No. 4 Other primitive types
boolean b = rand.nextBoolean();
long l = rand.nextLong();
float f = rand.nextFloat();     // 0.0 <= f < 1.0
double d = rand.nextDouble();   // 0.0 <= d < 1.0


// Create two random number generators with the same seed
long seed = rand.nextLong();
rand = new Random(seed);
Random rand2 = new Random(seed);


 Related Tips

 
< Prev   Next >
 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.