示例 1:使用类型转换将long转换为int的Java程序
class Main {
public static void main(String[] args) {
// create long variables
long a = 2322331L;
long b = 52341241L;
// convert long into int
// using typecasting
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) {
// create long variable
long value1 = 52336L;
long value2 = -445636L;
// change long to int
int num1 = Math.toIntExact(value1);
int num2 = Math.toIntExact(value2);
// print the int value
System.out.println(num1); // 52336
System.out.println(num2); // -445636
}
}
在这里,Math.toIntExact(value1)
方法将long
变量value1转换为int
并返回它。
如果返回的int
值不在int
数据类型的范围内,则toIntExact()
方法会抛出异常。即,
// value out of range of int
long value = 32147483648L
// throws the integer overflow exception
int num = Math.toIntExact(value);
要了解有关toIntExact()
方法的更多信息,请访问JavaMath.toIntExact()。
示例 3:将Long类的对象转换为int
在Java中,我们还可以将包装类Long
的对象转换为int
。为此,我们可以使用intValue()
方法。例如,
class Main {
public static void main(String[] args) {
// create an object of Long class
Long obj = 52341241L;
// convert object of Long into int
// using intValue()
int a = obj.intValue();
System.out.println(a); // 52341241
}
}
在这里,我们创建了一个名为obj的Long
类对象。然后,我们使用intValue()
方法将该对象转换为int
类型。
要了解有关包装类的更多信息,请访问Java包装类。