示例 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()
方法的更多信息,请访问 Java Math。 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 包装类。