int x = 9; System.out.println( Math.sqrt( x ) );
3.0
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 situation the type case is not required, but it is good to have it there to clearly show what the computation is doing. Sometimes a type cast is required.