开发者

In Java, what is the difference between the following declarations?

开发者 https://www.devze.com 2023-02-07 13:31 出处:网络
Considering Java. How are these 2 different and why? public void languageChecks() { Integer a = 5; Integer b = new Integer(5);

Considering Java. How are these 2 different and why?

public void languageChecks() {
    Integer a = 5;
    Integer b = new Integer(5);

  开发者_如何学Go  change(a); // a doesn't get incremented. value is 5
    change(b); // b does. value is now 6
}

public void change(Integer a) {
    a++;
}


The only difference is that

Integer b = new Integer(5);

guarantees a new object is created. The first will use an instance from a cache (see Integer.valueOf()).

Both are immutable and the references to both are passed by value (as is everything in Java). So change() has no effect on either.


I'd always been taught a++ was just shorthand for a = a + 1 in which case a local variable is created named a and immediately thrown away when the method returns. There're no methods on Integer that change the value (it's immutable), and likewise no operations on primitive ints that change their value.


Neither call to change() affects the values passed in, because of auto-boxing/unboxing.

public void change(Integer a) {
    // This unboxes 'a' into an int, increments it and throws it away
    a++;
}

The above code seems to imply that a++ changes the value of a, since it's an object, not a primitive. However, ++ is not overloaded by Integer, so it unboxes it to be able to apply the ++operator on its int. To me the compiler shouldn't allow this.

0

精彩评论

暂无评论...
验证码 换一张
取 消