Converting & Casting
How is data stored in the
Computer?
Types of Conversion
Implict Conversion
Explicit Conversion (Casting)
Converting
Primitive Data Types
Data Types in JAVA
Example of an implicit Conversion
//64 bit long integer
long myLongInteger;
// 32 bit standard integer
int myInteger;
myLongInteger = myInteger;
myInteger = (int) my LongInteger
Casting
The type of myLongInteger must be temporarily
changed to a int when the given assignment
statement is processed. Thus, the cast only lasts
for the duration of the assignment. Java type casts
have the following form: (T) N where T is the name
of a numeric type and N is a data item of another
numeric type. The result is of type T.
So a data type with lower precision (fewer bits) can
be converted to a type of higher precision without
explicit casting. To convert a higher precision type
to a lower precision, however, an explicit cast is
required or the compiler will flag an error.
Down & UP
Down Casting and Up Casting
Difference between Casting and
Rounding
Example of an explicit Casting
Employee emp = new Employee();
VicePresident veep = new VicePresident();
emp = veep; // no cast needed for upward use
veep = (VicePresident)emp; // must cast
explicitly