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.
Join The Discussion
Comments ( 4 )
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
In Java, which method is automatically called when an object is created?
A. start()
B. main()
C. init()
D. constructor()
What is method overloading in Java?
A. Defining multiple methods with the same name in the same class
B. Calling methods from another class
C. Using methods to load data from a file
D. Running methods in parallel threads
i am not understand this concept
I dint get the answer...need some more explanation
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
please explain how its works