Skip to main content
  1. Tech
  2. Gadgets & Tech
  3. Internet

How to generate a random number from 0 to N in Java

See also

Here are the steps to generate a random number from 0 to N in Java. If you do not want to include zero, then simply add one to the result.

Step 1 - Import the Java Random class.

import java.util.Random;

Step 2 - Create an instance of the Random class.

Random rand = new Random();

Step 3 - Call the nextInt() method.

This nextInt() method accepts an integer parameter. It generates a random number from 0 to that number, but not including that number. For example, this statement generates a random number from 0 to 9:

int num = rand.nextInt(10);

Here is a sample program that prints 100 random numbers from 0 to 9:

import java.util.Random;

public class Test {
public static void main(String[] args) {

Random rand = new Random();
for (int i=0; i < 100; i++) {
int n = rand.nextInt(10);
System.out.println(n);
}

}
}

For more articles, please subscribe, add or follow me here.

Advertisement