Numeric Casting


Java supports numeric types of different ranges in value. The float type uses 32 bits for its implementation and expresses a smaller range of numbers than does double, which uses 64 bits. The integral primitive typeschar, byte, short, int, and longeach support a range that is different from the rest of the integral primitive types.

You can always assign a variable of a smaller primitive type to a larger primitive type. For example, you can always assign a float reference to a double reference:

 float x = 3.1415f; double y = x; 

Behind the scenes, this assignment implicitly causes a type conversion from float to double.

Going the other wayfrom a larger primitive type to a smallerimplies that there might be some loss of information. If a number stored as a double is larger than the largest possible float, assigning it to a float would result in the truncation of information. In this situation, Java recognizes the possible loss of information and forces you to cast so that you explicitly recognize that there might be a problem.

If you attempt to compile this code:

 double x = 3.1415d; float y = x; 

you will receive a compiler error:

 possible loss of precision found   : double required: float float y = x;           ^ 

You must cast the double to a float:

 double x = 3.1415d; float y = (float)x; 

You may want to go the other way and cast from integral primitives to floating-point numbers in order to force noninteger division. A solution to the above problem of calculating the average for a Performance is to cast the dividend to a double before applying the divisor:

 public double average() {    int total = 0;    for (int score: tests)       total += score;    return (double)total / tests.length; } 

As an added note: When it builds an expression that uses a mix of integral and float values, Java converts the result of the expression to an appropriate float value:

 assertEquals(600.0f, 20.0f * 30, 0.05); assertEquals(0.5, 15.0 / 30, 0.05); assertEquals(0.5, 15 / 30.0, 0.05); 



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net