Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe for all free courses

How to generate random number in Java using Random class ?.

Program to demonstrate how to generate random number in Java.

 

package com.hubberspot.util;

import java.util.Random;

public class RandomNumberGenerator {

    public static void main(String[] args) {
    
        // 1. create a Random object
        Random random = new Random();
        int number;
        
        for(int i=1; i < = 5; i++) { 
           
            for(int j=1; j < = 5; j++) {
                // 2. nextInt(6) will return number 
                // from 0 to 5 and adding 1 to it 
                // will return number in the range
                // 1 to 6
                number = random.nextInt(6) + 1;
                System.out.print(number + " ");
            }
            System.out.println();
        }

    }

}


Output of the program : 

 
 
© 2021 Learn Java by Examples Template by Hubberspot