Static Methods of the Math Class

Hi! I know this isn’t tagged Java but my question is kinda related. The Java article Static Methods of the Math Class says the two lines of code below differ. Anyone knows why?

(int)(Math.random() * 10) + 1; // returns integer between 1 and 10
(int)(Math.random() * 10 + 1); // returns integer between 0 and 10

From what I read the (int) typecasts the element on its right to an integer and works similar to Math.floor()
Based on this information I would assume that both lines of code return the same range, which I used a while loop to check for. But I just want to be 100% sure.

Hello @trashy_coder, welcome to the forums!

This generates a number where the lowest number is 0, and the highest is 9.9999 (the 9s carry on for a while). This is rounded down (so 9.999 becomes 9. You then add 1 to that, so the lowest bound now becomes 1, and the highest bound becomes 10 (9 + 1 = 10).

This takes a random number (say 0.5) multiply it by 10, so you get 5. Then add 1 to this, to get 6. Now, finally you round it down. So, if you get 0.999 from Math.random():
0.999 * 10 = 9.999
9.999 + 1 = 10.999
(int)10.999 = Math.floor(10.999) = 10

I hope this helps!


Yes it does help! So there really isn’t a difference between the two, just the order of operations happening then. Thank you!!

1 Like