|
How to generate a Random Number in Java
The following example shows generating a random int, long, float, double etc. in Java.
|
package com.bethecoder.articles.basics.random;
import java.util.Arrays;
import java.util.Random;
public class RandomTest {
/**
* @param args
*/
public static void main(String[] args) {
Random rand = new Random();
System.out.println(rand.nextBoolean());
System.out.println(rand.nextDouble());
System.out.println(rand.nextFloat());
System.out.println(rand.nextGaussian());
System.out.println(rand.nextInt());
System.out.println(rand.nextLong());
System.out.println(rand.nextInt(17291729));
byte [] bytes = new byte[12];
rand.nextBytes(bytes);
System.out.println(Arrays.toString(bytes));
}
}
|
| |
It gives the following output,
true
0.9208379651206896
0.12319869
1.0118488718946061
2033383028
-6555723401767464176
11676418
[58, -116, 78, 126, 71, 31, 117, -101, 80, 0, 67, -10]
|
package com.bethecoder.articles.basics.random;
public class RandomTest2 {
/**
* @param args
*/
public static void main(String[] args) {
//Returns a value between 0 and 1
double value = Math.random();
System.out.println(value);
//Random number between 0 and 1729
int n = (int) (Math.random() * 1729);
System.out.println(n);
}
}
|
| |
It gives the following output,
0.14997177505825
488
|
|