Which of the following options is the best for generating random integer 0 or 1?

Which of the following options is the best for generating random integer 0 or 1? Correct Answer (int)(Math.random() + 0.5)

The correct answer is Option C: (int)(Math.random() + 0.5)

In Java, to generate a random integer that can be either 0 or 1, you can use the `Math.random()` method, which returns a random double value between 0.0 (inclusive) and 1.0 (exclusive). To convert this into either 0 or 1, you need to add 0.5 to the result and then cast it to an integer using `(int)`.

Here's the breakdown of the options:

- Option A: `(int)Math.random()` would generate either 0 or a random positive integer, but not necessarily 1.

- Option B: `(int)Math.random() + 1` would generate random positive integers starting from 1 and not 0.

- Option C: `(int)(Math.random() + 0.5)` adds 0.5 to the random value, making it either 0.5 or 1.5, and then casts it to an integer, resulting in either 0 or 1, which is what you want.

- Option D: `(int)(Math.random() + 0.2)` would not reliably generate only 0 or 1; it can produce a range of integers starting from 0.

Related Questions