Java程序将long类型变量转换为int
要理解这个示例,你应该具备以下 Java 编程 主题的知识:
示例 1:Java 程序使用类型转换将 long 转换为 int
class Main {
public static void main(String[] args) {
// 创建 long 变量
long a = 2322331L;
long b = 52341241L;
// 将 long 转换为 int
// 使用类型转换
int c = (int)a;
int d = (int)b;
System.out.println(c); // 2322331
System.out.println(d); // 52341241
}
}
在上面的示例中,我们有 long
类型的变量 a
和 b
。注意以下行,
int c = (int)a;
在这里,更高数据类型 long
被转换为较低的数据类型 int
。因此,这被称为缩小类型转换。要了解更多,请访问 Java 类型转换。
当 long
变量的值小于或等于 int
的最大值(2147483647)时,这个过程工作正常。然而,如果 long
变量的值大于最大的 int
值,那么会有数据丢失。
示例 2:使用 toIntExact() 方法将 long 转换为 int
我们还可以使用 Math
类的 toIntExact()
方法将 long
值转换为 int
。
class Main {
public static void main(String[] args) {
// 创建 long 变量
long value1 = 52336L;
long value2 = -445636L;
// 将 long 转换为 int
int num1 = Math.toIntExact(value1);
int num2 = Math.toIntExact(value2);
// 打印 int 值
System.out.println(num1); // 52336
System.out.println(num2); // -445636
}
}
在这里,Math.toIntExact(value1)
方法将 long
变量 value1
转换为 int
并返回。
如果返回的 int
值不在 int
数据类型的范围内,toIntExact()
方法会抛出异常。例如,
// int 范围外的值
long value = 32147483648L
// 抛出整数溢出异常
int num = Math.toIntExact(value);
要了解更多关于 toIntExact()
方法的信息,请访问 Java Math.toIntExact()。
示例 3:将 Long 类的对象转换为 int
在 Java 中,我们也可以将包装类 Long
的对象转换为 int
。为此,我们可以使用 intValue()
方法。例如,
class Main {
public static void main(String[] args) {
// 创建 Long 类的对象
Long obj = 52341241L;
// 将 Long 对象转换为 int
// 使用 intValue()
int a = obj.intValue();
System.out.println(a); // 52341241
}
}
在这里,我们创建了一个名为 obj
的 Long
类对象。然后我们使用 intValue()
方法将对象转换为 int
类型。
要了解更多关于包装类的信息,请访问 Java 包装类。