Home  >  Core Java

java.util.Random Example in Java

By Arvind Rai, August 24, 2013
java.util.Random is an utility provided by java to generate pseudorandom numbers and boolean values. Random number has methods as nextInt, nextDouble, nextLong etc. Random.setSeed can be used when two random object needs to generate same random number at a time. Find the example to use Random class.

RandomDemo.java
package com.concretepage.util;
import java.util.Random;
public class RandomDemo {
    public static void main(String[] args) {
        Random random = new Random();
        //Random number form 0 to 10
        System.out.println("Random integer number from 0 to 10 ...");
        for(int i=0; i<10;i++){
            int j = random.nextInt(10);
            System.out.println(j);
        }
        
        //Random boolean value
        System.out.println("Random boolean values...");
        for(int i=0;i<5;i++){
            System.out.println(random.nextBoolean());
        }
    }
}
 
output:
Output
Random integer number from 0 to 10 ...
7
6
4
2
2
5
6
1
2
9
Random boolean values...
false
true
false
true
false
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us