Java Programming - Java.lang Class - Discussion

Discussion Forum : Java.lang Class - Finding the output (Q.No. 8)
8.
What will be the output of the program?
int i = (int) Math.random();
i = 0
i = 1
value of i is undetermined
Statement causes a compile error
Answer: Option
Explanation:

Math.random() returns a double value greater than or equal to 0 and less than 1. Its value is stored to an int but as this is a narrowing conversion, a cast is needed to tell the compiler that you are aware that there may be a loss of precision.

The value after the decimal point is lost when you cast a double to int and you are left with 0.

Discussion:
2 comments Page 1 of 1.

Saptarshi Das said:   9 years ago
Because it gives random numbers between 0 and 1.

Rajshri said:   1 decade ago
Math.random gives a random number, then why I is between 0 and 1.

Post your comments here:

Your comments will be displayed after verification.