There are 3 ways we have through which we can generate the Random numbers.
1. Java.util.Random class
2. Math.Random method
3. ThreadLocalRandom class
Now we will see that how we can implement the above 3 ways to generate the Random numbers.
Java.util.Random class
To generate the Random number with this way, first we need to create an object of this class like below
Random rnd=new Random();
To use the above class you need to import the below jar in your project.
import java.util.Random;
Now, we need to see what type of Random number we need to generate like Integer, Long, Boolean, Float & Double etc.
There are methods which we can call through the object of Random class like below
rnd.nextInt(100) // This will generate the Random Number between 0 to 100.
rnd.nextFloat()
rnd.nextLong()
rnd.nextDouble()
rnd.nextBoolean();
import java.util.Random;
public class Numbers
{
public static void main(String args[])
{
Random rnd=new Random();
System.out.println(rnd.nextInt()); //Output 1579708416
System.out.println(rnd.nextInt(100));//Output 36
System.out.println(rnd.nextLong()); //output -3975729109407067933
System.out.println(rnd.nextFloat()); //output 0.22997051
System.out.println(rnd.nextDouble()); //output 0.7115380145242618
System.out.println(rnd.nextBoolean());//output true
}
}
Math.Random method
This method will generate the Random number of type Double between the range of 0.0 to 1.0 .
import java.util.Random;
public class Numbers
{
public static void main(String args[])
{
System.out.println("Random value :"+ Math.random());
//Output "Random value :0.9302772707882316"
}
}ThreadLocalRandom classThis class got introduced in Java 1.7 for generating the Random Numbers of type Integer, Float , double, boolean etc. Please find the below example
import java.util.concurrent.ThreadLocalRandom;
public class Numbers
{
public static void main(String args[])
{
System.out.println("Random value :"+ ThreadLocalRandom.current().nextInt());
System.out.println("Random value :"+ ThreadLocalRandom.current().nextInt(1,10));
System.out.println("Random value :"+ ThreadLocalRandom.current().nextInt(100));
//"Random value :-1778537131
//Random value :6
//Random value :37"
}
}***********************************************************************************************************************************************************
I will be adding more concepts in my upcoming posts. Please keep me posted if you have any questions and concerns.
Best of Luck.
No comments:
Post a Comment