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.

Anuj said: (Jul 19, 2019)  
Math.round (2.5 + Math.random() ) will return a double value, so the correct answer is 3.0 and not 3.

Aniket said: (Mar 26, 2020)  
@Anuj. Yes, it should be 3.0 but it's not in the option.

Rohit said: (Dec 12, 2020)  

What if Math.random() returns 1.0 and the statement looks like;
double d = Math.round ( 2.5 + 1.0 );
Value of d will be 3.5 and Math.round(3.5) will be 4.0.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.