Random number generator in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 13-Nov-2018 05:35:01
Advertisements