How do I generate a random int in Java?
Author: Deron Eriksson
Description: This Java tutorial describes how to generate a random integer in Java.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
The RandomInt class shows how to generate a random int using the nextInt() method of a Random object. It also shows how to generate a random int in a particular range of numbers via nextInt(int n). RandomInt.javapackage test; import java.util.Random; public class RandomInt { public static void main(String[] args) { Random random = new Random(); // generates a random int for (int i = 0; i < 10; i++) { anyRandomInt(random); } System.out.println(); // generates a random int in a range from low int to high int for (int i = 0; i < 10; i++) { anyRandomIntRange(random, 1, 5); } } public static void anyRandomInt(Random random) { int randomInt = random.nextInt(); System.out.println("random integer:" + randomInt); } public static void anyRandomIntRange(Random random, int low, int high) { int randomInt = random.nextInt(high) + low; System.out.println("random integer from " + low + " to " + high + ":" + randomInt); } } The output of executing the RandomInt class is shown here: random integer:-825420979 random integer:-1025830639 random integer:1004593785 random integer:1171042605 random integer:780283973 random integer:-450373878 random integer:-636417266 random integer:1017801497 random integer:1000679011 random integer:2147196241 random integer from 1 to 5:2 random integer from 1 to 5:5 random integer from 1 to 5:2 random integer from 1 to 5:2 random integer from 1 to 5:4 random integer from 1 to 5:5 random integer from 1 to 5:1 random integer from 1 to 5:3 random integer from 1 to 5:5 random integer from 1 to 5:3 It should be noted that the int value that is returned from nextInt() and nextInt(int n) is a pseudorandom, uniformly distributed int value. |