Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

128 HOUR 10:Creating Your First Object


To cast information into a new format, you precede it with the new format
surrounded by parentheses marks. For example, if you want to cast some-
thing into a longvariable, you precede it with (long). The following state-
ments cast a floatvalue into an int:
floatsource = 7.06F;
int destination = (int) source;

In variable casting where the destination holds larger values than the
source, the value is converted easily, such as when a byteis cast into an
int. Abyteholds values from –128 to 127, whereas an intholds values
from –2.1 billion to 2.1 billion. No matter what value the bytevariable
holds, the new intvariable has plenty of room for it.
You sometimes can use a variable in a different format without casting it at
all. For example, you can use charvariables as if they were intvariables.
Also, you can use intvariables as if they were longvariables, and any-
thing can be used as a double.
In most cases, because the destination provides more room than the source,
the information is converted without changing its value. The main excep-
tions occur when an intor longvariable is cast to a float, or a longis
cast into a double.
When you are converting information from a larger variable type into a
smaller type, you must explicitly cast it, as in the following statements:
int xNum = 103;
byteval = (byte) xNum;

Here, casting converts an integer value called xNuminto a bytevariable
called val. This is an example where the destination variable holds a
smaller range of values than the source variable. Abyteholds integer val-
ues ranging from –128 to 127, and an intholds a much larger range of
integer values.
When the source variable in a casting operation has a value that isn’t
enabled in the destination variable, Java changes the value to make the cast
fit successfully. This can produce unexpected results if you’re not expecting
the change.

Casting Objects
You can cast objects into other objects when the source and destination are
related by inheritance. One class must be a subclass of the other.
Free download pdf