Using Promotion and Type Casting

Promotion is used when you try to assign a data type that holds a smaller value range to data type that holds a bigger value range. This is to prevent precision lost in the assigned data type value. For example, promoting a byte data type to integer data type.

Typecast is used to lower the value range by changing its data type such as double floating point to floating point. This is normally done when developer need to access methods that only accept certain data types as arguments or to save memory.

Promotion In Use:

Data Type Promotion may occur automatically by Compiler if the data would not be lost. For examples:
  • Assign a smaller data type to a larger data type
  • Assign an integral data type to a floating point data type (no decimal value places to lose)
Type Casting:

Syntax:
identifier = (target_type) value
where
identifier is the Variable Namevalue is the value assign to the Identifier
value is the value assigned to the Identifier
(target_type) is the type that you wish to type cast the value

For example:
int number1 = 20; //32 bits of memory used
int number2 = 10; // 32 bits of memory used
byte number3 = 0; // 8 bits of memory lost
number3 = (byte) (number1 + number2); // no data loss

Compiler Assumptions for Integral and Floating Point Data Types:
  • Values are automatically converted to an int value (or higher) if the primitive data type values are used in an expression with certain operators (*, /, -, +, %).
  • Values assigned to a floating point data types are always defaulted to a double data type.

0 comments:

Post a Comment