Java random number generation
This article demonstrates how to generate random numbers in Java. The code examples helps you to understand the details.
Tutorial info:
| Name: | Java random number generation |
| Total steps: | 1 |
| Category: | Basics |
| Date: | 2011-04-12 |
| Level: | Beginner |
| Product: | See complete product |
| Viewed: | 5254 |
Bookmark Java random number generation
Step 1 - Generating random number in Java
Java random number generation
Generating a random number is a simple task using the Java built in Random class that is part of the java.util package. Using the Random class you can generate random Integer, Long, Float, Double, Boolean values. You need to create a new Random object first, and then you can use any if its nextInt(), nextFloat(), … methods.
Random myRandom = new Random();
System.out.println(myRandom.nextInt());
System.out.println(myRandom.nextFloat());
System.out.println(myRandom.nextBoolean());
System.out.println(myRandom.nextLong());
If you want to generate random integers in a specified interval, then you can use the following code:If you want to generate random integers in a specified interval, then you can use the following code:
This code will generate random numbers from 0 to 10 (exclusive). You can test it with the following code snippet:
Random myRandom = new Random();
for (int i=0; i< 100; i++){
System.out.println(myRandom.nextInt(10));
}
That's all.
Tags: java random number, random number generation, random generator
| Java random number generation - Table of contents |
|---|
| Step 1 - Generating random number in Java |