Java教程

Java 将 long 类型变量转换为 int 的程序

Java 程序将 long 类型变量转换为 int

在这个程序中,我们将学习在 Java 中将 long 变量转换为整数(int)。
要理解此示例,您应该了解以下Java 编程主题:
Java 数据类型(原生)

示例 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 类型变量 ab。注意线条,
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
  }
}
在这里,我们创建了一个名为 objLong 类的对象。然后我们使用 intValue() 方法将对象转换为 int 类型。
要了解有关包装类的更多信息,请访问 Java 包装类。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4