Sunday, October 28, 2018

Java Random Numbers

Random numbers are the sequence of numbers lack a defined pattern. For example 2,4,6,8 etc. are even numbers. 2,5,7,11 etc.. are prime numbers. By looking at the numbers we can relate a pattern in these series of numbers. But Random numbers will lack these kind of patterns and the next number in the sequence is unpredictable. eg: 1,2034, 33, 845 etc.

How to Generate Random numbers in Java?


JDK provided a class Random to deal with Random numbers and you can use methods like nextInt(), nextDouble() etc to generate random numbers.

Here is a basic example.

public class RandomNumberJavaBasic {

 public static void main(String[] args) {
  System.out.println(Math.random());
 }
}

This program will always produce a different double number whenever you run the program.

How to Generate a Random number in a range?

The following class will generate random numbers within a specified range.

public class JavaRandomNumbersInARange {

 public static void main(String[] args) {
  System.out.println(randomInt(1,10));
  
 }
 
 public static int randomInt(int min, int max) {
    
     Random randomNumGenerator = new Random();

     int randomNum = randomNumGenerator.nextInt((max - min) + 1) + min;

     return randomNum;
 }

}

Random numbers has many uses in statistics, gaming , cryptography and gambling software.

No comments:

Post a Comment