Java Programming - Java.lang Class - Discussion


What is the value of "d" after this line of code has been executed?

double d = Math.round ( 2.5 + Math.random() );

[A]. 2
[B]. 3
[C]. 4
[D]. 2.5

Answer: Option B


The Math.random() method returns a number greater than or equal to 0 and less than 1 . Since we can then be sure that the sum of that number and 2.5 will be greater than or equal to 2.5 and less than 3.5, we can be sure that Math.round() will round that number to 3. So Option B is the answer.

Swathi said: (Nov 13, 2011)  
I have satisfied with this question and answers.

Sandesh said: (Nov 30, 2012)  
What if only math.round(2.5); ?

Kavitha said: (Jan 27, 2014)  
I have one doubt.

If Math.round () returns 0 then the answer may become 2.5 also is it correct or wrong?

Arijit Paul said: (Feb 11, 2014)  

Math.random() "Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0."

Thus 2.5 + Math.random() will always be inside [2.5 to 3.5] range.

If the fractional portion of number is .5 or greater, the Math.round()rounded to the next higher integer. If the fractional portion of number is less than .5, the argument is rounded to the next lower integer.

So, The Math.round() of any number within this range[2.5 to 3.5] is 3.

Ashish said: (Aug 14, 2014)  
How I can check it out in my program ?

Pradeepsai.K said: (Oct 21, 2016)  
I agree with @Arijit Paul.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.