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

Answer:

3.0


Automatic Conversion

Even though sqrt() expects a double for an argument, here we gave it an int. This is OK. The compiler knows what sqrt() expects and automatically inserts code to convert the argument to the correct type. When sqrt() is called it has the double precision floating point argument that it expects.

Often programmers use a type cast to show explicitly where the type conversion takes place:

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

In the above code, the type case is not required, but it is used to clearly show what is intended. Sometimes a type cast is required.


QUESTION 15:

What does the following fragment write?

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

Warning: this is a trick question!


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