Pages Navigation Menu

Coding is much easier than you think

Is Java Pass by Reference or Pass by Value?

 
Java manipulates objects ‘by reference’, but it passes object references to methods ‘by value’.
 
Consider the following program:
 

public class MainJava
{
	public static void main(String[] arg) {
		Foo f = new Foo("f");
		// It won't change the reference!
		changeReference(f);
		// It will modify the object that the reference variable "f" refers to!
		modifyReference(f);
	}

	public static void changeReference(Foo a) {
		Foo b = new Foo("b");
		a = b;
	}

	public static void modifyReference(Foo c) {
		c.setAttribute("c");
	}
}

 
Recommended Article

 
I will explain this in steps:

  1. Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f".
     

    Foo f = new Foo("f");

     

    Simple reference

  2. From the method side, a reference of type Foo with a name a is declared and it’s initially assigned to null.
     

    public static void changeReference(Foo a)

     
    new reference

  3. As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.
    changeReference(f);

     
    assign referrence

  4. Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".
    Foo b = new Foo("b");

     
    new reference 2

  5. a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".
    That is Only the references of a is modified, not the original ones(Reference of f remains the same)

    re assign referrence

  6. As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".
     
    change value by
  7. c.setAttribute(“c”); will change the attribute of the object that reference c points to it, and it’s same object that reference f points to it.
     
    change value

I hope you understand now how passing objects as arguments works in Java :)

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.