In this post, we will see how to get random number between 0 to 1 in java. We have already seen random number generator in java.
Get Random Number between 0 and 1 in Java
We can simply use Math.random() method to get random number between 0 to 1.
Math.random method returns double value between o(inclusive) to 1(exclusive).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class RandomNumber0To1Main { public static void main(String args[]) { System.out.println("Random number 1 : "+Math.random()); System.out.println("Random number 2 : "+Math.random()); System.out.println("Random number 3 : "+Math.random()); System.out.println("Random number 4 : "+Math.random()); } } |
When you run above program, you will get below output
Random number 2 : 0.2933148166792703
Random number 3 : 0.48691199704439214
Random number 4 : 0.6151816544734755
Get Random Number 0 or 1 in Java
If you need to get random number as 0 or 1 and not floating points between 0 and 1, you can use following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.arpit.java2blog; public class GenerateRandomMain { public static void main( String args[] ) { int min = 0; // Min value int max = 1; // Max value int randomInt = (int)Math.floor(Math.random() * (max - min + 1) + min); // Random number 0 or 1 System.out.println("Random number 0 or 1: "+randomInt); } } |
This code is applicable to get any random numbers between range. You can change min and max value based on your requirements.
That’s all about how to get random number between 0 and 1 in java.