Java Integer 转换为 int 类型:两种方法

在 Java 中,您可以使用两种方法将 Integer 类型转换为 int 类型:

1. 使用 intValue() 方法

您可以使用 intValue() 方法将 Integer 对象转换为 int 类型的值:

Integer num = 10;
int result = num.intValue();

2. 使用自动拆箱 (autoboxing)

Java 提供了自动拆箱功能,您可以在需要 int 类型的地方直接使用 Integer 对象:

Integer num = 10;
int result = num;

自动拆箱会自动将 Integer 对象转换为 int 类型的值。

注意: 自动拆箱是一种方便的语法糖,但是当 Integer 对象为 null 时,会抛出 NullPointerException 异常。因此,在使用自动拆箱时,建议先检查 Integer 对象是否为 null。


原文地址: https://www.cveoy.top/t/topic/oLfu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录