Examveda
Examveda

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

A. (int)Math.random()

B. (int)Math.random() + 1

C. (int)(Math.random() + 0.5)

D. (int)(Math.random() + 0.2)

Answer: Option C

Solution(By Examveda Team)

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.

This Question Belongs to Java Program >> Constructors And Methods

Join The Discussion

Comments ( 4 )

  1. VIJAY KUMAR
    VIJAY KUMAR :
    8 months ago

    i am not understand this concept

  2. Shruthi Chowta
    Shruthi Chowta :
    7 years ago

    I dint get the answer...need some more explanation

  3. Khizar Syed
    Khizar Syed :
    7 years ago

    random() is a static method defined in Math class.
    Syntax: static double random()
    random() always return a value in the range 0.0 1 to 1.99 that will be '1' when typecasted to int. not selected
    3. (int)(Math.random() + 0.5) -> 0.5 to 1.49 that will be 0 or 1 when typecasted to int. high chances.
    4. (int)(Math.random() + 0.2) -> 0.2 to 1.19 that will be 0 or 1 when typecasted to int but more chances to '0'

    SO, C is the correct option

  4. Satyam Mutyala
    Satyam Mutyala :
    7 years ago

    please explain how its works

Related Questions on Constructors and Methods

What is a constructor in Java?

A. A special method to create instances of classes

B. A method used for mathematical calculations

C. A method to perform string manipulations

D. An exception handling mechanism