Casting between primitive types (like int, float, and double) and converting between objects and primitive types. --------------------------------------------------------------------- --------------------------------------------------------------------- I. Converting int to float: // The following lines of code WORK ...... int xInt = 120; float xFloat; xFloat = xInt; --------------------------------------------------------------------- --------------------------------------------------------------------- II. Converting float to int: --------------------------------------------------------------------- // The following lines of code DO NOT work! ...... int xInt; float xFloat = 3.8644f; xInt = xFloat; // During compilation you will get the following ERROR: // "Explicit cast needed to convert float to int." --------------------------------------------------------------------- // The following lines of code WORK ...... int xInt; Float x = new Float("3.8644"); xInt = x.intValue(); // Note that the value of xInt will be 3 (not 4) because // the fractional part of the floating point number is // truncated (not rounded) when converting float to int. --------------------------------------------------------------------- // The following lines of code ALSO WORK ...... int xInt; float xFloat = 3.8644f; xInt = (int) xFloat; --------------------------------------------------------------------- --------------------------------------------------------------------- III. Converting double to float: --------------------------------------------------------------------- // The following lines of code DO NOT work! ...... double xDouble = 3.8644951; float xFloat; xFloat = xDouble; // During compilation you will get the following ERROR: // "Explicit cast needed to convert double to float." --------------------------------------------------------------------- // The following lines of code WORK ...... float xFloat; Double x = new Double("3.8644951"); xFloat = x.floatValue(); --------------------------------------------------------------------- // The following lines of code ALSO WORK ...... double xDouble = 3.8644951; float xFloat; xFloat = (float) xDouble; --------------------------------------------------------------------- // Note, also, that the following lines of code DO NOT work! float xFloat = 3.8644f; float sum; sum = 2.0 + xFloat; // They will not work because, by default, in Java the // 2.0 on the right-hand-side of the last expression is a // double-precision number, so "xFloat" is first converted // to a double-precision number before it is added to "2.0", // then right-hand-side is of type "double" while the left- // hand-side is of type "float" so you have to perform an // explicit type cast, like.... sum = (float) (2.0 + xFloat); // or .... sum = 2.0f + xFloat; --------------------------------------------------------------------- ---------------------------------------------------------------------