go to previous page   go to home page   go to next page hear noise highlighting
int x = 1;
int y = 9;
System.out.println( Math.sqrt( x/y ) );

Answer:

0.0


Hidden Integer Division

The "trick" in this question is that the division of x by y is the first thing done in evaluating the statement. Since both x and y are integers, integer division is done and the result is integer 0.

Next, the integer 0 is converted to double precision 0.0, and it is that value that is sent to sqrt(), which computes 0.0 as a result.

Although the question was a "trick" this situation often occurs naturally in programs and you should watch out for it.


QUESTION 16:

Does the following correct the problem?

int x = 1;
int y = 9;
System.out.println( Math.sqrt( (double)x/y ) );

go to previous page   go to home page   go to next page