Java 中的类型转换是什么?
数据类型 是一组预定义的值,指定可以存储在其中的值的类型以及可以对其执行的操作。为什么需要类型转换?
Java 有不同的原始数据类型,它们需要不同的内存空间。将一种数据类型的值分配给另一种数据类型时,这可能会导致兼容性问题。如果数据类型已经兼容,则编译器会自动完成类型转换。因此,类型转换解决了程序中处理不同数据类型时的主要兼容性问题。Java 类型转换的类型
Java 中有两种类型的类型转换。- 加宽类型转换- 也称为隐式或自动类型转换
- 缩小类型转换— 也称为显式或手动类型转换
加宽型铸件
顾名思义,拓宽类型转换是指将较小的数据类型拓宽为较大的数据类型。当我们想要将小类型转换为大类型时,我们会执行这种类型转换。数据类型必须相互兼容。没有从数字到 char 或 boolean 类型的隐式转换。在 Java 中,char 和 boolean 类型是不兼容的。
字节 -> 短 -> 字符 -> int -> 长 -> 浮点 -> 双精度
这种类型的转换由编译器自动完成,不会丢失任何信息。它不需要程序员的任何外部触发。
例子
//Automatic type conversion
public class WideningExample {
public static void main(String[] args) {
int i = 100;
System.out.println("int value: " + i);
// int to long type
long l = i;
System.out.println("int to long value: " + l);
// long to float type
float f = l;
System.out.println("int to float value: " + f);
byte b = 1;
System.out.println("byte value: " + b);
// byte to int type
i = b;
System.out.println("byte to int value: " + i);
char c = 'a';
System.out.println("char value: " + c);
// char to int type
i = c;
// prints the ASCII value of the given character
// ASCII value of 'a' = 97
System.out.println("char to int value: " + i);
}
}
输出
int 值:100 int 转 long 值:100 int 转 float 值:100.0 byte 值:1 byte 转 int 值:1 char 值:a char 转 int 值:97
解释
在上面的代码中,我们展示了由编译器自动完成的加宽类型转换。首先,我们为int、byte和char赋值。然后,我们将 int 值分配给long和float,它们都大于int。我们还将byte和char值分配给int。byte和char都是比int小的数据类型,因此,这些转换是隐式的 。缩小型铸造
缩小类型转换,顾名思义,是指将较大的数据类型缩小为较小的数据类型。当我们想要将大类型转换为小类型时,我们会执行这种类型转换。
双精度 -> 浮点 -> 长整型 -> int -> 字符 -> 短整型 -> 字节
对于这种类型的转换,我们通过指定我们自己的转换来覆盖 Java 的默认转换。为了实现这一点,我们将需要类型转换的变量或值写在括号“()”中,前面加上目标数据类型。然而,这种类型的铸造可能会导致精度损失。
例子
//Manual Type Conversion
public class NarrowingExample {
public static void main(String[] arg) {
// double data type
double d = 97.04;
// Print statements
System.out.println("double value: " + d);
// Narrowing type casting from double to long
// implicitly writing the target data type in () followed by initial data type
long l = (long) d;
// fractional part lost - loss of precision
System.out.println("long value: " + l);
// Narrowing type casting from double to int
// implicitly writing the target data type in () followed by initial data type
int i = (int) l;
// fractional part lost - loss of precision
System.out.println("int value: " + i);
// Narrowing type casting from double to int
// implicitly writing the target data type in () followed by initial data type
char c = (char) i;
// displaying character corresponding to the ASCII value of 100
System.out.println("char value: " + c);
}
}
输出
double 值:97.04 long 值:97 int 值:97 char 值:a
GO TO FULL VERSION