Reputation: 127
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.
Upvotes: 1
Views: 10269
Reputation: 25874
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.
Upvotes: 6
Reputation: 556
Just to clarify the responses so far
public class Car {
private String type;
public Car(String type) {
this.type = type;
}
public void setType(String type) {
this.type = type;
}
public static void foo(Car someCar) {
Car newCar = new Car("Sedan");//new object created
someCar = newCar; //passed reference also points to newly created object
someCar.setType("Coupe");//Referred object changes
System.out.println(newCar.type);//Coupe
System.out.println(someCar.type);//Coupe
}
public static void main(String[] args) {
Car myCar = new Car("Sports");//new object created
foo(myCar);//reference is passed by value
System.out.println(myCar.type);//Sports
}
}
Upvotes: 1
Reputation: 616
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.
Upvotes: 2
Reputation: 991
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 the Object
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 the Dog
that was passed to the function, but to a new one.
Upvotes: 2