Why does java doesn't support pass by reference? Is there any specific reason for that?*
-
1Could you cite an example/doc which says this? – Snakes and Coffee Mar 18 '13 at 07:11
-
@SnakesandCoffee - says what? That Java use purely pass by value? Try the linked Question for a start. Or the Java Tutorial. Or any half decent Java text book. Or if that's not definitive enough for you, try the JLS. – Stephen C Mar 19 '13 at 00:36
-
@StephenC My comment was posted far before the link was added – Snakes and Coffee Mar 19 '13 at 01:09
-
@SnakesandCoffee - not withstanding that, the Java Tutorial, text books, the JLS ... and even Google ... existed before you posted the comment. Is > 10 years before your comment far enough before for you? – Stephen C Mar 19 '13 at 02:21
3 Answers
Why does java doesn't support pass by reference?
Java is indeed pass-by-value. However, you can still pass an object reference into a method. Even though the reference is passed by value, the overall effect is almost indistinguishable from pass-by-reference.
What is not supported is references to primitive types.
-
+1 for the 'overall' effect statement. I could not frame a coherent sentence that could tell what I wanted to tell – Aniket Inge Mar 18 '13 at 07:16
-
1"the overall effect is indistinguishable from pass-by-reference" Of course not. It is very distinguishable -- with pass-by-reference, you can always assign to a by-reference parameter inside the function, and it will do the same thing as if you assigned (i.e. with `=`) to the passed variable in the calling scope. That is something you cannot do with a pass-by-value language like Java. – newacct Mar 18 '13 at 18:55
-
@newacct: That depends on the language. By way of example, C++ has pass-by-reference but none of the semantics that you have outlined (by "assigning to a reference" I assume you mean rebinding the reference to a different object). – NPE Mar 18 '13 at 20:02
-
Is there any specific reason for that?
That is the language design.
It supports pass by reference in a different sense that the reference is passed by value.
See this: http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.1

- 13,752
- 1
- 36
- 71
Actually in Java everything is passed by value.
When you say Objects are passed by reference, that means Object reference is passed by value.
This is basically a design decision taken by Java designers, to make the language simple and the code easier to debug.

- 819
- 9
- 20