Java Random Integer

Java Random Integer

It is required random numbers in many applications like lotteries, testing programs, pick up names from a group etc. It is permitted to generate Java random integer, random double with the class java.util.Random.

Random class can generate three variations of random numbers.

1. At different times of execution, different random numbers
2. At different times of execution, same set of random numbers
3. Random numbers within a range (1 to given number or between two given numbers)

Following Example on Java Random Integer illustrates all the above three.

Java Random IntegerOutput Screenshot on Java Random Integer

rand1.nextInt() generate both positive and negative numbers. If wanted only positive, use Math.abs(rand1.nextInt());
nextInt(100): Prints 1 to 100. Pass the given number to the parameter of nextInt() method.
Getting random numbers between two numbers is a logical code self-explanatory.

For more detailed explanation with class signature and where to use which variation etc., see this link: class Random.

Leave a Reply

Your email address will not be published. Required fields are marked *