What will be the output of the program?
New location:java.awt.Point[x=14,y=22]
In the previous example,
converting from floating point to int
results in a loss of information,
so the programmer must explicitly ask for conversion with a type cast.
When a conversion from one type to another type
can be done without loss of
information,
the compiler will do it automatically.
For example,
the description of the move()
method says that
it requires two int
parameters:
public void move(int x, int y); // change (x,y) of a point object
An int
value is held in 32 bits.
A short
value that is held in 16 bits can be converted to 32 bits
without loss of information.
Why? The information encoded in 16 bits can also be encoded in 32 bits. So the following program will compile and run correctly:
import java.awt.*; // import the class library where Point is defined class autoConvEg1 { public static void main ( String arg[] ) { Point pointB = new Point(); // create a point at x=0 y=0 short a=12, b=42; pointB.move( a, b ); // values in parameter list automatically // converted to the required type, int. System.out.println("New location:" + pointB ); } }
The variables a
and b
themselves are not changed;
they are
only used to say what values to start with before the conversion.
What will this program write to the monitor?