如何在Java中将long转换为int ?


当前回答

手动类型转换可以在这里完成:

long x1 = 1234567891;
int y1 = (int) x1;
System.out.println("in value is " + y1);

其他回答

手动类型转换可以在这里完成:

long x1 = 1234567891;
int y1 = (int) x1;
System.out.println("in value is " + y1);
// Java Program to convert long to int
  
class Main {
  public static void main(String[] args) {
  
    // create long variable
    long value1 = 523386L;
    long value2 = -4456368L;
  
    // change long to int
    int num1 = Math.toIntExact(value1);
    int num2 = Math.toIntExact(value2);
      
    // print the type
    System.out.println("Converted type: "+ ((Object)num1).getClass().getName());
    System.out.println("Converted type: "+ ((Object)num2).getClass().getName());
  
    // print the int value
    System.out.println(num1);  // 52336
    System.out.println(num2);  // -445636
  }
}

从Java 8开始 你可以使用:数学。toIntExact(长值)

参见JavaDoc: Math.toIntExact

返回长参数的值;如果值溢出int,则抛出异常。

数学的源代码。在JDK 8中的toIntExact:

public static int toIntExact(long value) {
    if ((int)value != value) {
        throw new ArithmeticException("integer overflow");
    }
    return (int)value;
}

如果您想进行安全的转换,并享受使用Java8和Lambda表达式 你可以这样使用它:

val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)
long x = 3;
int y = (int) x;

但是假设long可以表示为int,你们知道这两者的区别吗?