Java 中的 Integer 和 int 有什么区别?
javaobject oriented programmingprogramming更新于 2025/5/25 2:52:17
Integer(包装类)和 int(原始数据类型)
- Integer 和 int 之间的主要区别在于,Integer 是包装类,而 int 是原始数据类型。
- int 是一种存储32 位有符号二进制补码整数的数据类型,而 Integer 是将原始类型 int 包装在对象中的类。
- Integer 可用作需要对象的方法的参数,而 int 可用作需要整数的方法的参数值, 可用于算术表达式。
- int 数据类型有助于将整数值存储在内存中,而 Integer 有助于将 int 转换为对象并将对象转换为 int。
- int 类型的变量是可变的 ,除非它被标记为final ,并且 Integer 类包含一个 int 值并且是不可变的。
示例 1
public class PrimitiveDataTypeTest {
public static void main(String []args) {
// int 的声明
int a = 20;
int b = 40;
int result = a+b;
System.out.println("Result is: " + result);
}
}
输出
Result is: 60
示例2
public class WrapperClassTest {
public static void main(String []args) {
int a = 20;
Integer b = Integer.valueOf(a);
System.out.println("Converted Value of b is: " + b);
Integer c = new Integer(30);
int d = c.intValue();
System.out.println("Converted Value of d is: " + d);
}
}
输出
Converted Value of b is: 20 Converted Value of d is: 30
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

