Type casting is a process to convert one data type to another. It makes the variable compatible temporarily. We often encounter situations where there is a need to store a value of one type into a variable of another type. In such situations, we must cast the value to be stored by preceding it with the type name in parentheses. Casting is often necessary when a method returns a type different than the one we require.
Four integer types can be cast to any other type except boolean. Casting into a smaller type may result in a loss of data. Similarly, the float and double can be cast to any other type except boolean. Again, casting to smaller type can result in a loss of data. Casting a floating point value to an integer will result in a loss of the fractional part. If the following order is used for type casting, it guarantees in no loss of information.
byte à char à short à int à long à float à double
for example
• byte value can be converted to int or double
• int value can be converted to long or float
The syntax for casting is: type variable1 = (type) variable2;
Type casting can be of two types:
Implicit type Casting (Automatic Conversion): when constants and variables of different types are mixed in an expression they are converted to the same type. This conversion is done implicitly by the C compiler. The C compiler converts all the operands to the type of the largest operand. For example if an expression involves int and float, int type gets converted to float type.
Example:
float x=32;
The value of the x will be ’32.0’, because of implicit conversion of value from int to float
Explicit type Casting: if a user forcefully changes the data type into other allowable data type it is said to be explicit type casting.
Example:
int to float:
float x;
x=5/2 /* value of x will be 2.0 */
x=(float)5/2; /* value of x will be 2.5 */
float to int:
int x;
x= 3.2 /* causes error */
x=(int)3.2 /* x will be 3 */
0 comments:
Post a Comment