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

N-th Tribonacci Number Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Find Second Smallest Element in the Array - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala