4

I am coming from C/C++ world. I noticed in many posts that people do not accept to say that in Java there is "pass by reference" (for non-primitives); their argument is that, in this case, a copy of the reference is taken. I could not understand this justification since this is actually what happens in C when we pass by reference (a copy of the pointer is taken). For my little understanding in Java, I would say:

  • Primitive types are passed by value.
  • Non primitive types are passed by reference.

Am I wrong?

aLogic
  • 125
  • 1
  • 8
  • As far as I understand, speaking to a C or C++ programmer I would say that object pointers are passed by value, so in function you can modify the original object, but you can not overwrite the original reference to it. But I have practically 0 knowledge in Java. – UldisK Apr 08 '13 at 11:12
  • 4
    In this strict sense of the word, C doesn't have pass by reference *either.* It has "pass by pointer," just like Java. This is in contrast to C++, which has genuine pass by referece. – Angew is no longer proud of SO Apr 08 '13 at 11:13
  • Thanks. You are very true. C has no pass by reference. Now I understand the difference Java vs C vs C++. – aLogic Apr 08 '13 at 11:21

1 Answers1

4

In C++, consider the function: void func(Type &arg);. Here, if you change arg (not the contents of arg but the actual variable), the caller's view of the passed in argument has changed -- completely. This is pass by reference. Contrast that with void func(Type *arg);. Here, you can change the contents of arg but if you assign arg to something, it's a local change only, due to pass-by-value of a pointer.

In Java, you're using pass by (invisible) pointer on all complex types.

mah
  • 39,056
  • 9
  • 76
  • 93
  • "(invisible)" It's not invisible. It's just that the syntax for object pointers is different in Java. – newacct Apr 08 '13 at 17:43