I'm a little bit confused about the difference between passing an object and a primitive data as the parameter in Java. I read a post here explaining that when you pass a primitive data, you copy that data and pass it, but if you pass an object then you pass by the object reference. And I also read this discussion explaining that there's no pass-by-reference in Java. So what is the real difference between above two passes and why Java deals with them differently? Thanks in advance.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
When you pass a primitive, you actually pass a copy of value of that variable. This means changes done in the called method will not reflect in original variable.
When you pass an object you don't pass a copy, you pass a copy of 'handle' of that object by which you can access it and can change it. This 'handle' is a 'reference'. In this changes will be reflected in original.
Now one thing, what would happen when you pass array variable of a primitive type. In that case you do not pass a copy and the changes made will be reflected in original one.
There's no difference between passing a primitive and an object reference. Both are passed by value. In the first case, the primitive value is copied; in the second case, the reference value is copied.
Just to clarify the responses so far
To be clear, primitive types are passed by value, a copy of the type is what exists inside a function.
An
Object
is not copied, a reference to it is passed to the function. This means that you can change theObject
within the function.However, the reference is passed by value. When that posting creates a new
Dog
from within the function, the value of the reference changes. It is no longer a reference to theDog
that was passed to the function, but to a new one.