Example Method Calls

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   go to next page

Answer:

conversion No loss of info.
Automatic Conversion.
Possible loss of precision.
Automatic Conversion.
Possible great loss of information.
Requires a Type Cast.
byte to short X   
short to byte   X
short to long X   
int to float  X  
float to byte   X
double to float   X

Example Method Calls

Where there is no loss of information, or only a possible loss of precision, Java will automatically convert the value in a method call to what is required. When there is a possible loss of both precision and magnitude, Java requires you to explicitly state that you want to go ahead with the conversion by using a type cast.

For example:

Point  A = new Point();

short  a = 93,    b = 92;
int    i = 12,    j = 13;
long   x =  0,    y = 44;
double u = 13.45, v = 99.2;

A.move( i, j );             // OK --- no conversion needed.
A.move( a, b );             // OK --- shorts converted to ints with no loss
A.move( a, j );             // OK --- short converted to int with no loss

A.move( x, y );             // NOT OK --- possible loss of 
                            // precision and magnitude.
A.move( (int)x, (int)y );   // OK --- type casts say to go ahead

A.move( i, v );             // NOT OK -- possible loss of 
                            // precision and magnitude (for v).
A.move( i, (int)v );        // OK --- type cast says to go ahead.

In making these decisions, it is only the type of the variable (or the expression) that is examined, NOT the particular value. For example, in the first method call marked NOT OK, the particular values could (in this case) be converted from long to int without loss of information. But for other values there would be total loss of information, so the call requires a type cast.

Conversion is done on individual parameters, if needed. In the third call, only the first parameter needed to be converted.

QUESTION 9:

Which of the following method calls are correct?

Point  A = new Point();

short  a = 93,    b = 92;
int    i = 12,    j = 13;
long   x =  0,    y = 44;
double u = 13.45, v = 99.2;

A.move( i, b );   //  
A.move( a, x );   //  
A.move( u, b );   //