This section shows you how to create a random number and example provided here will help you easily understand and use the code to generate random numbers in your java application.
Ads
TutorialsIn this section you will learn how to generate random number in java. Java API provide a random class in java.util.Random package which generate random number within a range. The random() method is most convenient way to generate random number in java which return only double value .You can also generate pseudo-random floating or double type numbers.
Random Numbers in Java with Example
As we discussed that to create a random number, java provide a random() method in java.util.Random class. You have to create the instance of random class. This class provide method to return random integer, double and float. The following example will illustrate the random number generation in java.
import java.util.Random; public class RandomNumber { public static void main(String args[]) { Random random = new Random(); for(int i =0; i<5; i++){ int randomInteger = random.nextInt(); System.out.println("Random Integer in Java: " + randomInteger); } } }
As this program execute it will generate five random numbers. If you are using java Math.random it will generate only double value not integer. Some of the methods of Random class are as follows :
So, if you will compile and execute the program then you will get the output as follows:
Posted on: June 21, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles
Advertisements
Ads
Ads
Discuss: How to generate random number in java
Post your Comment