如果 long 值小到足以适合 int,则 long 转换为 int

NFE*_*NFE 3 java

如果 long 值小到足以适合 int,是否可以自动将 long 转换为 int?

long i=1;
int j=i; //Error Type mismatch: cannot convert from long to int
Run Code Online (Sandbox Code Playgroud)

h22*_*h22 5

long i;
if (i =< Integer.MAX_VALUE && i >= Integer.MIN_VALUE) {
  int j = (int) i; // No loss of precision
} else {
    throw new Exception("Cannot convert "+i+" to int");
}
Run Code Online (Sandbox Code Playgroud)