How To Generate Random Numbers in Java

0
27
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share


Random numbers are run time constants and are very important in coding. We use Random numbers for Security of the application,Gaming(gambling),Maths etc.
Below are two packages and classes that supports generation of Random numbers.

  1. java.util.Random  
  2. java.Math.Random

Using java.util.Random Class:


import java.util.Random
public class myRandomNumber{
public static void main(String[] Args)
{
Random rand=new Random();
for(int i=0;i<10;i++)
{
int randomNumber=rand.nextInt(100);
System.out.println(randomNumber);
}
}

Using java.Math.Random Class: This is useful when we need to generate in a range



public class myRandomNumber{
public static void main(String[] Args)
{
for(int i=0;i<10;i++)
{
int randomNumber=Math.random();
System.out.println(randomNumber);
}
}
Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here