Java random number generation


Home - Tutorials - Basics

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:9178

Bookmark Java random number generation



AddThis Social Bookmark Button

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. 

Code:
  1. Random myRandom = new Random();
  2. System.out.println(myRandom.nextInt());
  3. System.out.println(myRandom.nextFloat());
  4. System.out.println(myRandom.nextBoolean());
  5. 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:

Code:
  1. myRandom.nextInt(10);

This code will generate random numbers from 0 to 10 (exclusive). You can test it with the following code snippet:

Code:
  1. Random myRandom = new Random();
  2.  
  3. for (int i=0; i< 100; i++){
  4.     System.out.println(myRandom.nextInt(10));
  5. }

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



Total time: 0.2301