Automatic Conversion

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 = 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 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.

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!