public int add(int a, int b) {
return a + b;
}
final int two = 2;
int sum = add(1, two);
变量两个作为原始整数类型2传递。而在
public int add(Integer a, Integer b) {
return a.intValue() + b.intValue();
}
final Integer two = Integer.valueOf(2);
int sum = add(Integer.valueOf(1), two);
变量两个作为一个引用传递给一个保存整数值2的对象。
< p > @WolfmanDragon:
通过引用传递将像这样工作:
public void increment(int x) {
x = x + 1;
}
int a = 1;
increment(a);
// a is now 2
当increment被调用时,它传递一个指向变量一个的引用(指针)。而增量函数直接修改变量一个。
对于对象类型,它的工作方式如下:
public void increment(Integer x) {
x = Integer.valueOf(x.intValue() + 1);
}
Integer a = Integer.valueOf(1);
increment(a);
// a is now 2
class ManualBoxing {
public static void main(String args[]) {
Integer objInt = new Integer(20); // Manually box the value 20.
int i = objInt.intValue(); // Manually unbox the value 20
System.out.println(i + " " + iOb); // displays 20 20
}
}
autoboxing/autounboxing的例子:
class AutoBoxing {
public static void main(String args[]) {
Integer objInt = 40; // autobox an int
int i = objInt ; // auto-unbox
System.out.println(i + " " + iOb); // displays 40 40
}
}
< p > (Java版本)
简单来说,int是原始的(不能有空值),Integer是int的包装对象
一个使用Integer和int的例子,当你想比较int变量时,它会抛出错误。
int a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is wrong - cannot compare primitive to null
{
do something...}
Instead you will use,
Integer a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is correct/legal
{ do something...}