Reputation: 126
I've been reading many posts about this, all are full of answers that tend to counter the answer before it and they all seem to be by high ranked people so im very confused and would just like to know if this works:
public class Object{
private int someNumber = 5;
public void setSomeNumber(int newNumber){someNumber = newNumber;}
}
public class Main {
Object myObject = new Object();
public static void main(String[] args){
changeNumber(myObject);
}
void changeNumber(Object obj)
{
obj.setSomeNumber(10);
}
}
Would this change myObject.someNumber to 10?
My understanding is that obj is pointing to the same place in memory as myObject so calling its method useing obj is the same as calling it with myObject because obj is not just a copy of myObject?
I thought it was clear to me till i started reading threads on here about it lol
Edit: Thanks for correcting code, i just wrote it out in here as a example, didnt see the mistakes
Thanks guys. Also i was confused by people saying pass by value so i wasnt sure if it was passing the address in memory or not because to me thats passing a refrence so it became unclear to me.
Upvotes: 0
Views: 125
Reputation: 37566
You are right, java does manipulate objects by reference, and all object variables are references, and doesn't pass method arguments by reference but by value.
Take a look at this article and see the difference in behaviour between objects and method arguments in the examples provided.
Upvotes: 0
Reputation: 42431
Although this code won't compile (you can't use Object, and can't access from static method non static data field), but I've got your question.
Basically you're right, and this is why:
In Java when you pass parameters into the method, they're passed by reference, but the reference itself is passed by value. This is done for optimization reasons I believe. So in fact, another reference is produces that points to the same Object in memory. If you take a look on these references by themselves they're different, but they both point on the same object. So when you change the internal state of the object from within 'changeNumber' method, its goes to the object that reference 'obj' refers to and changes it.
The only exception is primitives - they aren't passed by reference, instead they're passed by value as you probably have learnt in other languages.
Once you get aware of what exactly goes on when you call methods and pass parameters to it this will stop confusing you :)
Hope this helps
Upvotes: 0
Reputation: 118
You are correct. changeNumber() would change the someNumber variable of the object passed to it. You are passing a reference to the object itself, not a copy.
Upvotes: 2