What do you suspect will happen with the following method call?
pointB.move( 14.305, 34.9 );
This is an error, because
the parameter list has two floating point values,
not the two int
values required.
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:
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 class library 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.)