Get Random Number between 0 and 1 in Java

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).

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 1 : 0.7411678523235552
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.

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);
        }
}
Random number 0 or 1: 0

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.