I thought I know Java well. We have an int - primitive type. When we transfer it to a method, the method does not refer to a variable, but only a copy. I assumed that Integer, the full-fledged class of packing int is passed to the method by reference, and any manipulations with the Integer variable passed to the method will occur directly from the variable we passed, and not by some copy.

I don't understand why the following code works against my understanding of types in Java.

Integer a=5; inc(a); System.out.println(a); private static void inc(Integer a){ a++; } 

Output:

 5 

Explain why 5, not 6 ???

  • What does the fact that the method is static? - Igor
  • As I understand it, the way I want the code to work is realizable only int [1] = {5} - MediaPortal
  • Isn't there a banal overlap of a ? In the method adopted, increased by 1, but a = 6 is already a local variable in the method itself. - Pollux

4 answers 4

You said everything correctly, all arguments when calling a method in java are passed by value, but there is one nuance. java.lang.Integer is an immutable type, and when incrementing occurs, unboxing , increasing the value and then wrapping it into an object, i.e. a completely different object is being created.

  • And how then to transfer the Integer to the method in order to be able to change the value which is fixed by the reference variable? - MediaPortal
  • one
    There are several options, 1) pass an array or some kind of wrapper, 2) return the modified value from the method or 3) discard the Integer and replace it with some mutable analog, for example AtomicInteger (I do not advise) - Artem Konovalov
  • “Parameters in java, with the exception of primitive types, are passed by reference” - I, of course, understood what you had in mind, but it’s better not to write this way, so as not to mislead people. - post_zeew
  • )) @post_zeew I'm sorry, I really don’t know, but how? - Artem Konovalov
  • 2
    “All arguments in Java are passed when called by value” (c). - post_zeew

According to JLS 15.14.2

It is a variable of choice. the variable. Binary numeric promotion (§5.6.2) before the addition of the value of 1 and the value of the variable. Note that there may be unboxing conversion (§5.1.8)

Further, JLS 5.1.8 reads:

5.1.8. Unboxing conversion
If r is a reference of type Integer, then unboxing conversion converts into r.intValue ()

Thus, a.intValue() computed, which is incremented by 1.

Returns to 15.14.2:

If necessary, the sum is up to boxing conversion (§5.1.7).

Thus, the result is boxed in Integer , and assigned to the local variable a .

    In this sentence

     a++; 

    object a unpacked, creating a temporary object of a primitive type that increases its value. The object a type Integer remains unchanged.

      Integer is an immutable object and a new object is created during the accretion.