Section 3.9. Casts and Conversions

   

3.9 Casts and Conversions

In a strongly typed language it is sometimes necessary to make conversions between one data type and another. Perhaps you need to perform an operation that accepts a value of a particular type, so you need to convert the type. You can legally convert one numeric type to another, as shown in Table 3.9.

The compiler will automatically assign a smaller type to a larger type. Because no data would be lost, this operation is unproblematic. However, data of a larger type will not automatically be converted to a smaller type ” even if the smaller type is sufficiently large to hold the data ”because the compiler cannot know if the data's integrity will be maintained . To perform this kind of assignment, a typecast is required. Take a look at these examples:

Table 3.9. Numeric Type Conversions

From

To

Lose Precision?

byte

short

No

short

int

No

char

int

No

int

long

No

int

float

Yes

int

double

No

long

float

Yes

float

double

No

long

double

Yes

 byte x  = 20;  byte y = 10; int z = x + y; // okay 

The above code is fine, because the compiler will automatically make a promotion ”that is, cast from a smaller datatype to a larger datatype ”when it can do so without losing precision.

 int x = 20;  int y = 10; byte z = x + y; // compiler error 

Even though in the above examples a byte is ostensibly a big enough type to hold the result of 30, the compiler will not make such an assignment and will instead report "possible loss of precision." This kind of thing can occur in your programs for a number of reasons. Perhaps because of a multiplication operation a variable would exceed its range.

In trying to compile the following code snippet, the error reported could be confusing:

 byte a = 100;  byte b = 30; byte c = a + b; // error! 

Here, the compiler reports that it has found an int where a byte was required, even though no int datatypes are explicitly present in the code. That is because a byte cannot hold a positive value greater than 127. If the code doesn't mention anything about int s, and the compiler rejects the code, why does the compiler say that it found an int ? The reason is that when you use primitive data types, Java will automatically convert any integral type to an int when mathematical operators are applied to them.

Note

When mathematical operators are used, Java defaults integral types to int .


The compiler will also reject this:

 int myInt = 37F; // error! 

Again, the error reported regards a possible loss of precision, saying that a float was found where an int was required. At the same time, the compiler will reject this:

 float myFloat = 89773.23; // error! 

Why the error? That looks perfectly reasonable. The reason for the error is that floating point values default to double s if they are not explicitly marked . So both of the following are acceptable:

 float myFloat = 333.25F; // okay  double myDouble = 456.78; // okay 

Note

Floating point values default to double unless float is specifically stated.


While it may look strange , the following is acceptable too. This is called typecasting:

 float f = (float) 14.5; // okay 

A typecast is lowering the range of a given value by changing its type. To typecast a variable, write the data type to which you want to cast your value in parentheses before the value:

 identifier = (typecastTo) (value); 

For example:

 int x = 10;  int y = 20; byte z; z = (byte) (x + y);  // okay 

Decimal values will be lost in certain situations, such as this:

 double d = 30405.9893;  int i = (int) (d); // prints 30405 

While that means you must be very careful when typecasting, sometimes this is exactly what you want to do. For instance, while the java.lang.Math package makes available a round() method for returning a float as an int , you can also do this with a typecast. For instance:

 float f = 2097.8F;  int i = (int) (f); // yields 2097 

Note

In some languages, you can exchange a boolean value with the numeric values 0 (for false ) or 1 (for true ). You cannot cast from a boolean value to any numeric type in Java.


When performing mathematical operations on values of different types, there are certain rules that come into play:

  • When more than one value, any of different types, are used in an operation, the operands are converted to a common type before the operation is carried out.

  • If any operand is a double , the values are converted to double s.

  • If any operand is a float , the values are converted to float .

  • If any operand is a long , the values are converted to long .

  • In all other cases, the types are converted to int .

The following snippet illustrates these rules:

3.9.1 numericOps.java

 /*  File: chp3.numericOps.java Purpose: demos conversion dangers Author: E Hewitt */ public class numericOps { public static void main(String[] args) { // get some variables to work with int i = 50; double d = 70.75; short s = 32750; // do some operations System.out.println(i + d); // 120.75, type is double int i1 = s + i; System.out.println(i1); // 32800, type is int // remember that a short's positive limit is 32,767 int i2 = (short) i1; // conversion compiles System.out.println(i2); // whoa!! prints -32736!     } } 

Note

Clearly, conversion is something to be handled with care, especially for those of us used to dealing with a language like ColdFusion where a number is a number is a string.


When you cast from one type to another, first make sure that the result will not exceed the range allowed for the target type. While many of Java's improvements over other languages are intended to reduce the number of elusive errors that programmers can make, this remains tricky. For instance:


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

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