I read in this question that Java is always pass-by-value. And so even references are passed by value.
I don't understand what this means, can somebody clarify this for me please?
I read in this question that Java is always pass-by-value. And so even references are passed by value.
I don't understand what this means, can somebody clarify this for me please?
Given this
Object ref = new Object();
ref
is actually storing a value, some address to an object. Let's say 1234
.
When you pass ref
around
public void method(Object passed) {...}
...
method(ref);
Java actually copies the value of the reference and assigns it to the parameter. So, passed
will also have the value 1234
.
Similarly, if you had
Object otherRef = ref;
the value 1234
would be copied and assigned to otherRef
.
If you then re-assign otherRef
, like
otherRef = new Object();
that would assign a new value to otherRef
, but ref
would still have the same value as before. That's what pass by value is.
When you call a method
ref.toString();
Java uses the value of the reference to find the referenced object and invoke the method. This is called dereferencing.
You might want to go through the JPDA javadoc, starting with StackFrame
. Go through the fields and types and you'll start to understand how everything is mapped. For example, it has a getValues(..)
method which returns a Map<LocalVariable, Value>
. That should tell you that a variable doesn't actually store anything. Instead, it is mapped to a value, where that value may be all sorts of things.
int a = 5;
public void foo(int num) {
num = num + 5;
System.out.println(num);
}
foo(a);
System.out.println(a);
In the above code, a is passed into foo() by value. That means that a new variable is created with the scope of foo() that has the same initial value as a. When the value of num is changed, the value of a is not changed. The first println() will print a 10, the second will print a 5. In c++ you could pass a in by reference, which means that the value of a would be changed too.
I can try, in some other languages you have the option of passing something by a pointer (e.g. a reference to a memory region). Java calls every function with a value (not a pointer), but the value of an Object is a reference to a memory region. See also the default toString()
in your own classes.
I always find this a good example:
Dog foo = new Dog("Rocky");
modifyDog(foo);
System.out.println(foo.name); //Alice
public void modifyDog(Dog aDog)
{
aDog.name = "Alice"; //here you change the field 'name' of the object located in memory currently referenced by foo and aDog variables.
aDog = new Dog(); //since aDog is a copy of foo then this won't recreate foo object
}