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!
		// It will modify the object that the reference variable "f" refers to!

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

	public static void modifyReference(Foo 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.

    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

I'm a Full stack developer of IT exp in J2EE, AngularJs, MicroServices, Docker, Spring (Boot, MVC, Cloud), Bluemix, DevOps. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

%d bloggers like this: