Java always passes by value. What might be a little bit confusing is that Java also passes
references by value. Note that passing a reference by value is not the same as pass by reference!
Let's carefully look at what your program does.
In line 3 you declare a member variable called
integer in class
PassByValue.
In line 7, in the constructor of class
PassByValue, you assign a value to the member variable.
In line 12, you are declaring and initializing a local variable called
integer. Note that that variable does not have anything to do with the member variable of line 3 - it's a completely separate variable, that just happens to have the same name.
In line 13, you are declaring and initializing a local variable called
passByValue that is an instance of class
PassByValue. That instance will contain an instance of the member variable, initialized to
new Integer(10) by the constructor.
In line 16, you are printing the content of the member variable. It will print "10" as the value.
In line 18, you are calling the method on the instance of class
PassByValue, and you pass it the local variable. Note that in the method, the argument
copyInteger will now refer to the same
Integer object that the local variable
integer in line 12 refers to. The
reference integer is copied to
copyInteger.
In line 24, you make
copyInteger refer to another value. (Note that in this line, you are using
autoboxing). Note that making
copyInteger refer to something else does not have any effect on the local variable
integer in the
main() method -
copyInteger originally contained a
copy of the reference, it doesn't have any link back to the variable
integer in the
main() method.
In line 19, you are printing the content of the local variable
integer. It will print "15" as the value. The method call of line 18 didn't have any effect on the local variable
integer.
Seetharaman also makes an important point: class
Integer is
immutable. The value of an
Integer object cannot be changed after it has been created. In line 24 you are not changing the value of the
Integer object; you're just making
copyInteger refer to a different
Integer object.