Java Program to Generate Random Numbers - The Coding Shala

Home >> Java Programs >> Java Program to generate random numbers

 In this post, we will learn how to Generate Random Numbers in Java.

Java Program to Generate Random Numbers 

Write a Java Program to Generate random integers and doubles.

Approach 1

We can generate random integers using the Random class and nextInt() method. To generate random double use nextDouble() method.

Java Program: 

import java.util.*;

class Solution {
    
    public static void main(String[] args) {
        //create object of Random class
        Random rand = new Random();
        
        //random integers
        System.out.println("Random integer is: " + rand.nextInt());
        System.out.println("Random integer is: " + rand.nextInt());
        
        System.out.println("Random integer between 0 to 500 is: " + rand.nextInt(500));
        System.out.println("Random integer between 0 to 500 is: " + rand.nextInt(500));
        
        //random doubles
        System.out.println("Random double is: " + rand.nextDouble());
        System.out.println("Random double is: " + rand.nextDouble());
    }
}

Output: 
Random integer is: -237602665
Random integer is: 1724780755
Random integer between 0 to 500 is: 200
Random integer between 0 to 500 is: 374
Random double is: 0.0422535568322393
Random double is: 0.10644146580779246

Approach 2

We can also use Math.random() to generate double random numbers. It will return values between 0.0 to 1.0.

Java Program: 

import java.util.*;

class Solution {
    
    public static void main(String[] args) {
        //using Math.random()
        
        System.out.println("Random double is: " + Math.random());
        System.out.println("Random double is: " + Math.random());
        System.out.println("Random double is: " + Math.random());
        System.out.println("Random double is: " + Math.random());
    }
}

Output: 
Random double is: 0.4970007856549141
Random double is: 0.2711311270754778
Random double is: 0.1275856087981624
Random double is: 0.37157351525839033


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Longest Substring Without Repeating Characters Java Program - The Coding Shala

Anti Diagonals - The Coding Shala

First Missing Positive Solution - The Coding Shala

Shell Script to Display the digits which are at odd positions in a given 5-digit number - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala