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

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:使用类型转换将 long 转换为 int

public 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

public 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() 方法将引发异常 。也就是,

// 超出了 int 的范围
long value = 32147483648L

// 抛出异常
int num = Math.toIntExact(value);

要了解有关 toIntExact() 方法的更多信息,请访问 Java Math.toIntExact()

示例 3:将 Long 类的对象转换为 int

在 Java 中,我们还可以将包装类 Long 的对象转换为 int . 为此,我们可以使用 intValue() 方法。例如,

public 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 包装器类