如何在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,你们知道这两者的区别吗?
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap