Hidden Integer Division

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page
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 ) );