1. 类型转换:
在类型转换中,程序员在程序设计期间使用转换运算符将数据类型转换为另一种数据类型。在类型转换中,当将数据类型转换为另一种数据类型时,目标数据类型可能小于源数据类型,这就是为什么它也被称为收缩转换。
语法/声明:-
destination_datatype = (target_datatype)variable;
(): is a casting operator.
target_datatype:是我们要转换源数据类型的数据类型。
类型转换示例 –
float x;
byte y;
...
...
y=(byte)x; //Line 5
在第 5 行:您可以看到,我们正在将float(source) 数据类型转换为byte(target) 数据类型。
2. 类型转换:
在类型转换中,编译器在编译时将一种数据类型自动转换为另一种数据类型。在类型转换中,目标数据类型不能小于源数据类型,因此也称为扩展转换。更重要的一点是它只能应用于兼容的数据类型。
类型转换示例 –
int x=30;
float y;
y=x; // y==30.000000.
让我们看看下面给出的类型转换和类型转换之间的区别:
S.NO | TYPE CASTING | TYPE CONVERSION |
---|---|---|
1. | In type casting, a data type is converted into another data type by a programmer using casting operator. | Whereas in type conversion, a data type is converted into another data type by a compiler. |
2. | Type casting can be applied to compatible data types as well as incompatible data types. | Whereas type conversion can only be applied to compatible datatypes. |
3. | In type casting, casting operator is needed in order to cast the a data type to another data type. | Whereas in type conversion, there is no need for a casting operator. |
4. | In typing casting, the destination data type may be smaller than the source data type, when converting the data type to another data type. | Whereas in type conversion, the destination data type can’t be smaller than source data type. |
5. | Type casting takes place during the program design by programmer. | Whereas type conversion is done at the compile time. |
6. | Type casting is also called narrowing conversion because in this, the destination data type may be smaller than the source data type. | Whereas type conversion is also called widening conversion because in this, the destination data type can not be smaller than the source data type. |
7. | Type casting is often used in coding and competitive programming works. | Whereas type conversion is less used in coding and competitive programming as it might cause incorrect answer. |
8. | Type casting is more efficient and reliable. | Whereas type conversion is less efficient and less reliable. |