ProAnswers.org

Is Java pass-by-value?

I always thought Java was pass by reference. Could someone explain it please?

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references passed by value.

It goes like this:




	
		
			public void foo(Dog d) { 
			  d.name == "Max"; // true 
			  d = new Dog("Fifi"); 
			  d.name == "Fifi"; // true 
			} 
			 
			Dog aDog = new Dog("Max"); 
			foo(aDog); 
			aDog.name == "Max"; // true 
			 
	



In this example aDog.name will still be "Max". "d" is not overwritten in the function as the object reference is passed by value.



Likewise:




	
		
			public void foo(Dog d) { 
			  d.name == "Max"; // true 
			  d.setname("Fifi"); 
			} 
			 
			Dog aDog = new Dog("Max"); 
			foo(aDog); 
			aDog.name == "Fifi"; // true