Passing Variables into Methods- Java Passing Mechanism Explained

Every Programming Language has its own way of passing the variables into methods. There are basically two ways of passing variables- Pass by Reference and Pass By Value. The former deals with the passing of reference or pointer to particular variable and the latter involves passing a copy of the variable to the method. C supports both ways of passing and the Pass By Reference is supported b means of Pointers. Every Java Beginner ponders over “Is Java a Pass By Value?” or “Is it a Pass By reference?”  or “Both?”. Before answering the question i would like to throw light on Passing Object Reference variables and Passing primitive reference variables.

Object Reference Variables: These are the variables which refer to the object of the declared type or its subtype. Something like

Animal a = new Animal()

where  a is the reference variable

Passing Object Reference Variables:

When a object variable is passed into the method, only the copy of the Object reference is passed and not the Object itself. The bit pattern in the reference variable is copied into the method parameter. What is this bit pattern? This bit pattern is the address of the specific object in the memory (on the heap). In other words, both the caller and the called method will now have identical copies of the reference and thus both will refer to the same exact object on the heap.

Code Example:

import java.awt.Dimension;
class PassObjectRef
{

public static void main(String[] args)
{

Dimension plotDimension = new Dimension(20,30);
PassObjectRef passObj=new PassObjectRef();
System.out.println("B4 Updating: "+"H: "+plotDimension.height+" W:"+plotDimension.width);
//Before the object values are altered
passObj.updateDimension(plotDimension );
System.out.println("After Updating: "+"H:"+plotDimension.height+" W:"+plotDimension.width);
//After the object values are altered

}
void updateDimension(Dimension dim)
{

dim.height+=10; //Notice the values being changed here.
dim.width+=20;

}

}

Output:

B4 Updating:  H: 30 W: 20
After Updating:  H: 40 W: 40

Notice that the values being updated in the updateDimension() method are being also reflected outside the scope of the method. That means both the plotDimension and dim object references are referring to the same object on the heap.

Passing Primitive Variables:
When a primitive variable is passed the value with in the variable is copied into the method parameter, which is nothing but the pass-by-copy-of-the-bits-in-the-variable.

Code Snippet:

class PassPrimVar
{

public static void main(String[] args)
{
int primitiveVariable =4;
PassPrimVar passObj =new PassPrimVar();
System.out.println</span>("Before Updating Value: "+primitiveVariable );
// Value being printed before changing
passObj.updateValue(primitiveVariable);
System.ou.println("After Updating Value: "+primitiveVariable );
// Value being printed after changing. Notice there is no difference

}
void updateValue(int var)
{

var+=40; //Value being Changed Here
System.out.println("While Updating Value: "+var);

}
}

Output:
Before Updating Value: 4
While Updating Value: 44
After Updating Value: 4

Notice that the Value is same before and after the updateValue() method has been executed. But in the method the value has been changed. In other words the value being changed in the method is not being reflected in the main() method, its local to the scope of the method in which it is changed.

Does Java Use Pass-By-Value?

Here is the main confusion- Does Java Use Pass By Reference for Object Reference Passing and Pass By Value for Primitive Variable Passing? Java is actually pass-by-value for all variables running within a single VM. Pass By Variable is nothing but passing the variable value. It is same even if you pass and object reference variable or an primitive variable, you are always passing the copy of the bits in the variable. So for passing Object reference variable you are passing the copy of bits which actually is the reference (or address) to the object on the heap and this results in both the reference variables referring to the same object. Because two identical reference variables refer to the exact same object, if the called method modifies the object, the caller will see that the object the caller’s original variable refers to has also been changed. But keep in mind- Suppose in the called method the object reference is reassigned a new object, the caller’s original variable will still refer to the same object on the heap. In this case there will be two references and two objects on the heap. See the code excerpt below:

void do()
{

Animal animal = new Animal(”Dog”);
//New Animal object created on the heap with name Dog referenced by animal
kill(animal); // animal being passed to the kill() method

}
void kill(Animal ani)
{

/*
Method receives a copy of the reference, but animal and ani both still refer to same object
*/
ani =new Animal(”Cat”);
/*
But after this statement, the animal reference still refers to the object by name “Dog”,
but the ani reference now refers to the object by name “Cat”.
There are 2 references referring to 2 different objects on the heap.
*/

}

Coming to the passing of primitive variables it is pretty simple and straight forward. When you pass the primitvie variable into a method, you’re passing a copy of the bits representing the value. For example if you pass an int variable with the value 6, and try to change the value in the called method, we can change it but the modifications will not be reflected in the caller’s vairable.

So the bottom line is- Java always uses Pass By Value– Be it for passing Object Reference Variable or primitive variables.

15 thoughts on “Passing Variables into Methods- Java Passing Mechanism Explained”

  1. The comparison of java and C++ needs to be done carefully because they have many things in common, but some starange uncommon things as well. Personaly it will be good if you dont intermix the discussion, as that is harder to grasp!
    Over all a very nice post buddy,
    keep it up and thanks for the links at the end to my blog. 🙂

    Regards,
    Saurabh Patil
    http://passingSCJP.blogspot.com

    Reply
  2. So tell me how would you change primitave varibles? If its only passed by value how can i posiblly change the actual varible i’m passing? This is whats confusing. Is it no possible to change primitve types in methods?

    Reply
    • Why do u want to change the variables? Thats a bad practice to change the value of the variables within the methods. One should try to make the methods hav no side effects. So u can return the value and assign to the variable u want to change. Or u can make the variables as fields of the class, create a instance of that class and then pass it to the method. In the method u can update the values of the fields of the class

      Reply
  3. Hi I am having a bit of a problem. I am trying to create a scanner variable, convert it to a string with the .nextLine(); method, and then use a getter and setter methods to use those results in another class. I will post the code so you can see what I am doing. Any help would be much appreciated.

    import java.util.Scanner;

    public class Operation {
    Scanner operation = new Scanner(System.in);

    public void setOp(){
    operation.nextLine();
    String op = operation.nextLine();
    }

    public Scanner getOp(){
    return op;
    }
    }
    But I always get an error because it says that the variable op in my getOp method doesn’t exists.

    Reply
    • The op variable being used in getOp() isn’t in the scope of getOp() method. you could be using the operation instance variable declared in the Operation class.
      Moreover the ‘op’ variable declared in setOp() is of type String and its scope is limited to that of the setOp() method.
      Try using ‘operation’ instead of ‘op’ in getOp().

      Reply
  4. Advice is truly timeless. I’m new to developing in Android, which, of course, is based on Java. You have no idea how many hours I have spent banging my head against the wall trying to figure out how changing a value inside of a method also changed the value outside of the scope of the method (I’m following along in a book and got stuck on a tutorial). This explains it (along with that link posted by Java Developer). Crystal clear now. Thanks.

    Reply

Leave a Reply

Discover more from Experiences Unlimited

Subscribe now to keep reading and get access to the full archive.

Continue reading