73

I need to create a Java method to return true or false randomly. How can I do this?

8 Answers 8

133

The class java.util.Random already has this functionality:

public boolean getRandomBoolean() {
    Random random = new Random();
    return random.nextBoolean();
}

However, it's not efficient to always create a new Random instance each time you need a random boolean. Instead, create a attribute of type Random in your class that needs the random boolean, then use that instance for each new random booleans:

public class YourClass {

    /* Oher stuff here */

    private Random random;

    public YourClass() {
        // ...
        random = new Random();
    }

    public boolean getRandomBoolean() {
        return random.nextBoolean();
    }

    /* More stuff here */

}
0
68

(Math.random() < 0.5) returns true or false randomly

0
19

This should do:

public boolean randomBoolean(){
    return Math.random() < 0.5;
}
0
5

You can use the following code

public class RandomBoolean {
    Random random = new Random();
    public boolean getBoolean() {
        return random.nextBoolean();
    }
    public static void main(String[] args) {
        RandomBoolean randomBoolean = new RandomBoolean();
        for (int i = 0; i < 10; i++) {
            System.out.println(randomBoolean.getBoolean());
        }
    }
}
1
  • 2
    This is a little redundant. randomBoolean could just be new Random(), and instead of getBoolean() have nextBoolean(). The code above is just adding a pointless class wrapping.
    – whitfin
    Apr 26, 2015 at 19:03
3

You will get it by this:

return Math.random() < 0.5;
1
  • 8
    Where possible try to only add answers which add information. This answer is near identical to MichaelBorgwardt's answer Sep 3, 2013 at 13:46
1

ThreadLocalRandom.current().nextBoolean()

To avoid recreating Random objects, use ThreadLocalRandom. Every thread has just one such object.

boolean rando = ThreadLocalRandom.current().nextBoolean() ;

That code is so short and easy to remember that you need not bother to create a dedicated method as asked in the Question.

0

You can use the following for an unbiased result:

Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

Note: random.nextInt(2) means that the number 2 is the bound. the counting starts at 0. So we have 2 possible numbers (0 and 1) and hence the probability is 50%!

If you want to give more probability to your result to be true (or false) you can adjust the above as following!

Random random = new Random();

//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

//For 25% chance of true
boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;

//For 40% chance of true
boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;
1
  • I don't know, but I would read better something like: //For 40% chance of true boolean chance40oftrue = (random.nextInt(100) < 40);
    – Patrice M.
    Sep 17, 2020 at 22:28
0

Java's Random class makes use of the CPU's internal clock (as far as I know). Similarly, one can use RAM information as a source of randomness. Just open Windows Task Manager, the Performance tab, and take a look at Physical Memory - Available: it changes continuously; most of the time, the value updates about every second, only in rare cases the value remains constant for a few seconds. Other values that change even more often are System Handles and Threads, but I did not find the cmd command to get their value. So in this example I will use the Available Physical Memory as a source of randomness.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public String getAvailablePhysicalMemoryAsString() throws IOException
    {
        Process p = Runtime.getRuntime().exec("cmd /C systeminfo | find \"Available Physical Memory\"");
        BufferedReader in = 
                new BufferedReader(new InputStreamReader(p.getInputStream()));
        return in.readLine();
    }

    public int getAvailablePhysicalMemoryValue() throws IOException
    {
        String text = getAvailablePhysicalMemoryAsString();
        int begin = text.indexOf(":")+1;
        int end = text.lastIndexOf("MB");
        String value = text.substring(begin, end).trim();

        int intValue = Integer.parseInt(value);
        System.out.println("available physical memory in MB = "+intValue);
        return intValue;
    }

    public boolean getRandomBoolean() throws IOException
    {
        int randomInt = getAvailablePhysicalMemoryValue();
        return (randomInt%2==1);
    }


    public static void main(String args[]) throws IOException
    {       
        Main m = new Main();
        while(true)
        {
            System.out.println(m.getRandomBoolean());
        }
    }
}

As you can see, the core part is running the cmd systeminfo command, with Runtime.getRuntime().exec().

For the sake of brevity, I have omitted try-catch statements. I ran this program several times and no error occured - there is always an 'Available Physical Memory' line in the output of the cmd command.

Possible drawbacks:

  1. There is some delay in executing this program. Please notice that in the main() function , inside the while(true) loop, there is no Thread.sleep() and still, output is printed to console only about once a second or so.
  2. The available memory might be constant for a newly opened OS session - please verify. I have only a few programs running, and the value is changing about every second. I guess if you run this program in a Server environment, getting a different value for every call should not be a problem.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.