Quote:Original post by MeaiQuote:
Not exactly correct. In Java, method arguments are always passed by value. That means passing any primitive type to a method means they will not be modified outside of the method.
You see, this is where my problems arose at the first place. In plain language (like you just described) this is perfectly correct. However it does not explain the underlying principle at all! What happens for built-in "int" - not Integer!
in Java? If they just get "copied" into the function argument, ..how? Well, the only explanation that makes sense, is that a new memory location for the function argument is created, and the dereferenced value of that "int" is being copied into that location.
My original question, where I was not entirely sure and therefore created the thread:
For an Integer (not "int", and we are in Java right now) a new memory location is also being created. -> for the function argument, that has to reside somewhere, doesn't it? The difference to c++ is now in my understanding, that Java copies the value of the reference of that Integer and replaces it with the temporary new memory location created for the function parameter.
C++ has "call by reference"...it means, ...it means that it copies the value of the pointer aswell?! Where is the difference then?
You have the idea. In both languages, in the abstract sense, space is allocated "on the stack" to contain the formal parameters to a function. In the case of Java and C, arguments to a function are always and only passed by value: the case if primitive types the meaning of "value" os self evident, but object types in Java are always references, so the formal parameter created on the stack is the value of the reference (which is like a pointer in C, but without the funky address-of and dereference operators, they;re implicit in Java).
C++ gets a little more complicated because it allows function parameters to be references, so that the arguments can be passed by reference or by value. Still, space has to be alloacted on the stack for the format parameters, as you have described.
What isn't obvious is that the actual code generated by a compiler does not necessarily exactly mirror what goes on in the abstract machine of the language. For example, in the case of passing by reference in C++, the compile may choose to inline the function body and the use of the formal function parameters is replaced by the use of the actual arguments. No extra space is allocated, no copies performed.