I am trying to understand how exactly method parameters are passed in Java.
I was able to figure out that java only uses pass by value. I understand how this works for primitive types (like int) but I am a little confused about reference types.
I think that in Java we don't pass objects but object references. But in this case I don't really understand what's going on in this code example:
public class test {
static String a = "String a";
static String b = "String b";
public static void main(String[] args) {
System.out.println(a); //expected String a
doSomething(a);
System.out.println(a); //expected String b
}
static void doSomething(String someString) {
someString = b;
}
}
I know that this is anything but good practice but I am only using this example to understand what's going on.
So, basically be calling the method doSomething, I am passing a reference to a String object (the reference is stored in the variable called a). But then I try to change this reference inside the method to reference another String object. However, this does not work.
I somehow just assumed that parameters in Java work the same way as io-parameters in pascal procedures (there are no return types, instead you just reassign a pass by reference parameter). That doesn't seem to be right.
The only way I can explain this to myself is, that when calling a method, java does not pass the actual object reference but instead passes a 'copy' of the reference wich points to the same object (same object but different pointers). Can anybody confirm if am right with this or tell please me, what actually happens here?
I would really appreciate your help.