Java Reference
In-Depth Information
Sometimes you'll have a value in your Java class that isn't the right type for what you
need. It might be the wrong class or the wrong data type, such as a float when you need
an int .
You use casting to convert a value from one type to another.
Casting is the process of producing a new value that has a different type than its source.
Although the concept of casting is reasonably simple, the usage is complicated by the
fact that Java has both primitive types (such as int , float , and boolean ) and object
types ( String , Point , ZipFile , and the like). This section discusses three forms of casts
and conversions:
Casting between primitive types, such as int to float or float to double
n
Casting from an instance of a class to an instance of another class, such as Object
to String
n
3
Casting primitive types to objects and then extracting primitive values from those
objects
n
When discussing casting, it can be easier to think in terms of sources and destinations.
The source is the variable being cast into another type. The destination is the result.
Casting Primitive Types
Casting between primitive types enables you to convert the value of one type to another
primitive type. It most commonly occurs with the numeric types, and there's one primi-
tive type that can never be used in a cast. Boolean values must be either true or false
and cannot be used in a casting operation.
In many casts between primitive types, the destination can hold larger values than the
source, so the value is converted easily. An example would be casting a byte into an int .
Because a byte holds values from -128 to 127 and an int holds from 2,100,000 to
2,100,000, there's more than enough room to cast a byte into an int .
You often can automatically use a byte or a char as an int ; you can use an int as a
long , an int as a float , or anything as a double . In most cases, because the larger type
provides more precision than the smaller, no loss of information occurs as a result. The
exception is casting integers to floating-point values; casting an int or a long to a float ,
or a long to a double , can cause some loss of precision.
Search WWH ::




Custom Search