Random number generator in Java


To generate random numbers in Java, use.

import java.util.Random;

Now, take Random class and create an object.

Random num = new Random();

Now, in a loop, use the nextInt() method since it is used to get the next random integer value. You can also set a range, like for 0 to 20, write it as.

nextInt( 20 );

Let us see the complete example wherein the range is 1 to 10.

Example

 Live Demo

import java.util.Random;
public class Demo {
   public static void main( String args[] ) {
      Random num = new Random();
      int res;
      for ( int i = 1; i <= 5; i++ ) {
         res = 1 + num.nextInt( 10 );
         System.out.printf( "%d ", res );
      }
   }
}

Output

4 5 9 6 9

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements