How To Generate Random Numbers in Java



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);
}
}
How To Generate Random Numbers in Java How To Generate Random Numbers in Java Reviewed by Animesh Chatterjee on September 06, 2018 Rating: 5

No comments:

Powered by Blogger.