Java passes parameters by value or by reference?

Today I was talking to the usual suspect and we were discussing about people that get stuff into their CV without even know the basics of it. Somewhere in the middle of the conversation we got to talk about pointers and how Java developers usually don’t give a fuck about them. I must admit, I don’t! The thing is that’s something intrinsic to the language itself.

I know this has been heavily discussed in blogs and foruns, but hey it’s never too much to remember: Java is pass-by-value!

I’ve done the following program to help understanding the issue:

class Test {
  public static void main (String[] args) {
    Person p1 = new Person("PPires The Master of The Universe");
    System.out.println("Person name is " + p1.getName());

    // now let's change name
    changeName(p1);

    /*
     * OK by now, if Java is passing 'p1' as a reference everything
     * in the method 'changeName' shall be reflected.
     */
    System.out.println("Person name NOW is " + p1.getName());
  }

  static void changeName (Person p) {
    p.setName("César é lhammu!");

    /*
     * If "p" is a reference, then the instance of "p" will now be changed!
     * Else the instance will be the same and name will be "César é lhammu!"
     */
    p = new Person("O João Pereira já não dá uma pra caixa..");
  }
}

class Person {
  String _name;

  public String getName() {
    return this._name;
  }

  public void setName(String name) {
    System.out.println("Setting Person name to " + name);
    this._name = name;
  }

  public Person(String name) {
    this._name = name;
  }
}

This prints out:

ppires@davinci:~$ javac Test.java
ppires@davinci:~$ java Test
Person name is PPires The Master of The Universe
Setting Person name to César é lhammu!
Person name NOW is César é lhammu!

Get the point? For more detailed info check out this link provided by the usual suspect, once again!

Oh, and btw, the names used in this proof-of-concept are totally fruit of my mind. Any similarities with dead or living people is pure coincidence!

11 thoughts on “Java passes parameters by value or by reference?

  1. Miguel says:

    But that’s not a pure “by value”

    If only the value was passed, the final result was “Person name NOW is PPires The Master of The Universe” because changeName would receive a copy of p1

  2. Java has pointers, and the value of the pointer is passed in. There’s no way to actually pass an object itself as a parameter. You can only pass a pointer to an object, therefore a value.

  3. So, you’re saying that passing a pointer to an object is passing by value? What would you consider as passing by reference?

    From what I remember, passing an object by value creates a copy of the object, not a copy of the pointer to the object. Using this definition, java would be “pass by reference” for objects and “pass by value” for primitive types (like int and long).

    Also, be careful with your tests with String because this class is, unlike others, an immutable object, for performance reasons (see http://en.wikipedia.org/wiki/Immutable_object)

  4. Rui says:

    Discussions between the usual suspetcs? I want in!

    Anyway, you’re stating the obvious… that pointers are themselves passed by value. In changeName() the variable p is always at the same place in memory but its contents (the reference value) change when you create a new instance of Person. And from the moment you create a new instance and put its adress over the adress that p help, you’re no longer modifying the original object when manipulating p.

    Hope this makes sense😉

  5. Hello.

    This “java is pass-by-value” can be easily explained on a “debugger” to a newbie, because you will see that you will have 2 objects of type Person in memory instead of one ( if you stop on the right spot, of course ).

    Just one quick story:

    A few weeks ago another fellow developer asked me if i was using design patterns on my work. I told him that i didn’t knew nothing about design patterns and the guy was amazed. Not that i don’t know what design paterns in “software engineering” is, but i’m really sick of people using keywords without really understand them.

    That’s why everybody should avoid specific technology questions on a job interview.

    If the person is smart enough, that person will learn fast, so there’s really no need to ask if “java is passing parameters by value or by reference” or if you use “design patterns” or even “quicksort” related remarks.

    ( it happened once to me, and my answer was something like: “sorry, i thought this was a job interview and if you really want the answer just give me a quick sorted list of seconds to search for it on altavista” ).

    Now, if we are talking to the usual suspect…🙂

  6. @Olavo I totally agree with you. The conversation started because we we’re talking about people that put stuff like Java into their CV’s but they actually do not know “anything” about Java, not even the basics of the language itself.
    So this was not about job interviews, but about people selling stuff they don’t have.

  7. Pedro Francisco says:

    Não me apetece escrever em EN, fica em PT:
    Uma notazinha a dizer isto:

    In Java,

    Dog d; // Java

    is exactly like C or C++’s

    Dog *d; // C++

    Facilitava muito a compreensão de pessoal que não saiba Java🙂 eu fiquei confuso e com a mesma dúvida do gajo do primeiro comentário, e só com a página que referi fiquei esclarecido.

    Portanto sim, é passado por valor, o truque é que Dog d em Java == Dog* d em C++, como referido na quote…

  8. luuuis says:

    I’m guessing the designers of the language decided to use the term “reference” instead of “pointer” to avoid bringing up all the negative memories it would conjure in C/C++ programmers, when in fact it behaves just like a pointer (pointer arithmetic excepted).

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s