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

Browse Java. How are these 2 different and why?

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

    change(a); // a doesn't get incremented. value is 5
    change(b); // b does. value is now 6
}

public void change(Integer a) {
    a++;
}
+3
source share
3 answers

The only difference is that

Integer b = new Integer(5);

guarantees the creation of a new facility. The first will use the cache instance (see Integer.valueOf()).

Both are immutable, and references to both are passed by value (like everything in Java). Therefore, change()does not affect.

+6
source

, a++ a = a + 1, a , . Integer, ( ), ints, .

+1

No call to change () affects the passed values ​​due to automatic boxing / unpacking.

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

The above code means that a ++ changes the value of a since it is an object, not a primitive. However, ++ is not overloaded by Integer, so it blocks it in order to be able to apply the ++ operator to its int. To me, the compiler should not allow this.

-1
source

Source: https://habr.com/ru/post/1789035/


All Articles