Skip to Content

Generate random numbers using Math.random

  1. /*
  2.   Generate random numbers using Math.random
  3.   This java example shows how to generate random numbers using random method of
  4.   Java Math class.
  5. */
  6.  
  7. public class GenerateRandomNumbers {
  8.  
  9.   public static void main(String[] args) {
  10.    
  11.     /*
  12.      * To generate random numbers, use
  13.      * static double random() method of Java Math class.
  14.      *
  15.      * This method returns a positive double value grater than 0.0
  16.      * and less than 1.0
  17.     */
  18.    
  19.     System.out.println("Random numbers between 0.0 and 1.0 are,");
  20.     for(int i=0; i < 5 ; i++)
  21.       System.out.println("Random Number ["+ (i+1) + "] : " + Math.random());
  22.      
  23.     /*
  24.      * To generate random number between 1 to 100 use following code
  25.      */
  26.  
  27.     System.out.println("Random numbers between 1 and 100 are,");
  28.     for(int i=0; i < 5 ; i++)
  29.       System.out.println("Random Number ["+ (i+1) + "] : " + (int)(Math.random()*100));
  30.    
  31.   }
  32. }
  33.  
  34. /*
  35. Typical output would be
  36. Random numbers between 0.0 and 1.0 are,
  37. Random Number [1] : 0.7900395454653136
  38. Random Number [2] : 0.15887365598103076
  39. Random Number [3] : 0.5570570713930629
  40. Random Number [4] : 0.017811004461356195
  41. Random Number [5] : 0.7135560403213513
  42.  
  43. Random numbers between 1 and 100 are,
  44. Random Number [1] : 31
  45. Random Number [2] : 21
  46. Random Number [3] : 24
  47. Random Number [4] : 95
  48. Random Number [5] : 3
  49. */