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.

1 Like

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!

2 Likes

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

Hello, I want to ask about what written above. It says that if you place + 1 inside of parentheses it will return numbers between 0 to 10. But how?

int c = (int)(Math.random() * 10 +1 )
let say the lowest Math.random() can generate is 0. if we follow order of operations, 0 * 10 result in 0. Then add 1.
So isn’t it suppose to generate random int between 1 to 10 instead of 0 to 10?

1 Like

Did you read my post above (post 2)? If that doesn’t clear it up, just ask!

Written in the lesson:
int c = (int)(Math.random() * 10) + 1;
if we placed the +1 inside the parentheses, we would get a random int between 0 and 10.

is the above statement true?
i thought int c = (int)(Math.random() * 10 + 1); would generate int between 1 and 10

You are right! The two pieces of code have the same range of outputs, this is a mistake by the lesson

2 Likes