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

What do you suspect will happen with the following method call?

pointB.move( 14.305, 34.9 );

Answer:

This is an error, because the parameter list has two floating point values, not the two int values required.

Parameters Must be the Correct Type

When a method starts running, it must have the right number of parameters, and each parameter must be of the required type. However, sometimes, just before a method starts running, the values supplied in a parameter list are converted to the required type. There are two ways in which this can happen:

  1. Explicitly — the programmer asks for values to be converted with a type cast.
  2. Implicitly — if the compiler can make the conversion without loss of information, or with only a small loss of precision, it will automatically do so.

A type cast looks like this:

(requiredType)(expression)

The (requiredType) is something like (int). The expression is an ordinary expression. If it is a single variable, you don't need the surrounding parentheses. Here is an example program that shows a type cast:

import java.awt.*;      // import the package where Point is defined
class TypeCastEg
{

  public static void main ( String arg[] )
  {
    Point pointB = new Point();     // create a point at x=0 y=0
    pointB.move( (int)14.305, (int)(34.9-12.6) );
    System.out.println("New location:" + pointB );
  }
}

In this case, a type cast is required for both parameters because converting a floating point number to an int will usually lose information. In casting a floating point value to an int, the fractional part will be lost. (Not rounded.)

QUESTION 5:

What will be the output of the program?