Java Pass by Value

This is a fundamental concept in Java that I didn’t necessarily forget but sometimes tend to mixup, I know it can be considered criminal in all Java circles!

Java always passes parameters by value!

The following example creates ‘Animal’ objects and sets the number of legs depending on the animal.

The class hierarchy should be self explanatory. (i.e. Dogs and Parrots are Animals :))

public void methodA(){
   Animal d = new Dog();  // 'd' is not a Dog but a pointer to a Dog object
   methodB(d);  // the pointer to the Dog object is passed as a value (a copy of the pointer)
   System.out.println("Number of Legs: "+d.getLegCount());

public void methodB(Animal a){
  a = new Parrot();  //creates a new reference, does not change object referenced by 'd'

The output would be “Number of Legs: 4” since the parameter ‘d’ is passed to methodB() as value. The “new” keyword creates a new reference (memory location) for the “Parrot”. Therefore when we return back to methodA() the variable ‘d’ still point to the memory location where the “Dog” is. Therefore the object pointed to by ‘d’ never changes.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s