<p>I always thought Java uses <strong>pass-by-reference</strong>.</p>
<p>However, I've seen <a href="http://javadude.com/articles/passbyvalue.htm" rel="noreferrer">a blog post</a> that claims that Java uses <strong>pass-by-value</strong>.</p>
<p>I don't think I understand the distinction they're making.</p>
<p>What is the explanation?</p>

[{'answer_id': 40499, 'author': 'SCdF', 'author_id': 1666, 'author_profile': 'https://Stackoverflow.com/users/1666', 'pm_score': 10, 'selected': False, 'text': '<p>Java is always pass by value, with no exceptions, <strong>ever</strong>.</p>\n\n<p>So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java <strong>never</strong> provides direct access to the values of <em>objects themselves</em>, in <em>any</em> circumstances. The only access to objects is through a <em>reference</em> to that object. Because Java objects are <em>always</em> accessed through a reference, rather than directly, it is common to talk about fields and variables <em>and method arguments</em> as being <em>objects</em>, when pedantically they are only <em>references to objects</em>. <strong>The confusion stems from this (strictly speaking, incorrect) change in nomenclature.</strong></p>\n\n<p>So, when calling a method</p>\n\n<ul>\n<li>For primitive arguments (<code>int</code>, <code>long</code>, etc.), the pass by value is <em>the actual value</em> of the primitive (for example, 3).</li>\n<li>For objects, the pass by value is the value of <em>the reference to the object</em>.</li>\n</ul>\n\n<p>So if you have <code>doSomething(foo)</code> and <code>public void doSomething(Foo foo) { .. }</code> the two Foos have copied <em>references</em> that point to the same objects.</p>\n\n<p>Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.</p>\n'}, {'answer_id': 40501, 'author': 'ScArcher2', 'author_id': 1310, 'author_profile': 'https://Stackoverflow.com/users/1310', 'pm_score': 9, 'selected': False, 'text': "<p>Java passes references by value.</p>\n\n<p>So you can't change the reference that gets passed in.</p>\n"}, {'answer_id': 40507, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 8, 'selected': False, 'text': "<p>Basically, reassigning Object parameters doesn't affect the argument, e.g.,</p>\n<pre><code>private static void foo(Object bar) {\n    bar = null;\n}\n\npublic static void main(String[] args) {\n    String baz = &quot;Hah!&quot;;\n    foo(baz);\n    System.out.println(baz);\n}\n</code></pre>\n<p>will print out <code>&quot;Hah!&quot;</code> instead of <code>null</code>. The reason this works is because <code>bar</code> is a copy of the value of <code>baz</code>, which is just a reference to <code>&quot;Hah!&quot;</code>. If it were the actual reference itself, then <code>foo</code> would have redefined <code>baz</code> to <code>null</code>.</p>\n"}, {'answer_id': 40514, 'author': 'John Channing', 'author_id': 3305, 'author_profile': 'https://Stackoverflow.com/users/3305', 'pm_score': 8, 'selected': False, 'text': '<p>Java passes references to objects by value.</p>\n'}, {'answer_id': 40523, 'author': 'erlando', 'author_id': 4192, 'author_profile': 'https://Stackoverflow.com/users/4192', 'pm_score': 13, 'selected': False, 'text': '<p>The terms &quot;pass-by-value&quot; and &quot;pass-by-reference&quot; have special, <a href="https://en.wikipedia.org/w/index.php?title=Pass-by-value" rel="noreferrer">precisely defined</a> meanings in computer science. These meanings differ from the intuition many people have when first hearing the terms. Much of the confusion in this discussion seems to come from this fact.</p>\n<p>The terms &quot;pass-by-value&quot; and &quot;pass-by-reference&quot; are talking about <em>variables.</em> Pass-by-value means that the <em>value</em> of a variable is passed to a function/method. Pass-by-reference means that a <em>reference</em> to that variable is passed to the function. The latter gives the function a way to change the contents of the variable.</p>\n<p>By those definitions, Java is always <strong>pass-by-value</strong>.  Unfortunately, when we deal with variables holding objects we are really dealing with object-handles called <em>references</em> which are passed-by-value as well.  This terminology and semantics easily confuse many beginners.</p>\n<p>It goes like this:</p>\n<pre><code>public static void main(String[] args) {\n    Dog aDog = new Dog(&quot;Max&quot;);\n    Dog oldDog = aDog;\n\n    // we pass the object to foo\n    foo(aDog);\n    // aDog variable is still pointing to the &quot;Max&quot; dog when foo(...) returns\n    aDog.getName().equals(&quot;Max&quot;); // true\n    aDog.getName().equals(&quot;Fifi&quot;); // false\n    aDog == oldDog; // true\n}\n\npublic static void foo(Dog d) {\n    d.getName().equals(&quot;Max&quot;); // true\n    // change d inside of foo() to point to a new Dog instance &quot;Fifi&quot;\n    d = new Dog(&quot;Fifi&quot;);\n    d.getName().equals(&quot;Fifi&quot;); // true\n}\n</code></pre>\n<p>In the example above <code>aDog.getName()</code> will still return <code>&quot;Max&quot;</code>. The value <code>aDog</code> within <code>main</code> is not changed in the function <code>foo</code> with the <code>Dog</code> <code>&quot;Fifi&quot;</code> as the object reference is passed by value. If it were passed by reference, then the <code>aDog.getName()</code> in <code>main</code> would return <code>&quot;Fifi&quot;</code> after the call to <code>foo</code>.</p>\n<p>Likewise:</p>\n<pre><code>public static void main(String[] args) {\n    Dog aDog = new Dog(&quot;Max&quot;);\n    Dog oldDog = aDog;\n\n    foo(aDog);\n    // when foo(...) returns, the name of the dog has been changed to &quot;Fifi&quot;\n    aDog.getName().equals(&quot;Fifi&quot;); // true\n    // but it is still the same dog:\n    aDog == oldDog; // true\n}\n\npublic static void foo(Dog d) {\n    d.getName().equals(&quot;Max&quot;); // true\n    // this changes the name of d to be &quot;Fifi&quot;\n    d.setName(&quot;Fifi&quot;);\n}\n</code></pre>\n<p>In the above example, <code>Fifi</code> is the dog\'s name after call to <code>foo(aDog)</code> because the object\'s name was set inside of <code>foo(...)</code>. Any operations that <code>foo</code> performs on <code>d</code> are such that, for all practical purposes, they are performed on <code>aDog</code>, but it is <strong>not</strong> possible to change the value of the variable <code>aDog</code> itself.</p>\n<p>For more information on pass by reference and pass by value, consult the following answer: <a href="https://stackoverflow.com/a/430958/6005228">https://stackoverflow.com/a/430958/6005228</a>. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.</p>\n'}, {'answer_id': 40630, 'author': 'Paul de Vrieze', 'author_id': 4100, 'author_profile': 'https://Stackoverflow.com/users/4100', 'pm_score': 5, 'selected': False, 'text': '<p>To make a long story short, <a href="http://en.wikipedia.org/wiki/Java_%28programming_language%29" rel="noreferrer">Java</a> objects have some very peculiar properties.</p>\n\n<p>In general, Java has primitive types (<code>int</code>, <code>bool</code>, <code>char</code>, <code>double</code>, etc) that are passed directly by value. Then Java has objects (everything that derives from <code>java.lang.Object</code>). Objects are actually always handled through a reference (a reference being a pointer that you can\'t touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.</p>\n\n<p>Does this sound strange and confusing? Let\'s consider how C implements pass by reference and pass by value. In C, the default convention is pass by value. <code>void foo(int x)</code> passes an int by value. <code>void foo(int *x)</code> is a function that does not want an <code>int a</code>, but a pointer to an int: <code>foo(&amp;a)</code>. One would use this with the <code>&amp;</code> operator to pass a variable address.</p>\n\n<p>Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation: <code>void foo(int &amp;x)</code> is called by <code>foo(a)</code>, where the compiler itself knows that it is a reference and the address of the non-reference <code>a</code> should be passed. In Java, all variables referring to objects are actually of reference type, in effect forcing call by reference for most intends and purposes without the fine grained control (and complexity) afforded by, for example, C++.</p>\n'}, {'answer_id': 42392, 'author': 'shsteimer', 'author_id': 292, 'author_profile': 'https://Stackoverflow.com/users/292', 'pm_score': 6, 'selected': False, 'text': '<p>The distinction, or perhaps just the way I remember as I used to be under the same impression as the original poster is this: Java is always pass by value. All objects( in Java, anything except for primitives) in Java are references. These references are passed by value.</p>\n'}, {'answer_id': 42455, 'author': 'pek', 'author_id': 2644, 'author_profile': 'https://Stackoverflow.com/users/2644', 'pm_score': 5, 'selected': False, 'text': '<p>As many people mentioned it before, <a href="http://academic.regis.edu/dbahr/GeneralPages/IntroToProgramming/JavaPassByValue.htm" rel="noreferrer">Java is always pass-by-value</a></p>\n\n<p>Here is another example that will help you understand the difference (<a href="http://www.javaranch.com/campfire/StoryPassBy.jsp" rel="noreferrer">the classic swap example</a>):</p>\n\n<pre><code>public class Test {\n  public static void main(String[] args) {\n    Integer a = new Integer(2);\n    Integer b = new Integer(3);\n    System.out.println("Before: a = " + a + ", b = " + b);\n    swap(a,b);\n    System.out.println("After: a = " + a + ", b = " + b);\n  }\n\n  public static swap(Integer iA, Integer iB) {\n    Integer tmp = iA;\n    iA = iB;\n    iB = tmp;\n  }\n}\n</code></pre>\n\n<p>Prints:  </p>\n\n<blockquote>\n  <p>Before: a = 2, b = 3<br>\n  After: a = 2, b = 3</p>\n</blockquote>\n\n<p>This happens because iA and iB are new local reference variables that have the same value of the passed references (they point to a and b respectively). So, trying to change the references of iA or iB will only change in the local scope and not outside of this method.</p>\n'}, {'answer_id': 49857, 'author': 'SWD', 'author_id': 3034, 'author_profile': 'https://Stackoverflow.com/users/3034', 'pm_score': 5, 'selected': False, 'text': '<p>I always think of it as "pass by copy". It is a copy of the value be it primitive or reference. If it is a primitive it is a copy of the bits that are the value and if it is an Object it is a copy of the reference.</p>\n\n<pre><code>public class PassByCopy{\n    public static void changeName(Dog d){\n        d.name = "Fido";\n    }\n    public static void main(String[] args){\n        Dog d = new Dog("Maxx");\n        System.out.println("name= "+ d.name);\n        changeName(d);\n        System.out.println("name= "+ d.name);\n    }\n}\nclass Dog{\n    public String name;\n    public Dog(String s){\n        this.name = s;\n    }\n}\n</code></pre>\n\n<p>output of java PassByCopy:</p>\n\n<blockquote>\n  <p>name= Maxx<br>\n  name= Fido</p>\n</blockquote>\n\n<p>Primitive wrapper classes and Strings are immutable so any example using those types will not work the same as other types/objects.</p>\n'}, {'answer_id': 49863, 'author': 'sven', 'author_id': 46, 'author_profile': 'https://Stackoverflow.com/users/46', 'pm_score': 5, 'selected': False, 'text': '<p>I have created a thread devoted to these kind of questions for <em>any</em> programming languages <a href="https://stackoverflow.com/questions/2027/pass-by-reference-or-pass-by-value">here</a>.</p>\n\n<p><a href="https://stackoverflow.com/questions/2027/pass-by-reference-or-pass-by-value#2028">Java is also mentioned</a>. Here is the short summary:</p>\n\n<ul>\n<li>Java passes it parameters by value</li>\n<li>"by value" is the only way in java to pass a parameter to a method</li>\n<li>using methods from the object given as parameter will alter the\nobject as the references point to\nthe original objects. (if that\nmethod itself alters some values)</li>\n</ul>\n'}, {'answer_id': 73021, 'author': 'Scott Stanchfield', 'author_id': 12541, 'author_profile': 'https://Stackoverflow.com/users/12541', 'pm_score': 12, 'selected': False, 'text': '<p>I just noticed you referenced <a href="http://javadude.com/articles/passbyvalue.htm" rel="noreferrer">my article</a>.</p>\n<p>The Java Spec says that everything in Java is pass-by-value. There is no such thing as &quot;pass-by-reference&quot; in Java.</p>\n<p>The key to understanding this is that something like</p>\n<pre><code>Dog myDog;\n</code></pre>\n<p>is <em>not</em> a Dog; it\'s actually a <em>pointer</em> to a Dog. The use of the term &quot;reference&quot; in Java is very misleading and is what causes most of the confusion here. What they call &quot;references&quot; act/feel more like what we\'d call &quot;pointers&quot; in most other languages.</p>\n<p>What that means, is when you have</p>\n<pre><code>Dog myDog = new Dog(&quot;Rover&quot;);\nfoo(myDog);\n</code></pre>\n<p>you\'re essentially passing the <em>address</em> of the created <code>Dog</code> object to the <code>foo</code> method.</p>\n<p>(I say essentially because Java pointers/references aren\'t direct addresses, but it\'s easiest to think of them that way.)</p>\n<p>Suppose the <code>Dog</code> object resides at memory address 42. This means we pass 42 to the method.</p>\n<p>if the Method were defined as</p>\n<pre><code>public void foo(Dog someDog) {\n    someDog.setName(&quot;Max&quot;);     // AAA\n    someDog = new Dog(&quot;Fifi&quot;);  // BBB\n    someDog.setName(&quot;Rowlf&quot;);   // CCC\n}\n</code></pre>\n<p>let\'s look at what\'s happening.</p>\n<ul>\n<li>the parameter <code>someDog</code> is set to the value 42</li>\n<li>at line &quot;AAA&quot;\n<ul>\n<li><code>someDog</code> is followed to the <code>Dog</code> it points to (the <code>Dog</code> object at address 42)</li>\n<li>that <code>Dog</code> (the one at address 42) is asked to change his name to Max</li>\n</ul>\n</li>\n<li>at line &quot;BBB&quot;\n<ul>\n<li>a new <code>Dog</code> is created. Let\'s say he\'s at address 74</li>\n<li>we assign the parameter <code>someDog</code> to 74</li>\n</ul>\n</li>\n<li>at line &quot;CCC&quot;\n<ul>\n<li>someDog is followed to the <code>Dog</code> it points to (the <code>Dog</code> object at address 74)</li>\n<li>that <code>Dog</code> (the one at address 74) is asked to change his name to Rowlf</li>\n</ul>\n</li>\n<li>then, we return</li>\n</ul>\n<p>Now let\'s think about what happens outside the method:</p>\n<p><em>Did <code>myDog</code> change?</em></p>\n<p>There\'s the key.</p>\n<p>Keeping in mind that <code>myDog</code> is a <em>pointer</em>, and not an actual <code>Dog</code>, the answer is NO. <code>myDog</code> still has the value 42; it\'s still pointing to the original <code>Dog</code> (but note that because of line &quot;AAA&quot;, its name is now &quot;Max&quot; - still the same Dog; <code>myDog</code>\'s value has not changed.)</p>\n<p>It\'s perfectly valid to <em>follow</em> an address and change what\'s at the end of it; that does not change the variable, however.</p>\n<p>Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, the caller will not see any changes you make to where that pointer points. (In a language with pass-by-reference semantics, the method function <em>can</em> change the pointer and the caller will see that change.)</p>\n<p>In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed.</p>\n<p>If Java had pass-by-reference semantics, the <code>foo</code> method we defined above would have changed where <code>myDog</code> was pointing when it assigned <code>someDog</code> on line BBB.</p>\n<p>Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.</p>\n<h2>Update</h2>\n<p>A discussion in the comments warrants some clarification...</p>\n<p>In C, you can write</p>\n<pre class="lang-c prettyprint-override"><code>void swap(int *x, int *y) {\n    int t = *x;\n    *x = *y;\n    *y = t;\n}\n\nint x = 1;\nint y = 2;\nswap(&amp;x, &amp;y);\n</code></pre>\n<p>This is not a special case in C. Both languages use pass-by-value semantics. Here the call site is creating additional data structure to assist the function to access and manipulate data.</p>\n<p>The function is being passed pointers to data, and follows those pointers to access and modify that data.</p>\n<p>A similar approach in Java, where the caller sets up assisting structure, might be:</p>\n<pre class="lang-java prettyprint-override"><code>void swap(int[] x, int[] y) {\n    int temp = x[0];\n    x[0] = y[0];\n    y[0] = temp;\n}\n\nint[] x = {1};\nint[] y = {2};\nswap(x, y);\n</code></pre>\n<p>(or if you wanted both examples to demonstrate features the other language doesn\'t have, create a mutable IntWrapper class to use in place of the arrays)</p>\n<p>In these cases, both C and Java are <em>simulating</em> pass-by-reference. They\'re still both passing values (pointers to ints or arrays), and following those pointers inside the called function to manipulate the data.</p>\n<p>Pass-by-reference is all about the function <em>declaration/definition</em>, and how it handles its parameters. Reference semantics apply to <em>every</em> call to that function, and the call site only needs to pass variables, no additional data structure.</p>\n<p>These simulations require the call site and the function to cooperate. No doubt it\'s useful, but it\'s still pass-by-value.</p>\n'}, {'answer_id': 85711, 'author': 'Eclipse', 'author_id': 8701, 'author_profile': 'https://Stackoverflow.com/users/8701', 'pm_score': 8, 'selected': False, 'text': '<p>Just to show the contrast, compare the following <a href="https://en.wikipedia.org/wiki/C++" rel="noreferrer">C++</a> and <a href="http://en.wikipedia.org/wiki/Java_%28programming_language%29" rel="noreferrer">Java</a> snippets:</p>\n\n<p>In C++: <strong>Note: Bad code - memory leaks!</strong>  But it demonstrates the point.</p>\n\n<pre><code>void cppMethod(int val, int &amp;ref, Dog obj, Dog &amp;objRef, Dog *objPtr, Dog *&amp;objPtrRef)\n{\n    val = 7; // Modifies the copy\n    ref = 7; // Modifies the original variable\n    obj.SetName("obj"); // Modifies the copy of Dog passed\n    objRef.SetName("objRef"); // Modifies the original Dog passed\n    objPtr-&gt;SetName("objPtr"); // Modifies the original Dog pointed to \n                               // by the copy of the pointer passed.\n    objPtr = new Dog("newObjPtr");  // Modifies the copy of the pointer, \n                                   // leaving the original object alone.\n    objPtrRef-&gt;SetName("objRefPtr"); // Modifies the original Dog pointed to \n                                    // by the original pointer passed. \n    objPtrRef = new Dog("newObjPtrRef"); // Modifies the original pointer passed\n}\n\nint main()\n{\n    int a = 0;\n    int b = 0;\n    Dog d0 = Dog("d0");\n    Dog d1 = Dog("d1");\n    Dog *d2 = new Dog("d2");\n    Dog *d3 = new Dog("d3");\n    cppMethod(a, b, d0, d1, d2, d3);\n    // a is still set to 0\n    // b is now set to 7\n    // d0 still have name "d0"\n    // d1 now has name "objRef"\n    // d2 now has name "objPtr"\n    // d3 now has name "newObjPtrRef"\n}\n</code></pre>\n\n<p>In Java, </p>\n\n<pre><code>public static void javaMethod(int val, Dog objPtr)\n{\n   val = 7; // Modifies the copy\n   objPtr.SetName("objPtr") // Modifies the original Dog pointed to \n                            // by the copy of the pointer passed.\n   objPtr = new Dog("newObjPtr");  // Modifies the copy of the pointer, \n                                  // leaving the original object alone.\n}\n\npublic static void main()\n{\n    int a = 0;\n    Dog d0 = new Dog("d0");\n    javaMethod(a, d0);\n    // a is still set to 0\n    // d0 now has name "objPtr"\n}\n</code></pre>\n\n<p>Java only has the two types of passing: by value for built-in types, and by value of the pointer for object types.</p>\n'}, {'answer_id': 436924, 'author': 'Harald Schilly', 'author_id': 54236, 'author_profile': 'https://Stackoverflow.com/users/54236', 'pm_score': 4, 'selected': False, 'text': "<p>It's a bit hard to understand, but Java always copies the value - the point is, normally the value is a reference. Therefore you end up with the same object without thinking about it...</p>\n"}, {'answer_id': 436969, 'author': 'JacquesB', 'author_id': 7488, 'author_profile': 'https://Stackoverflow.com/users/7488', 'pm_score': 7, 'selected': False, 'text': '<p>The crux of the matter is that the word <em>reference</em> in the expression "pass by reference" means something completely different from the usual meaning of the word <em>reference</em> in Java. </p>\n\n<p>Usually in Java <em>reference</em> means a a <em>reference to an object</em>. But the technical terms <em>pass by reference/value</em> from programming language theory is talking about a <em>reference to the memory cell holding the variable</em>, which is something completely different.</p>\n'}, {'answer_id': 623155, 'author': 'Jared Oberhaus', 'author_id': 73019, 'author_profile': 'https://Stackoverflow.com/users/73019', 'pm_score': 6, 'selected': False, 'text': '<p>You can never pass by reference in Java, and one of the ways that is obvious is when you want to return more than one value from a method call. Consider the following bit of code in C++:</p>\n\n<pre><code>void getValues(int&amp; arg1, int&amp; arg2) {\n    arg1 = 1;\n    arg2 = 2;\n}\nvoid caller() {\n    int x;\n    int y;\n    getValues(x, y);\n    cout &lt;&lt; "Result: " &lt;&lt; x &lt;&lt; " " &lt;&lt; y &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Sometimes you want to use the same pattern in Java, but you can\'t; at least not directly. Instead you could do something like this:</p>\n\n<pre><code>void getValues(int[] arg1, int[] arg2) {\n    arg1[0] = 1;\n    arg2[0] = 2;\n}\nvoid caller() {\n    int[] x = new int[1];\n    int[] y = new int[1];\n    getValues(x, y);\n    System.out.println("Result: " + x[0] + " " + y[0]);\n}\n</code></pre>\n\n<p>As was explained in previous answers, in Java you\'re passing a pointer to the array as a value into <code>getValues</code>. That is enough, because the method then modifies the array element, and by convention you\'re expecting element 0 to contain the return value. Obviously you can do this in other ways, such as structuring your code so this isn\'t necessary, or constructing a class that can contain the return value or allow it to be set. But the simple pattern available to you in C++ above is not available in Java.</p>\n'}, {'answer_id': 707416, 'author': 'kukudas', 'author_id': 48402, 'author_profile': 'https://Stackoverflow.com/users/48402', 'pm_score': 6, 'selected': False, 'text': '<p>As far as I know, Java only knows call by value. This means for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects. However I think there are some pitfalls; for example, this will not work:</p>\n\n<pre><code>public static void swap(StringBuffer s1, StringBuffer s2) {\n    StringBuffer temp = s1;\n    s1 = s2;\n    s2 = temp;\n}\n\n\npublic static void main(String[] args) {\n    StringBuffer s1 = new StringBuffer("Hello");\n    StringBuffer s2 = new StringBuffer("World");\n    swap(s1, s2);\n    System.out.println(s1);\n    System.out.println(s2);\n}\n</code></pre>\n\n<p>This will populate Hello World and not World Hello because in the swap function you use copys which have no impact on the references in the main. But if your objects are not immutable you can change it for example:</p>\n\n<pre><code>public static void appendWorld(StringBuffer s1) {\n    s1.append(" World");\n}\n\npublic static void main(String[] args) {\n    StringBuffer s = new StringBuffer("Hello");\n    appendWorld(s);\n    System.out.println(s);\n}\n</code></pre>\n\n<p>This will populate Hello World on the command line. If you change StringBuffer into String it will produce just Hello because String is immutable. For example:</p>\n\n<pre><code>public static void appendWorld(String s){\n    s = s+" World";\n}\n\npublic static void main(String[] args) {\n    String s = new String("Hello");\n    appendWorld(s);\n    System.out.println(s);\n}\n</code></pre>\n\n<p>However you could make a wrapper for String like this which would make it able to use it with Strings:</p>\n\n<pre><code>class StringWrapper {\n    public String value;\n\n    public StringWrapper(String value) {\n        this.value = value;\n    }\n}\n\npublic static void appendWorld(StringWrapper s){\n    s.value = s.value +" World";\n}\n\npublic static void main(String[] args) {\n    StringWrapper s = new StringWrapper("Hello");\n    appendWorld(s);\n    System.out.println(s.value);\n}\n</code></pre>\n\n<p>edit: i believe this is also the reason to use StringBuffer when it comes to "adding" two Strings because you can modifie the original object which u can\'t with immutable objects like String is.</p>\n'}, {'answer_id': 1964260, 'author': 'Rusty Shackleford', 'author_id': 238938, 'author_profile': 'https://Stackoverflow.com/users/238938', 'pm_score': 5, 'selected': False, 'text': '<p>A few corrections to some posts.</p>\n\n<p>C does NOT support pass by reference. It is ALWAYS pass by value. C++ does support pass by reference, but is not the default and is quite dangerous.</p>\n\n<p>It doesn\'t matter what the value is in Java: primitive or address(roughly) of object, it is ALWAYS passed by value.</p>\n\n<p>If a Java object "behaves" like it is being passed by reference, that is a property of mutability and has absolutely nothing to do with passing mechanisms.</p>\n\n<p>I am not sure why this is so confusing, perhaps because so many Java "programmers" are not formally trained, and thus do not understand what is really going on in memory?</p>\n'}, {'answer_id': 1964361, 'author': 'fastcodejava', 'author_id': 184730, 'author_profile': 'https://Stackoverflow.com/users/184730', 'pm_score': 5, 'selected': False, 'text': '<p>Java copies the reference by value. So if you change it to something else (e.g, using <code>new</code>) the reference does not change outside the method. For native types, it is always pass by value.</p>\n'}, {'answer_id': 3439923, 'author': 'Vinay Lodha', 'author_id': 212665, 'author_profile': 'https://Stackoverflow.com/users/212665', 'pm_score': 4, 'selected': False, 'text': '<p>Have a look at this code. This code will not throw <code>NullPointerException</code>... It will print "Vinay"</p>\n\n<pre><code>public class Main {\n    public static void main(String[] args) {\n        String temp = "Vinay";\n        print(temp);\n        System.err.println(temp);\n    }\n\n    private static void print(String temp) {\n        temp = null;\n    }\n}\n</code></pre>\n\n<p>If Java is pass by reference then it should have thrown <code>NullPointerException</code> as reference is set to Null.</p>\n'}, {'answer_id': 3663123, 'author': 'Jörg W Mittag', 'author_id': 2988, 'author_profile': 'https://Stackoverflow.com/users/2988', 'pm_score': 7, 'selected': False, 'text': '<p>I can\'t believe that nobody mentioned Barbara Liskov yet. When she designed CLU in 1974, she ran into this same terminology problem, and she invented the term <em>call by sharing</em> (also known as <em>call by object-sharing</em> and <em>call by object</em>) for this specific case of "call by value where the value is a reference".</p>\n'}, {'answer_id': 7034719, 'author': 'Marsellus Wallace', 'author_id': 807231, 'author_profile': 'https://Stackoverflow.com/users/807231', 'pm_score': 10, 'selected': False, 'text': '<p><strong>This will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you\'ll just smile :-)</strong></p>\n\n<p>Step one please erase from your mind that word that starts with \'p\' "_ _ _ _ _ _ _", especially if you come from other programming languages. Java and \'p\' cannot be written in the same book, forum, or even txt.</p>\n\n<p>Step two remember that when you pass an Object into a method you\'re passing the Object reference and not the Object itself.</p>\n\n<ul>\n<li><em>Student</em>: Master, does this mean that Java is pass-by-reference?</li>\n<li><em>Master</em>: Grasshopper, No.</li>\n</ul>\n\n<p>Now think of what an Object\'s reference/variable does/is:</p>\n\n<ol>\n<li><strong>A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).</strong></li>\n<li>When passing arguments to a method <strong>you ARE NOT passing the reference variable, but a copy of the bits in the reference variable</strong>. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.</li>\n<li>So you\'re just passing 3bad086a that it\'s the value of the reference.</li>\n<li>You\'re passing the value of the reference and not the reference itself (and not the object).</li>\n<li><strong><em>This value is actually COPIED and given to the method</em></strong>. </li>\n</ol>\n\n<p>In the following (please don\'t try to compile/execute this...):</p>\n\n<pre><code>1. Person person;\n2. person = new Person("Tom");\n3. changeName(person);\n4.\n5. //I didn\'t use Person person below as an argument to be nice\n6. static void changeName(Person anotherReferenceToTheSamePersonObject) {\n7.     anotherReferenceToTheSamePersonObject.setName("Jerry");\n8. }\n</code></pre>\n\n<p>What happens?</p>\n\n<ul>\n<li>The variable <em>person</em> is created in line #1 and it\'s null at the beginning.</li>\n<li>A new Person Object is created in line #2, stored in memory, and the variable <em>person</em> is given the reference to the Person object. That is, its address. Let\'s say 3bad086a.</li>\n<li>The variable <em>person</em> holding the address of the Object is passed to the function in line #3.</li>\n<li>In line #4 you can listen to the sound of silence </li>\n<li>Check the comment on line #5</li>\n<li>A method local variable -<em>anotherReferenceToTheSamePersonObject</em>- is created and then comes the magic in line #6:\n\n<ul>\n<li>The variable/reference <em>person</em> is copied bit-by-bit and passed to <em>anotherReferenceToTheSamePersonObject</em> inside the function.</li>\n<li>No new instances of Person are created.</li>\n<li>Both "<em>person</em>" and "<em>anotherReferenceToTheSamePersonObject</em>" hold the same value of 3bad086a.</li>\n<li>Don\'t try this but person==anotherReferenceToTheSamePersonObject would be true.</li>\n<li>Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.</li>\n</ul></li>\n</ul>\n\n<p>A picture is worth a thousand words:</p>\n\n<p><img src="https://i.stack.imgur.com/Ba3hJ.jpg" alt="Pass by Value"></p>\n\n<p><strong>Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!</strong></p>\n\n<p>If you didn\'t get it then just trust me and remember that it\'s better to say that <strong>Java is pass by value</strong>. Well, <strong>pass by reference value</strong>. Oh well, even better is <strong><em>pass-by-copy-of-the-variable-value! ;)</em></strong></p>\n\n<p>Now feel free to hate me but note that given this <strong>there is no difference between passing primitive data types and Objects</strong> when talking about method arguments.</p>\n\n<p>You always pass a copy of the bits of the value of the reference!</p>\n\n<ul>\n<li>If it\'s a primitive data type these bits will contain the value of the primitive data type itself.</li>\n<li>If it\'s an Object the bits will contain the value of the address that tells the JVM how to get to the Object.</li>\n</ul>\n\n<blockquote>\n  <p>Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you\'ll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n  <p>The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.</p>\n</blockquote>\n\n<hr>\n\n<p>Of course you can cut it short and just say that  <strong>Java is pass-by-value!</strong></p>\n'}, {'answer_id': 10236169, 'author': 'Luigi R. Viggiano', 'author_id': 258289, 'author_profile': 'https://Stackoverflow.com/users/258289', 'pm_score': 3, 'selected': False, 'text': '<p>Everything is passed by value. Primitives and Object references. But objects can be changed, if their interface allows it.</p>\n\n<p>When you pass an object to a method, you are passing a reference, and the object can be modified by the method implementation. </p>\n\n<pre><code>void bithday(Person p) {\n    p.age++;\n}\n</code></pre>\n\n<p>The reference of the object itself, is passed by value: you can reassign the parameter, but the change is not reflected back:</p>\n\n<pre><code>void renameToJon(Person p) { \n    p = new Person("Jon"); // this will not work\n}\n\njack = new Person("Jack");\nrenameToJon(jack);\nsysout(jack); // jack is unchanged\n</code></pre>\n\n<p>As matter of effect, "p" is reference (pointer to the object) and can\'t be changed. </p>\n\n<p>Primitive types are passed by value. Object\'s reference can be considered a primitive type too. </p>\n\n<p>To recap, everything is passed by value.</p>\n'}, {'answer_id': 11764499, 'author': 'Fernando Espinosa', 'author_id': 1426433, 'author_profile': 'https://Stackoverflow.com/users/1426433', 'pm_score': 4, 'selected': False, 'text': '<p>It\'s really quite, quite simple:</p>\n\n<p>For a variable of primitive type (eg. <code>int</code>, <code>boolean</code>, <code>char</code>, etc...), when you use its name for a method argument, you are passing the value contained in it (<code>5</code>, <code>true</code>, or <code>\'c\'</code>). This value gets "copied", and the variable retains its value even after the method invocation.</p>\n\n<p>For a variable of reference type (eg. <code>String</code>, <code>Object</code>, etc...), when you use its name for a method argument, you are passing the value contained in it (<em>the <strong>reference value</strong> that "points" to the object</em>). This <strong><em>reference value</em></strong> gets "copied", and the variable retains its value even after the method invocation. <strong><em>The reference variable keeps "pointing" to the same object.</em></strong></p>\n\n<p>Either way, you\'re always passing stuff by value.</p>\n\n<hr>\n\n<p>Compare this to say C++ where you can have a method to take an <code>int&amp;</code>, or in C# where you could have take a <code>ref int</code> (although, in this case, you also have to use the <code>ref</code> modifier when passing the variable\'s name to the method.)</p>\n'}, {'answer_id': 12429953, 'author': 'Eng.Fouad', 'author_id': 597657, 'author_profile': 'https://Stackoverflow.com/users/597657', 'pm_score': 11, 'selected': False, 'text': '<p>Java always passes arguments <em>by value</em>, NOT by reference.</p>\n<hr />\n<p>Let me explain this through an <a href="https://stackoverflow.com/a/9404727/597657">example</a>:</p>\n<pre class="lang-java prettyprint-override"><code>public class Main {\n\n     public static void main(String[] args) {\n          Foo f = new Foo(&quot;f&quot;);\n          changeReference(f); // It won\'t change the reference!\n          modifyReference(f); // It will modify the object that the reference variable &quot;f&quot; refers to!\n     }\n\n     public static void changeReference(Foo a) {\n          Foo b = new Foo(&quot;b&quot;);\n          a = b;\n     }\n\n     public static void modifyReference(Foo c) {\n          c.setAttribute(&quot;c&quot;);\n     }\n\n}\n</code></pre>\n<p>I will explain this in steps:</p>\n<ol>\n<li><p>Declaring a reference named <code>f</code> of type <code>Foo</code> and assign it a new object of type <code>Foo</code> with an attribute <code>&quot;f&quot;</code>.</p>\n<pre><code>Foo f = new Foo(&quot;f&quot;);\n</code></pre>\n<p><img src="https://i.stack.imgur.com/arXpP.png" alt="enter image description here" /></p>\n</li>\n<li><p>From the method side, a reference of type <code>Foo</code> with a name <code>a</code> is declared and it\'s initially assigned <code>null</code>.</p>\n<pre><code>public static void changeReference(Foo a)\n</code></pre>\n<p><img src="https://i.stack.imgur.com/k2LBD.png" alt="enter image description here" /></p>\n</li>\n<li><p>As you call the method <code>changeReference</code>, the reference <code>a</code> will be assigned the object which is passed as an argument.</p>\n<pre><code>changeReference(f);\n</code></pre>\n<p><img src="https://i.stack.imgur.com/1Ez74.png" alt="enter image description here" /></p>\n</li>\n<li><p>Declaring a reference named <code>b</code> of type <code>Foo</code> and assign it a new object of type <code>Foo</code> with an attribute <code>&quot;b&quot;</code>.</p>\n<pre><code>Foo b = new Foo(&quot;b&quot;);\n</code></pre>\n<p><img src="https://i.stack.imgur.com/Krx4N.png" alt="enter image description here" /></p>\n</li>\n<li><p><code>a = b</code> makes a new assignment to the reference <code>a</code>, <strong>not</strong> <code>f</code>, of the object whose attribute is <code>&quot;b&quot;</code>.</p>\n<p><img src="https://i.stack.imgur.com/rCluu.png" alt="enter image description here" /></p>\n</li>\n<li><p>As you call <code>modifyReference(Foo c)</code> method, a reference <code>c</code> is created and assigned the object with attribute <code>&quot;f&quot;</code>.</p>\n<p><img src="https://i.stack.imgur.com/PRZPg.png" alt="enter image description here" /></p>\n</li>\n<li><p><code>c.setAttribute(&quot;c&quot;);</code> will change the attribute of the object that reference <code>c</code> points to it, and it\'s the same object that reference <code>f</code> points to it.</p>\n<p><img src="https://i.stack.imgur.com/H9Qsf.png" alt="enter image description here" /></p>\n</li>\n</ol>\n<p>I hope you understand now how passing objects as arguments works in Java :)</p>\n'}, {'answer_id': 12851599, 'author': 'Herupkhart', 'author_id': 1733754, 'author_profile': 'https://Stackoverflow.com/users/1733754', 'pm_score': 6, 'selected': False, 'text': '<p>No, it\'s not pass by reference.</p>\n\n<p>Java is pass by value according to the Java Language Specification:</p>\n\n<blockquote>\n  <p>When the method or constructor is invoked (§15.12), <strong>the values of the actual argument expressions initialize newly created parameter variables</strong>, each of the declared type, before execution of the body of the method or constructor. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method or constructor to refer to the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.1" rel="noreferrer">formal parameter</a>. </p>\n</blockquote>\n'}, {'answer_id': 14105447, 'author': 'fatma.ekici', 'author_id': 1678760, 'author_profile': 'https://Stackoverflow.com/users/1678760', 'pm_score': 4, 'selected': False, 'text': '<p>Java is pass by constant reference where a copy of the reference is passed which means that it is basically a pass by value. You might change the contents of the reference if the class is mutable but you cannot change the reference itself. In other words the address can not be changed since it is passed by value but the content that is pointed by the address can be changed. In case of immutable classes, the content of the reference cannot be changed either.</p>\n'}, {'answer_id': 16880062, 'author': 'Khaled.K', 'author_id': 2128327, 'author_profile': 'https://Stackoverflow.com/users/2128327', 'pm_score': 3, 'selected': False, 'text': '<p>Java is always pass-by-value, the parameters are copies of what the variables passed, all Objects are defined using a reference, and reference is a variable that stores a memory address of where the object is in memory.</p>\n\n<p>Check the comments to understand what happens in execution; follow numbers as they show the flow of execution ..</p>\n\n<pre><code>class Example\n{\n    public static void test (Cat ref)\n    {\n        // 3 - &lt;ref&gt; is a copy of the reference &lt;a&gt;\n        // both currently reference Grumpy\n        System.out.println(ref.getName());\n\n        // 4 - now &lt;ref&gt; references a new &lt;Cat&gt; object named "Nyan"\n        ref = new Cat("Nyan");\n\n        // 5 - this should print "Nyan"\n        System.out.println( ref.getName() );\n    }\n\n    public static void main (String [] args)\n    {\n        // 1 - a is a &lt;Cat&gt; reference that references a Cat object in memory with name "Grumpy"\n        Cat a = new Cat("Grumpy");\n\n        // 2 - call to function test which takes a &lt;Cat&gt; reference\n        test (a);\n\n        // 6 - function call ends, and &lt;ref&gt; life-time ends\n        // "Nyan" object has no references and the Garbage\n        // Collector will remove it from memory when invoked\n\n        // 7 - this should print "Grumpy"\n        System.out.println(a.getName());\n    }\n}\n</code></pre>\n'}, {'answer_id': 17303467, 'author': 'JasonG', 'author_id': 1255825, 'author_profile': 'https://Stackoverflow.com/users/1255825', 'pm_score': 4, 'selected': False, 'text': '<p>In an attempt to add even more to this, I thought I\'d include the SCJP Study Guide section on the topic. This is from the guide that is made to pass the Sun/Oracle test on the behaviour of Java so it\'s a good source to use for this discussion.</p>\n\n<blockquote>\n  <p>Passing Variables into Methods (Objective 7.3)</p>\n  \n  <p>7.3 Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.</p>\n  \n  <p>Methods can be declared to take primitives and/or object references. You need to know how (or if) the caller\'s variable can be affected by the called method. The difference between object reference and primitive variables, when passed into methods, is huge and important. To understand this section, you\'ll need to be comfortable with the assignments section covered in the first part of this chapter.</p>\n  \n  <p>Passing Object Reference Variables</p>\n  \n  <p>When you pass an object variable into a method, you must keep in mind that you\'re passing the object reference, and not the actual object itself. Remember that a reference variable holds bits that represent (to the underlying VM) a way to get to a specific object in memory (on the heap). More importantly, you must remember that you aren\'t even passing the actual reference variable, but rather a copy of the reference variable. A copy of a variable means you get a copy of the bits in that variable, so when you pass a reference variable, you\'re passing a copy of the bits representing how to get to a specific object. In other words, both the caller and the called method will now have identical copies of the reference, and thus both will refer to the same exact (not a copy) object on the heap.</p>\n  \n  <p>For this example, we\'ll use the Dimension class from the java.awt package:</p>\n</blockquote>\n\n<pre><code>1. import java.awt.Dimension;\n2. class ReferenceTest {\n3.     public static void main (String [] args) {\n4.         Dimension d = new Dimension(5,10);\n5.         ReferenceTest rt = new ReferenceTest();\n6.         System.out.println("Before modify() d.height = " + d.height);\n7.         rt.modify(d);\n8.         System.out.println("After modify() d.height = "\n9.     }\n10.\n11.\n12.\n13.   }\n14. }\n</code></pre>\n\n<blockquote>\n  <p>When we run this class, we can see that the modify() method was indeed able to modify the original (and only) Dimension object created on line 4.</p>\n</blockquote>\n\n<pre>\nC:\\Java Projects\\Reference>java ReferenceTest\nBefore modify() d.height = 10\ndim = 11\nAfter modify() d.height = 11\n</pre>\n\n<blockquote>\n  <p>Notice when the Dimension object on line 4 is passed to the modify() method, any changes to the object that occur inside the method are being made to the object whose reference was passed. In the preceding example, reference variables d and dim both point to the same object.</p>\n  \n  <p>Does Java Use Pass-By-Value Semantics?</p>\n  \n  <p>If Java passes objects by passing the reference variable instead, does that mean Java uses pass-by-reference for objects? Not exactly, although you\'ll often hear and read that it does. Java is actually pass-by-value for all variables running within a single VM. Pass-by-value means pass-by-variable-value. And that means, pass-by-copy-of- the-variable! (There\'s that word copy again!)</p>\n  \n  <p>It makes no difference if you\'re passing primitive or reference variables, you are always passing a copy of the bits in the variable. So for a primitive variable, you\'re passing a copy of the bits representing the value. For example, if you pass an int variable with the value of 3, you\'re passing a copy of the bits representing 3. The called method then gets its own copy of the value, to do with it what it likes.</p>\n  \n  <p>And if you\'re passing an object reference variable, you\'re passing a copy of the bits representing the reference to an object. The called method then gets its own copy of the reference variable, to do with it what it likes. But because two identical reference variables refer to the exact same object, if the called method modifies the object (by invoking setter methods, for example), the caller will see that the object the caller\'s original variable refers to has also been changed. In the next section, we\'ll look at how the picture changes when we\'re talking about primitives.</p>\n  \n  <p>The bottom line on pass-by-value: the called method can\'t change the caller\'s variable, although for object reference variables, the called method can change the object the variable referred to. What\'s the difference between changing the variable and changing the object? For object references, it means the called method can\'t reassign the caller\'s original reference variable and make it refer to a different object, or null. For example, in the following code fragment,</p>\n</blockquote>\n\n<pre><code>        void bar() {\n           Foo f = new Foo();\n           doStuff(f);\n        }\n        void doStuff(Foo g) {\n           g.setName("Boo");\n           g = new Foo();\n        }\n</code></pre>\n\n<blockquote>\n  <p>reassigning g does not reassign f! At the end of the bar() method, two Foo objects have been created, one referenced by the local variable f and one referenced by\n  the local (argument) variable g. Because the doStuff() method has a copy of the reference variable, it has a way to get to the original Foo object, for instance to call the setName() method. But, the doStuff() method does not have a way to get to the f reference variable. So doStuff() can change values within the object f refers to, but doStuff() can\'t change the actual contents (bit pattern) of f. In other words, doStuff() can change the state of the object that f refers to, but it can\'t make f refer to a different object!</p>\n  \n  <p>Passing Primitive Variables</p>\n  \n  <p>Let\'s look at what happens when a primitive variable is passed to a method:</p>\n</blockquote>\n\n<pre><code>class ReferenceTest {\n    public static void main (String [] args) {\n      int a = 1;\n      ReferenceTest rt = new ReferenceTest();\n      System.out.println("Before modify() a = " + a);\n      rt.modify(a);\n      System.out.println("After modify() a = " + a);\n    }\n    void modify(int number) {\n      number = number + 1;\n      System.out.println("number = " + number);\n    }\n}\n</code></pre>\n\n<blockquote>\n  <p>In this simple program, the variable a is passed to a method called modify(),\n  which increments the variable by 1. The resulting output looks like this:</p>\n</blockquote>\n\n<pre><code>  Before modify() a = 1\n  number = 2\n  After modify() a = 1\n</code></pre>\n\n<blockquote>\n  <p>Notice that a did not change after it was passed to the method. Remember, it was a copy of a that was passed to the method. When a primitive variable is passed to a method, it is passed by value, which means pass-by-copy-of-the-bits-in-the-variable.</p>\n</blockquote>\n'}, {'answer_id': 17563873, 'author': 'Gaurav', 'author_id': 1912964, 'author_profile': 'https://Stackoverflow.com/users/1912964', 'pm_score': 5, 'selected': False, 'text': '<p>Java has only pass by value. A very simple example to validate this.</p>\n\n<pre><code>public void test() {\n    MyClass obj = null;\n    init(obj);\n    //After calling init method, obj still points to null\n    //this is because obj is passed as value and not as reference.\n}\nprivate void init(MyClass objVar) {\n    objVar = new MyClass();\n}\n</code></pre>\n'}, {'answer_id': 18287583, 'author': 'bvdb', 'author_id': 1833961, 'author_profile': 'https://Stackoverflow.com/users/1833961', 'pm_score': 3, 'selected': False, 'text': '<p>Shortest answer :)</p>\n\n<ul>\n<li>Java has pass-by-value (and pass-reference-by-value.) </li>\n<li><strong>C# also has pass-by-reference</strong></li>\n</ul>\n\n<p>In C# this is accomplished with the "out" and "ref" keywords. </p>\n\n<p>Pass By Reference: The variable is passed in such a way that <strong>a reassignment inside the method is reflected even outside the method.</strong></p>\n\n<p>Here follows <strong>an example of passing-by-reference (C#)</strong>.\nThis feature does not exist in java.</p>\n\n<pre><code>class Example\n{\n    static void InitArray(out int[] arr)\n    {\n        arr = new int[5] { 1, 2, 3, 4, 5 };\n    }\n\n    static void Main()\n    {\n        int[] someArray;\n        InitArray(out someArray);\n\n        // This is true !\n        boolean isTrue = (someArray[0] == 1);\n    }\n}\n</code></pre>\n\n<p>See also: <a href="http://msdn.microsoft.com/en-us/library/szasx730.aspx" rel="noreferrer" title="MSDN library: passing arrays by ref and out">MSDN library (C#): passing arrays by ref and out</a></p>\n\n<p>See also: <a href="http://msdn.microsoft.com/en-us/library/0f66670z.aspx" rel="noreferrer" title="MSDN library: passing by reference">MSDN library (C#): passing by by value and by reference</a></p>\n'}, {'answer_id': 18623099, 'author': 'James Drinkard', 'author_id': 543572, 'author_profile': 'https://Stackoverflow.com/users/543572', 'pm_score': 3, 'selected': False, 'text': '<p>The bottom line on pass-by-value: the called method can\'t change the caller\'s\nvariable, although for object reference variables, the called method can change the\nobject the variable referred to. What\'s the difference between changing the variable\nand changing the object? For object references, it means the called method can\'t\nreassign the caller\'s original reference variable and make it refer to a different object,\nor null. </p>\n\n<p>I took this code and explanation from a book on Java Certification and made some minor changes.<br>\nI think it\'s a\ngood illustration to the pass by value of an object.  In the code below, \nreassigning g does not reassign f! At the end of the bar() method, two Foo objects\nhave been created, one referenced by the local variable f and one referenced by\nthe local (argument) variable g. </p>\n\n<p>Because the doStuff() method has a copy of the reference variable, it has a way to get \nto the original Foo object, for instance to call\nthe setName() method. But, the doStuff() method does not have a way to get to\nthe f reference variable. So doStuff() can change values within the object f refers\nto, but doStuff() can\'t change the actual contents (bit pattern) of f. In other\nwords, doStuff() can change the state of the object that f refers to, but it can\'t\nmake f refer to a different object!</p>\n\n<pre><code>package test.abc;\n\npublic class TestObject {\n\n    /**\n     * @param args\n     */\n    public static void main(String[] args) {\n        bar();\n    }\n\n    static void bar() {\n        Foo f = new Foo();\n        System.out.println("Object reference for f: " + f);\n        f.setName("James");\n        doStuff(f);\n        System.out.println(f.getName());\n        //Can change the state of an object variable in f, but can\'t change the object reference for f.\n        //You still have 2 foo objects.\n        System.out.println("Object reference for f: " + f);\n        }\n\n    static void doStuff(Foo g) {\n            g.setName("Boo");\n            g = new Foo();\n            System.out.println("Object reference for g: " + g);\n        }\n}\n\n\npackage test.abc;\n\npublic class Foo {\n    public String name = "";\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n}\n</code></pre>\n\n<p><strong>Note that the object reference has not changed in the console output below:</strong></p>\n\n<p><strong>Console output:</strong></p>\n\n<p>Object reference for f: test.abc.Foo@62f72617</p>\n\n<p>Object reference for g: test.abc.Foo@4fe5e2c3</p>\n\n<p>Boo\nObject reference for f: test.abc.Foo@62f72617 </p>\n'}, {'answer_id': 18740042, 'author': 'cutmancometh', 'author_id': 1917489, 'author_profile': 'https://Stackoverflow.com/users/1917489', 'pm_score': 8, 'selected': False, 'text': '<p>I feel like arguing about "pass-by-reference vs pass-by-value" is not super-helpful.</p>\n\n<p>If you say, "Java is pass-by-whatever (reference/value)", in either case, you\'re not provide a complete answer. Here\'s some additional information that will hopefully aid in understanding what\'s happening in memory.</p>\n\n<p>Crash course on stack/heap before we get to the Java implementation:\nValues go on and off the stack in a nice orderly fashion, like a stack of plates at a cafeteria.\nMemory in the heap (also known as dynamic memory) is haphazard and disorganized. The JVM just finds space wherever it can, and frees it up as the variables that use it are no longer needed.</p>\n\n<p>Okay. First off, local primitives go on the stack. So this code:</p>\n\n<pre><code>int x = 3;\nfloat y = 101.1f;\nboolean amIAwesome = true;\n</code></pre>\n\n<p>results in this:</p>\n\n<p><img src="https://i.stack.imgur.com/7nGKU.png" alt="primitives on the stack"></p>\n\n<p>When you declare and instantiate an object. The actual object goes on the heap. What goes on the stack? The address of the object on the heap. C++ programmers would call this a pointer, but some Java developers are against the word "pointer". Whatever. Just know that the address of the object goes on the stack.</p>\n\n<p>Like so:</p>\n\n<pre><code>int problems = 99;\nString name = "Jay-Z";\n</code></pre>\n\n<p><img src="https://i.stack.imgur.com/yTIYp.png" alt="a b*7ch aint one!"></p>\n\n<p>An array is an object, so it goes on the heap as well. And what about the objects in the array? They get their own heap space, and the address of each object goes inside the array.</p>\n\n<pre><code>JButton[] marxBros = new JButton[3];\nmarxBros[0] = new JButton("Groucho");\nmarxBros[1] = new JButton("Zeppo");\nmarxBros[2] = new JButton("Harpo");\n</code></pre>\n\n<p><img src="https://i.stack.imgur.com/v2b33.png" alt="marx brothers"></p>\n\n<p>So, what gets passed in when you call a method? If you pass in an object, what you\'re actually passing in is the address of the object. Some might say the "value" of the address, and some say it\'s just a reference to the object. This is the genesis of the holy war between "reference" and "value" proponents. What you call it isn\'t as important as that you understand that what\'s getting passed in is the address to the object.</p>\n\n<pre><code>private static void shout(String name){\n    System.out.println("There goes " + name + "!");\n}\n\npublic static void main(String[] args){\n    String hisName = "John J. Jingleheimerschmitz";\n    String myName = hisName;\n    shout(myName);\n}\n</code></pre>\n\n<p>One String gets created and space for it is allocated in the heap, and the address to the string is stored on the stack and given the identifier <code>hisName</code>, since the address of the second String is the same as the first, no new String is created and no new heap space is allocated, but a new identifier is created on the stack. Then we call <code>shout()</code>: a new stack frame is created and a new identifier, <code>name</code> is created and assigned the address of the already-existing String.</p>\n\n<p><img src="https://i.stack.imgur.com/q0prc.png" alt="la da di da da da da"></p>\n\n<p>So, value, reference? You say "potato".</p>\n'}, {'answer_id': 18950805, 'author': 'user1931858', 'author_id': 1931858, 'author_profile': 'https://Stackoverflow.com/users/1931858', 'pm_score': 3, 'selected': False, 'text': '<p>Java passes parameters by value, but for object variables, the values are essentially references to objects. Since arrays are objects the following <a href="http://theoryapp.com/parameter-passing-in-java/" rel="noreferrer">example code</a> shows the difference.</p>\n\n<pre><code>public static void dummyIncrease(int[] x, int y)\n{\n    x[0]++;\n    y++;\n}\npublic static void main(String[] args)\n{\n    int[] arr = {3, 4, 5};\n    int b = 1;\n    dummyIncrease(arr, b);\n    // arr[0] is 4, but b is still 1\n}\n\nmain()\n  arr +---+       +---+---+---+\n      | # | ----&gt; | 3 | 4 | 5 |\n      +---+       +---+---+---+\n  b   +---+             ^\n      | 1 |             | \n      +---+             |\n                        |\ndummyIncrease()         |\n  x   +---+             |\n      | # | ------------+\n      +---+      \n  y   +---+ \n      | 1 | \n      +---+ \n</code></pre>\n'}, {'answer_id': 19421107, 'author': 'Ganesh', 'author_id': 1910406, 'author_profile': 'https://Stackoverflow.com/users/1910406', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Java is always pass by value, not pass by reference</strong></p>\n<p>First of all, we need to understand what pass by value and pass by reference are.</p>\n<p><strong>Pass by value means that you are making a copy in memory of the actual parameter\'s value that is passed in. This is a copy of the contents of the actual parameter</strong>.</p>\n<p><strong>Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored</strong>.</p>\n<p>Sometimes Java can give the illusion of pass by reference. Let\'s see how it works by using the example below:</p>\n<pre><code>public class PassByValue {\n    public static void main(String[] args) {\n        Test t = new Test();\n        t.name = &quot;initialvalue&quot;;\n        new PassByValue().changeValue(t);\n        System.out.println(t.name);\n    }\n    \n    public void changeValue(Test f) {\n        f.name = &quot;changevalue&quot;;\n    }\n}\n\nclass Test {\n    String name;\n}\n</code></pre>\n<p>The output of this program is:</p>\n<blockquote>\n<pre><code>changevalue\n</code></pre>\n</blockquote>\n<p>Let\'s understand step by step:</p>\n<pre><code>Test t = new Test();\n</code></pre>\n<p>As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is <code>0x100234</code> (we don\'t know the actual JVM internal value, this is just an example) .</p>\n<p><img src="https://i.stack.imgur.com/AVrhI.png" alt="first illustration" /></p>\n<pre><code>new PassByValue().changeValue(t);\n</code></pre>\n<p>When passing reference t to the function it will not directly pass the actual reference value of object test,  but it will create a copy of t and then pass it to the function. Since it is <strong>passing by value</strong>, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was <code>0x100234</code>, both t and f will have the same value and hence they will point to the same object.</p>\n<p><img src="https://i.stack.imgur.com/WwdPh.png" alt="second illustration" /></p>\n<p>If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output <code>changevalue</code>,   which is updated in the function.</p>\n<p>To understand this more clearly, consider the following example:</p>\n<pre><code>public class PassByValue {\n    public static void main(String[] args) {\n        Test t = new Test();\n        t.name = &quot;initialvalue&quot;;\n        new PassByValue().changeRefence(t);\n        System.out.println(t.name);\n    }\n    \n    public void changeRefence(Test f) {\n        f = null;\n    }\n}\n\nclass Test {\n    String name;\n}\n</code></pre>\n<p>Will this throw a <code>NullPointerException</code>? No, because it only passes a copy of the reference.\nIn the case of passing by reference, it could have thrown a <code>NullPointerException</code>, as seen below:</p>\n<p><img src="https://i.stack.imgur.com/jH6KP.png" alt="third illustration" /></p>\n<p>Hopefully this will help.</p>\n'}, {'answer_id': 19970416, 'author': 'Bhushan', 'author_id': 1907916, 'author_profile': 'https://Stackoverflow.com/users/1907916', 'pm_score': 2, 'selected': False, 'text': '<p>The Java programming language passes arguments only by value, that is,\nyou cannot change the argument value in the calling method from within\nthe called method.</p>\n\n<hr>\n\n<p>However, when an object instance is passed as an argument to a method,\nthe value of the argument is not the object itself but a reference to the\nobject. You can change the contents of the object in the called method but\nnot the object reference.</p>\n\n<hr>\n\n<p>To many people, this looks like pass-by-reference, and behaviorally, it has\nmuch in common with pass-by-reference. However, there are two reasons\nthis is inaccurate.</p>\n\n<ul>\n<li><p>Firstly, the ability to change the thing passed into a\nmethod only applies to objects, not primitive values. </p></li>\n<li><p>Second, the actual\nvalue associated with a variable of object type is the reference to the\nobject, and not the object itself. This is an important distinction in other\nways, and if clearly understood, is entirely supporting of the point that\nthe Java programming language passes arguments by value.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>The following code example illustrates this point:\n1 public class PassTest {\n2\n3   // Methods to change the current values\n4   public static void changeInt(int value) {\n5     value = 55;\n6  }\n7   public static void changeObjectRef(MyDate ref) {\n8     ref = new MyDate(1, 1, 2000);\n9  }\n10   public static void changeObjectAttr(MyDate ref) {\n11     ref.setDay(4);\n12   }\n13\n14 public static void main(String args[]) {\n15     MyDate date;\n16     int val;\n17\n18     // Assign the int\n19     val = 11;\n20     // Try to change it\n21     changeInt(val);\n22     // What is the current value?\n23     System.out.println("Int value is: " + val);\n24\n25 // Assign the date\n26     date = new MyDate(22, 7, 1964);\n27     // Try to change it\n28     changeObjectRef(date);\n29     // What is the current value?\n30 System.out.println("MyDate: " + date);\n31\n32 // Now change the day attribute\n33     // through the object reference\n34     changeObjectAttr(date);\n35     // What is the current value?\n36 System.out.println("MyDate: " + date);\n37   }\n38 }\n</code></pre>\n\n<hr>\n\n<pre><code>This code outputs the following:\njava PassTest\nInt value is: 11\nMyDate: 22-7-1964\nMyDate: 4-7-1964\nThe MyDate object is not changed by the changeObjectRef method;\nhowever, the changeObjectAttr method changes the day attribute of the\nMyDate object.\n</code></pre>\n'}, {'answer_id': 20125921, 'author': 'Srle', 'author_id': 922581, 'author_profile': 'https://Stackoverflow.com/users/922581', 'pm_score': 7, 'selected': False, 'text': '<p>In java everything is reference, so when you have something like:\n    <code>Point pnt1 = new Point(0,0);</code> Java does following:</p>\n\n<ol>\n<li>Creates new Point object</li>\n<li>Creates new Point reference and initialize that reference to <em>point (refer to)</em> on previously created Point object.</li>\n<li>From here, through Point object life, you will access to that object through pnt1\n reference. So we can say that in Java you manipulate object through its reference.<br></li>\n</ol>\n\n<p><img src="https://i.stack.imgur.com/jM54f.png" alt="enter image description here"></p>\n\n<p><strong>Java doesn\'t pass method arguments by reference; it passes them by value.</strong> I will use example from <a href="http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html" rel="noreferrer">this site</a>: </p>\n\n<pre><code>public static void tricky(Point arg1, Point arg2) {\n  arg1.x = 100;\n  arg1.y = 100;\n  Point temp = arg1;\n  arg1 = arg2;\n  arg2 = temp;\n}\npublic static void main(String [] args) {\n  Point pnt1 = new Point(0,0);\n  Point pnt2 = new Point(0,0);\n  System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y); \n  System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);\n  System.out.println(" ");\n  tricky(pnt1,pnt2);\n  System.out.println("X1: " + pnt1.x + " Y1:" + pnt1.y); \n  System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);  \n}\n</code></pre>\n\n<p>Flow of the program:</p>\n\n<pre><code>Point pnt1 = new Point(0,0);\nPoint pnt2 = new Point(0,0);\n</code></pre>\n\n<p>Creating two different Point object with two different reference associated.\n<img src="https://i.stack.imgur.com/5LIKC.png" alt="enter image description here"></p>\n\n<pre><code>System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y); \nSystem.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);\nSystem.out.println(" ");\n</code></pre>\n\n<p>As expected output will be:</p>\n\n<pre><code>X1: 0     Y1: 0\nX2: 0     Y2: 0\n</code></pre>\n\n<p><strong>On this line \'pass-by-value\' goes into the play...</strong> <br></p>\n\n<pre><code>tricky(pnt1,pnt2);           public void tricky(Point arg1, Point arg2);\n</code></pre>\n\n<p>References <code>pnt1</code> and <code>pnt2</code> are <strong>passed by value</strong> to the tricky method, which means that now yours references <code>pnt1</code> and <code>pnt2</code> have their <code>copies</code> named <code>arg1</code> and <code>arg2</code>.So <code>pnt1</code> and <code>arg1</code> <em>points</em> to the same object. (Same for the <code>pnt2</code> and <code>arg2</code>)\n<img src="https://i.stack.imgur.com/qd1GH.png" alt="enter image description here"></p>\n\n<p>In the <code>tricky</code> method:</p>\n\n<pre><code> arg1.x = 100;\n arg1.y = 100;\n</code></pre>\n\n<p><img src="https://i.stack.imgur.com/o4WT0.png" alt="enter image description here"></p>\n\n<p>Next in the <code>tricky</code> method</p>\n\n<pre><code>Point temp = arg1;\narg1 = arg2;\narg2 = temp;\n</code></pre>\n\n<p>Here, you first create new <code>temp</code> Point reference which will <em>point</em> on same place like <code>arg1</code> reference. Then you move reference <code>arg1</code> to <em>point</em> to the same place like <code>arg2</code> reference.\nFinally <code>arg2</code> will <em>point</em> to the same place like <code>temp</code>.</p>\n\n<p><img src="https://i.stack.imgur.com/fX5Q3.png" alt="enter image description here"></p>\n\n<p>From here scope of <code>tricky</code> method is gone and you don\'t have access any more to the references: <code>arg1</code>, <code>arg2</code>, <code>temp</code>. <strong>But important note is that everything you do with these references when they are \'in life\' will permanently affect object on which they are <em>point</em> to.</strong> </p>\n\n<p>So after executing method <code>tricky</code>, when you return to <code>main</code>, you have this situation:\n<img src="https://i.stack.imgur.com/LRETe.png" alt="enter image description here"></p>\n\n<p>So now, completely execution of program will be:</p>\n\n<pre><code>X1: 0         Y1: 0\nX2: 0         Y2: 0\nX1: 100       Y1: 100\nX2: 0         Y2: 0\n</code></pre>\n'}, {'answer_id': 20346109, 'author': 'Aniket Thakur', 'author_id': 2396539, 'author_profile': 'https://Stackoverflow.com/users/2396539', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Java passes references to objects by value.</strong></p>\n\n<p>So if any modification is done to the Object to which the reference argument points it will be reflected back on the original object.</p>\n\n<p>But if the reference argument point to another Object still the original reference will point to original Object.</p>\n'}, {'answer_id': 20566453, 'author': 'karatedog', 'author_id': 216248, 'author_profile': 'https://Stackoverflow.com/users/216248', 'pm_score': 6, 'selected': False, 'text': '<h2>A reference is always a value when represented, no matter what language you use.</h2>\n\n<p>Getting an outside of the box view, let\'s look at Assembly or some low level memory management. At the CPU level a <em>reference</em> to anything immediately becomes a <em>value</em> if it gets written to memory or to one of the CPU registers. (That is why <em>pointer</em> is a good definition. It is a value, which has a purpose at the same time).</p>\n\n<p>Data in memory has a <strong>Location</strong> and at that location there is a value (byte,word, whatever). In Assembly we have a convenient solution to give a <strong>Name</strong> to certain <strong>Location</strong> (aka variable), but when compiling the code, the assembler simply replaces <strong>Name</strong> with the designated location just like your browser replaces domain names with IP addresses.</p>\n\n<p>Down to the core it is technically impossible to pass a reference to anything in any language without representing it (when it immediately becomes a value).</p>\n\n<p>Lets say we have a variable Foo, its <strong>Location</strong> is at the 47th byte in memory and its <strong>Value</strong> is 5. We have another variable <strong>Ref2Foo</strong> which is at 223rd byte in memory, and its value will be 47. This Ref2Foo might be a technical variable, not explicitly created by the program. If you just look at 5 and 47 without any other information, you will see just two <strong>Values</strong>.\nIf you use them as references then to reach to <code>5</code> we have to travel:</p>\n\n<pre><code>(Name)[Location] -&gt; [Value at the Location]\n---------------------\n(Ref2Foo)[223]  -&gt; 47\n(Foo)[47]       -&gt; 5\n</code></pre>\n\n<p>This is how jump-tables work. </p>\n\n<p>If we want to call a method/function/procedure with Foo\'s value, there are a few possible way to pass the variable to the method, depending on the <strong>language</strong> and its several method invocation modes:</p>\n\n<ol>\n<li>5 gets copied to one of the CPU registers (ie. EAX).</li>\n<li>5 gets PUSHd to the stack.</li>\n<li>47 gets copied to one of the CPU registers</li>\n<li>47 PUSHd to the stack.</li>\n<li>223 gets copied to one of the CPU registers.</li>\n<li>223 gets PUSHd to the stack.</li>\n</ol>\n\n<p>In every cases above a value - a <strong>copy</strong> of an existing value - has been created, it is now upto the receiving method to handle it. When you write "Foo" inside the method, it is either read out from EAX, or automatically  <strong>dereferenced</strong>, or double dereferenced, the process depends on how the language works and/or what the type of Foo dictates. This is hidden from the developer until she circumvents the dereferencing process. So a <em>reference</em> is a <em>value</em> when represented, because a reference is a value that has to be processed (at language level).</p>\n\n<p>Now we have passed Foo to the method:</p>\n\n<ul>\n<li>in case 1. and 2. if you change Foo (<code>Foo = 9</code>) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.</li>\n<li>in case 3. and 4. if you use default language constructs and change Foo (<code>Foo = 11</code>), it could change Foo globally (depends on the language, ie. Java or like Pascal\'s <code>procedure findMin(x, y, z: integer;</code><strong>var m</strong><code>: integer);</code>). However if the language allows you to circumvent the dereference process, you can change <code>47</code>, say to <code>49</code>. At that point Foo seems to have been changed if you read it, because you have changed the <strong>local pointer</strong> to it. And if you were to modify this Foo inside the method (<code>Foo = 12</code>) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at <code>47</code>). BUT Foo\'s value of <code>47</code> did not change globally, only the one inside the method, because <code>47</code> was also a copy to the method.</li>\n<li>in case 5. and 6. if you modify <code>223</code> inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was <strong>copied</strong>. However if you are able to dereference <code>Ref2Foo</code> (that is <code>223</code>), reach to and modify the pointed value <code>47</code>, say, to <code>49</code>, it will affect Foo <strong>globally</strong>, because in this case the methods got a copy of <code>223</code>  but the referenced <code>47</code> exists only once, and changing that to <code>49</code> will lead every <code>Ref2Foo</code> double-dereferencing to a wrong value.</li>\n</ul>\n\n<p>Nitpicking on insignificant details, even languages that do pass-by-reference will pass values to functions, but those functions know that they have to use it for dereferencing purposes. This pass-the-reference-as-value is just hidden from the programmer because it is practically useless and the terminology is only <em>pass-by-reference</em>.</p>\n\n<p>Strict <em>pass-by-value</em> is also useless, it would mean that a 100 Mbyte array should have to be copied every time we call a method with the array as argument, therefore Java cannot be stricly pass-by-value. Every language would pass a reference to this huge array (as a value) and either employs copy-on-write mechanism if that array can be changed locally inside the method or allows the method (as Java does) to modify the array globally (from the caller\'s view) and a few languages allows to modify the Value of the reference itself.</p>\n\n<p>So in short and in Java\'s own terminology, Java is <em>pass-by-value</em> where <em>value</em> can be: either a <strong>real value</strong> or a <strong>value</strong> that is a representation of a <strong>reference</strong>. </p>\n'}, {'answer_id': 21288385, 'author': 'JAN', 'author_id': 779111, 'author_profile': 'https://Stackoverflow.com/users/779111', 'pm_score': 3, 'selected': False, 'text': '<p>Mr @Scott Stanchfield wrote an excellent answer. Here is the class that would you to verify\nexactly what he meant:</p>\n\n<pre><code>public class Dog {\n\n    String dog ;\n    static int x_static;\n    int y_not_static;\n\n    public String getName()\n    {\n        return this.dog;\n    }\n\n    public Dog(String dog)\n    {\n        this.dog = dog;\n    }\n\n    public void setName(String name)\n    {\n        this.dog = name;\n    }\n\n    public static void foo(Dog someDog)\n    {\n        x_static = 1;\n        // y_not_static = 2;  // not possible !!\n        someDog.setName("Max");     // AAA\n        someDog = new Dog("Fifi");  // BBB\n        someDog.setName("Rowlf");   // CCC\n    }\n\n    public static void main(String args[])\n    {\n        Dog myDog = new Dog("Rover");\n        foo(myDog);\n        System.out.println(myDog.getName());\n    }\n}\n</code></pre>\n\n<p>So, we pass from main() a dog called <code>Rover</code>, then we assign a new address to the pointer that we passed, but at the end, the name of the dog is not <code>Rover</code>, and not <code>Fifi</code>, and certainly not <code>Rowlf</code>, but <code>Max</code>.</p>\n'}, {'answer_id': 24546764, 'author': 'Sotirios Delimanolis', 'author_id': 438154, 'author_profile': 'https://Stackoverflow.com/users/438154', 'pm_score': 6, 'selected': False, 'text': '<p>I thought I\'d contribute this answer to add more details from the Specifications.</p>\n<p>First, <a href="https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value">What&#39;s the difference between passing by reference vs. passing by value?</a></p>\n<blockquote>\n<p>Passing by reference means the called functions\' parameter will be the\nsame as the callers\' passed argument (not the value, but the identity</p>\n<ul>\n<li>the variable itself).</li>\n</ul>\n<p>Pass by value means the called functions\' parameter will be a copy of\nthe callers\' passed argument.</p>\n</blockquote>\n<p>Or from wikipedia, <a href="http://en.wikipedia.org/wiki/Call_by_reference#Call_by_reference" rel="noreferrer">on the subject of pass-by-reference</a></p>\n<blockquote>\n<p>In call-by-reference evaluation (also referred to as\npass-by-reference), a function receives an implicit reference to a\nvariable used as argument, rather than a copy of its value. This\ntypically means that the function can modify (i.e. assign to) the\nvariable used as argument—something that will be seen by its caller.</p>\n</blockquote>\n<p>And <a href="http://en.wikipedia.org/wiki/Call_by_value#Call_by_value" rel="noreferrer">on the subject of pass-by-value</a></p>\n<blockquote>\n<p>In call-by-value, the argument expression is evaluated, and the\nresulting value is bound to the corresponding variable in the function [...].\nIf the function or procedure is able to assign values to its\nparameters, only its local copy is assigned [...].</p>\n</blockquote>\n<p>Second, we need to know what Java uses in its method invocations. The <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.1" rel="noreferrer">Java Language Specification</a> states</p>\n<blockquote>\n<p>When the method or constructor is invoked (§15.12), <strong>the values of the\nactual argument expressions initialize newly created parameter\nvariables</strong>, each of the declared type, before execution of the body of\nthe method or constructor.</p>\n</blockquote>\n<p>So it assigns (or binds) the value of the argument to the corresponding parameter variable.</p>\n<p><strong>What is the value of the argument?</strong></p>\n<p>Let\'s consider reference types, the <a href="http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.4" rel="noreferrer">Java Virtual Machine Specification</a> states</p>\n<blockquote>\n<p>There are three kinds of <strong>reference types</strong>: class types, array types,\nand interface types. <strong>Their values are references to dynamically\ncreated class instances, arrays, or class instances or arrays that\nimplement interfaces, respectively.</strong></p>\n</blockquote>\n<p>The <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.3.1" rel="noreferrer">Java Language Specification</a> also states</p>\n<blockquote>\n<p><strong>The reference values (often just references) are pointers to these objects</strong>, and a special null reference, which refers to no object.</p>\n</blockquote>\n<p>The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (<code>new ...</code>) all resolve to a reference type value.</p>\n<p>So</p>\n<pre><code>public void method (String param) {}\n...\nString variable = new String(&quot;ref&quot;);\nmethod(variable);\nmethod(variable.toString());\nmethod(new String(&quot;ref&quot;));\n</code></pre>\n<p>all bind the value of a reference to a <code>String</code> instance to the method\'s newly created parameter, <code>param</code>. This is exactly what the definition of pass-by-value describes. As such, <strong>Java is pass-by-value</strong>.</p>\n<p><strong>The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation.</strong> The definition of pass-by-reference was</p>\n<blockquote>\n<p>This typically means that the function can modify (i.e. assign to) the\nvariable used as argument—something that will be seen by its caller.</p>\n</blockquote>\n<p>In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. <strong>Modifying the object referenced by the variable is a different concept entirely.</strong></p>\n<hr />\n<p>Primitive values are also defined in the Java Virtual Machine Specification, <a href="http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.3" rel="noreferrer">here</a>. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).</p>\n'}, {'answer_id': 24685542, 'author': 'Dustin Deus', 'author_id': 1893773, 'author_profile': 'https://Stackoverflow.com/users/1893773', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Understand it in 2 Steps:</strong> </p>\n\n<p>You can\'t change the reference to the object itself but you can work with this passed parameter as a reference to the object.</p>\n\n<p>If you want to change the value behind the reference you will only declare a new variable on the stack with the same name \'d\'. Look at the references with the sign <code>@</code> and you will find out that the reference has been changed.</p>\n\n<pre><code>public static void foo(Dog d) {\n  d.Name = "belly";\n  System.out.println(d); //Reference: Dog@1540e19d\n\n  d = new Dog("wuffwuff");\n  System.out.println(d); //Dog@677327b6\n}\npublic static void main(String[] args) throws Exception{\n  Dog lisa = new Dog("Lisa");\n  foo(lisa);\n  System.out.println(lisa.Name); //belly\n}\n</code></pre>\n'}, {'answer_id': 26028582, 'author': 'Michał Żbikowski', 'author_id': 3961865, 'author_profile': 'https://Stackoverflow.com/users/3961865', 'pm_score': 4, 'selected': False, 'text': '<p>Throughout all the answers we see that Java pass-by-value or rather as @Gevorg \nwrote: "pass-by-copy-of-the-variable-value" and this is the idea that we should have in mind all the time. </p>\n\n<p>I am focusing on examples that helped me understand the idea and it is rather addendum to previous answers.</p>\n\n<p>From [1] In Java you always are passing arguments by copy; that is you\'re always creating a new instance of the value inside the function. But there are certain behaviors that can make you think you\'re passing by reference.</p>\n\n<ul>\n<li><p>Passing by copy: When a variable is passed to a method/function, a copy is made (sometimes we hear that when you pass primitives, you\'re making copies).</p></li>\n<li><p>Passing by reference: When a variable is passed to a method/function, the code in the method/function operates on the original variable (You\'re still passing by copy, but references to values inside the complex object are parts of both versions of the variable, both the original and the version inside the function. The complex objects themselves are being copied, but the internal references are being retained)</p></li>\n</ul>\n\n<h2>Examples of Passing by copy/ by value</h2>\n\n<p><strong>Example from [ref 1]</strong></p>\n\n<pre><code>void incrementValue(int inFunction){\n  inFunction ++;\n  System.out.println("In function: " + inFunction);\n}\n\nint original = 10;\nSystem.out.print("Original before: " + original);\nincrementValue(original);\nSystem.out.println("Original after: " + original);\n\nWe see in the console:\n &gt; Original before: 10\n &gt; In Function: 11\n &gt; Original after: 10 (NO CHANGE)\n</code></pre>\n\n<p><strong>Example from [ref 2]</strong></p>\n\n<blockquote>\n  <p>shows nicely the mechanism\n  <a href="https://www.youtube.com/watch?v=W2ysz_6AyJE&amp;list=PL6C11012B1B464EC5#t=502" rel="noreferrer">watch max 5 min</a></p>\n</blockquote>\n\n<h2>(Passing by reference) pass-by-copy-of-the-variable-value</h2>\n\n<p><strong>Example from [ref 1]</strong>\n(remember that an array is an object)</p>\n\n<pre><code>void incrementValu(int[] inFuncion){\n  inFunction[0]++;\n  System.out.println("In Function: " + inFunction[0]);\n}\n\nint[] arOriginal = {10, 20, 30};\nSystem.out.println("Original before: " + arOriginal[0]);\nincrementValue(arOriginal[]);\nSystem.out.println("Original before: " + arOriginal[0]);\n\nWe see in the console:\n  &gt;Original before: 10\n  &gt;In Function: 11\n  &gt;Original before: 11 (CHANGE)\n</code></pre>\n\n<p>The complex objects themselves are being copied, but the internal references are being retained.</p>\n\n<p><strong>Example from[ref 3]</strong></p>\n\n<pre><code>package com.pritesh.programs;\n\nclass Rectangle {\n  int length;\n  int width;\n\n  Rectangle(int l, int b) {\n    length = l;\n    width = b;\n  }\n\n  void area(Rectangle r1) {\n    int areaOfRectangle = r1.length * r1.width;\n    System.out.println("Area of Rectangle : " \n                            + areaOfRectangle);\n  }\n}\n\nclass RectangleDemo {\n  public static void main(String args[]) {\n    Rectangle r1 = new Rectangle(10, 20);\n    r1.area(r1);\n  }\n}\n</code></pre>\n\n<p>The area of the rectangle is 200 and the length=10 and width=20</p>\n\n<p><strong>Last thing</strong> I would like to share was this moment of the lecture:\n<strong><a href="https://www.youtube.com/watch?v=W8nNdNZ40EQ#t=1206" rel="noreferrer">Memory Allocation</a></strong>\nwhich I found very helpful in understanding the Java passing by value or rather “pass-by-copy-of-the-variable-value” as @Gevorg has written.</p>\n\n<ol>\n<li><a href="http://www.lynda.com/Android-tutorials/Passing-arguments-reference-value/86005/94989-4.html" rel="noreferrer">REF 1 Lynda.com</a></li>\n<li><a href="http://see.stanford.edu/see/courseinfo.aspx?coll=824a47e1-135f-4508-a5aa-866adcae1111" rel="noreferrer">REF 2 Professor Mehran Sahami</a>\n\n<ul>\n<li><a href="https://www.youtube.com/watch?v=W2ysz_6AyJE&amp;list=PL6C11012B1B464EC5#t=502" rel="noreferrer">watch max 5 min</a></li>\n<li><a href="https://www.youtube.com/watch?v=W8nNdNZ40EQ#t=1206" rel="noreferrer">Memory Allocation</a></li>\n</ul></li>\n<li><a href="http://www.c4learn.com/" rel="noreferrer">REF 3 c4learn</a>\n\n<ul>\n<li><a href="http://www.c4learn.com/java/java-passing-object-as-parameter-to-method/" rel="noreferrer">passing-object-as-parameter-to-method</a></li>\n</ul></li>\n</ol>\n'}, {'answer_id': 26210057, 'author': 'drew7721', 'author_id': 2997238, 'author_profile': 'https://Stackoverflow.com/users/2997238', 'pm_score': 3, 'selected': False, 'text': '<p>There is a workaround in Java for the reference. Let me explain by this example:</p>\n\n<pre><code>public class Yo {\npublic static void foo(int x){\n    System.out.println(x); //out 2\n    x = x+2;\n    System.out.println(x); // out 4\n}\npublic static void foo(int[] x){\n    System.out.println(x[0]); //1\n    x[0] = x[0]+2;\n    System.out.println(x[0]); //3\n}\npublic static void main(String[] args) {\n    int t = 2;\n    foo(t);\n    System.out.println(t); // out 2 (t did not change in foo)\n\n    int[] tab = new int[]{1};\n    foo(tab);\n    System.out.println(tab[0]); // out 3 (tab[0] did change in foo)\n}}\n</code></pre>\n\n<p>I hope this helps!</p>\n'}, {'answer_id': 27608651, 'author': 'Ramprasad', 'author_id': 1695011, 'author_profile': 'https://Stackoverflow.com/users/1695011', 'pm_score': 3, 'selected': False, 'text': "<p><strong>Simple program</strong></p>\n\n<pre><code>import java.io.*;\nclass Aclass\n{\n    public int a;\n}\npublic class test\n{\n    public static void foo_obj(Aclass obj)\n    {\n        obj.a=5;\n    }\n    public static void foo_int(int a)\n    {\n        a=3;\n    }\n    public static void main(String args[])\n    {\n        //test passing an object\n        Aclass ob = new Aclass();\n        ob.a=0;\n        foo_obj(ob);\n        System.out.println(ob.a);//prints 5\n\n        //test passing an integer\n        int i=0;\n        foo_int(i);\n        System.out.println(i);//prints 0\n    }\n}\n</code></pre>\n\n<p>From a C/C++ programmer's point of view, java uses pass by value, so for primitive data types (int, char etc) changes in the function does not reflect in the calling function. But when you pass an object and in the function you change its data members or call member functions which can change the state of the object, the calling function will get the changes.</p>\n"}, {'answer_id': 28750315, 'author': 'João Oliveira', 'author_id': 1282030, 'author_profile': 'https://Stackoverflow.com/users/1282030', 'pm_score': 3, 'selected': False, 'text': '<p>Java passes everything by value!!</p>\n\n<p>//create an object by passing in a name and age:</p>\n\n<pre><code>PersonClass variable1 = new PersonClass("Mary", 32);\n\nPersonClass variable2;\n</code></pre>\n\n<p>//Both variable2 and variable1 now reference the same object</p>\n\n<pre><code>variable2 = variable1; \n\n\nPersonClass variable3 = new PersonClass("Andre", 45);\n</code></pre>\n\n<p>// variable1 now points to variable3</p>\n\n<pre><code>variable1 = variable3;\n</code></pre>\n\n<p>//WHAT IS OUTPUT BY THIS?</p>\n\n<pre><code>System.out.println(variable2);\nSystem.out.println(variable1);\n\nMary 32\nAndre 45\n</code></pre>\n\n<p>if you could understand this example we r done.\notherwise, please visit this webPage for detailed explanation:</p>\n\n<p><a href="http://www.programmerinterview.com/index.php/java-questions/does-java-pass-by-reference-or-by-value/" rel="noreferrer">webPage</a></p>\n'}, {'answer_id': 29133165, 'author': 'Christian', 'author_id': 112670, 'author_profile': 'https://Stackoverflow.com/users/112670', 'pm_score': 5, 'selected': False, 'text': '<p>Java passes parameters by VALUE, and by value <strong>ONLY</strong>.</p>\n\n<p><strong>To cut long story short:</strong></p>\n\n<blockquote>\n  <p>For those coming from C#: <strong>THERE IS NO "out" parameter.</strong></p>\n  \n  <p>For those coming from PASCAL: <strong>THERE IS NO "var" parameter</strong>.</p>\n</blockquote>\n\n<p>It means you can\'t change the reference from the object itself, but you can always change the object\'s properties.</p>\n\n<p>A workaround is to use <code>StringBuilder</code> parameter instead <code>String</code>. And you can always use arrays!</p>\n'}, {'answer_id': 30201678, 'author': 'spiderman', 'author_id': 3250087, 'author_profile': 'https://Stackoverflow.com/users/3250087', 'pm_score': 6, 'selected': False, 'text': '<p>Let me try to explain my understanding with the help of four examples. Java is pass-by-value, and not pass-by-reference</p>\n\n<p>/**</p>\n\n<p>Pass By Value</p>\n\n<p>In Java, all parameters are passed by value, i.e. assigning a method argument is not visible to the caller.</p>\n\n<p>*/</p>\n\n<p><strong>Example 1:</strong></p>\n\n<pre><code>public class PassByValueString {\n    public static void main(String[] args) {\n        new PassByValueString().caller();\n    }\n\n    public void caller() {\n        String value = "Nikhil";\n        boolean valueflag = false;\n        String output = method(value, valueflag);\n        /*\n         * \'output\' is insignificant in this example. we are more interested in\n         * \'value\' and \'valueflag\'\n         */\n        System.out.println("output : " + output);\n        System.out.println("value : " + value);\n        System.out.println("valueflag : " + valueflag);\n\n    }\n\n    public String method(String value, boolean valueflag) {\n        value = "Anand";\n        valueflag = true;\n        return "output";\n    }\n}\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>output : output\nvalue : Nikhil\nvalueflag : false\n</code></pre>\n\n<p><strong>Example 2:</strong></p>\n\n<p>/**\n * \n * Pass By Value\n *\n */</p>\n\n<pre><code>public class PassByValueNewString {\n    public static void main(String[] args) {\n        new PassByValueNewString().caller();\n    }\n\n    public void caller() {\n        String value = new String("Nikhil");\n        boolean valueflag = false;\n        String output = method(value, valueflag);\n        /*\n         * \'output\' is insignificant in this example. we are more interested in\n         * \'value\' and \'valueflag\'\n         */\n        System.out.println("output : " + output);\n        System.out.println("value : " + value);\n        System.out.println("valueflag : " + valueflag);\n\n    }\n\n    public String method(String value, boolean valueflag) {\n        value = "Anand";\n        valueflag = true;\n        return "output";\n    }\n}\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>output : output\nvalue : Nikhil\nvalueflag : false\n</code></pre>\n\n<p><strong>Example 3:</strong></p>\n\n<p>/**\n  This \'Pass By Value has a feeling of \'Pass By Reference\'</p>\n\n<p>Some people say primitive types and \'String\' are \'pass by value\'\n  and objects are \'pass by reference\'.</p>\n\n<p>But from this example, we can understand that it is infact pass by value only,\n  keeping in mind that here we are passing the reference as the value.\n  ie: reference is passed by value.\n  That\'s why are able to change and still it holds true after the local scope.\n  But we cannot change the actual reference outside the original scope.\n  what that means is demonstrated by next example of PassByValueObjectCase2.</p>\n\n<p>*/</p>\n\n<pre><code>public class PassByValueObjectCase1 {\n\n    private class Student {\n        int id;\n        String name;\n        public Student() {\n        }\n        public Student(int id, String name) {\n            super();\n            this.id = id;\n            this.name = name;\n        }\n        public int getId() {\n            return id;\n        }\n        public void setId(int id) {\n            this.id = id;\n        }\n        public String getName() {\n            return name;\n        }\n        public void setName(String name) {\n            this.name = name;\n        }\n        @Override\n        public String toString() {\n            return "Student [id=" + id + ", name=" + name + "]";\n        }\n    }\n\n    public static void main(String[] args) {\n        new PassByValueObjectCase1().caller();\n    }\n\n    public void caller() {\n        Student student = new Student(10, "Nikhil");\n        String output = method(student);\n        /*\n         * \'output\' is insignificant in this example. we are more interested in\n         * \'student\'\n         */\n        System.out.println("output : " + output);\n        System.out.println("student : " + student);\n    }\n\n    public String method(Student student) {\n        student.setName("Anand");\n        return "output";\n    }\n}\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>output : output\nstudent : Student [id=10, name=Anand]\n</code></pre>\n\n<p><strong>Example 4:</strong></p>\n\n<p>/**</p>\n\n<p>In addition to what was mentioned in Example3 (PassByValueObjectCase1.java),  we cannot change the actual reference outside the original scope."</p>\n\n<p>Note: I am not pasting the code for <code>private class Student</code>. The class definition for <code>Student</code> is same as Example3.</p>\n\n<p>*/</p>\n\n<pre><code>public class PassByValueObjectCase2 {\n\n    public static void main(String[] args) {\n        new PassByValueObjectCase2().caller();\n    }\n\n    public void caller() {\n        // student has the actual reference to a Student object created\n        // can we change this actual reference outside the local scope? Let\'s see\n        Student student = new Student(10, "Nikhil");\n        String output = method(student);\n        /*\n         * \'output\' is insignificant in this example. we are more interested in\n         * \'student\'\n         */\n        System.out.println("output : " + output);\n        System.out.println("student : " + student); // Will it print Nikhil or Anand?\n    }\n\n    public String method(Student student) {\n        student = new Student(20, "Anand");\n        return "output";\n    }\n\n}\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>output : output\nstudent : Student [id=10, name=Nikhil]\n</code></pre>\n'}, {'answer_id': 34924074, 'author': 'Placinta Alexandru', 'author_id': 4957499, 'author_profile': 'https://Stackoverflow.com/users/4957499', 'pm_score': 4, 'selected': False, 'text': '<p>Java always uses <strong>call by value</strong>. That means the method gets copy of all parameter values.</p>\n\n<p>Consider next 3 situations:</p>\n\n<h2>1) Trying to change primitive variable</h2>\n\n<pre><code>public static void increment(int x) { x++; }\n\nint a = 3;\nincrement(a);\n</code></pre>\n\n<p>x will copy value of a and will increment x, a remains the same</p>\n\n<h2>2) Trying to change primitive field of an object</h2>\n\n<pre><code>public static void increment(Person p) { p.age++; }\n\nPerson pers = new Person(20); // age = 20\nincrement(pers);\n</code></pre>\n\n<p>p will copy reference value of pers and will increment age field, variables are referencing to the same object so age is changed</p>\n\n<h2>3) Trying to change reference value of reference variables</h2>\n\n<pre><code>public static void swap(Person p1, Person p2) {\n    Person temp = p1;\n    p1 = p2;\n    p2 = temp;\n}\n\nPerson pers1 = new Person(10);\nPerson pers2 = new Person(20);\nswap(pers1, pers2);\n</code></pre>\n\n<p>after calling swap p1, p2 copy reference values from pers1 and pers2, are swapping with values, so pers1 and pers2 remain the same</p>\n\n<p>So. you can change only fields of objects in method passing copy of reference value to this object.</p>\n'}, {'answer_id': 36040135, 'author': 'Gee Bee', 'author_id': 5903395, 'author_profile': 'https://Stackoverflow.com/users/5903395', 'pm_score': 4, 'selected': False, 'text': '<p>So many long answers. Let me give a simple one:</p>\n\n<ul>\n<li>Java always passes everything by value</li>\n<li>that means also references are passed by value</li>\n</ul>\n\n<p>In short, you can not modify value of any parameter passed, but you can call methods or change attributes of an object reference passed.</p>\n'}, {'answer_id': 36843568, 'author': 'OverCoder', 'author_id': 2164304, 'author_profile': 'https://Stackoverflow.com/users/2164304', 'pm_score': 4, 'selected': False, 'text': '<p>I made this little diagram that shows how the data gets created and passed</p>\n\n<p><a href="https://i.stack.imgur.com/77ppY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/77ppY.png" alt="Diagram of how data is created and passed"></a></p>\n\n<p>Note: Primitive values are passed as a value, the first reference to to that value is the method\'s argument</p>\n\n<p>That means:</p>\n\n<ul>\n<li>You can change the value of <code>myObject</code> <em>inside</em> the function</li>\n<li>But you can\'t change what <code>myObject</code> references to, inside the function, because <code>point</code> is not <code>myObject</code></li>\n<li>Remember, both <code>point</code> and <code>myObject</code> are <strong>references</strong>, different <strong>references</strong>, however, those references <strong>point</strong> at the same <code>new Point(0,0)</code></li>\n</ul>\n'}, {'answer_id': 37190132, 'author': 'Cdaragorn', 'author_id': 658018, 'author_profile': 'https://Stackoverflow.com/users/658018', 'pm_score': 4, 'selected': False, 'text': '<p>A lot of the confusion surrounding this issue comes from the fact that Java has attempted to redefine what "Pass by value" and "Pass by reference" mean. It\'s important to understand that these are <a href="https://en.wikipedia.org/wiki/Jargon" rel="noreferrer">Industry Terms</a>, and cannot be correctly understood outside of that context. They are meant to help you as you code and are valuable to understand, so let\'s first go over what they mean. </p>\n\n<p>A good description of both can be found <a href="http://cplus.about.com/od/glossar1/g/passbyrefdefn.htm" rel="noreferrer">here</a>.</p>\n\n<p><strong>Pass By Value</strong> The value the function received is a copy of the object the caller is using. It is entirely unique to the function and anything you do to that object will only be seen within the function.</p>\n\n<p><strong>Pass By Reference</strong> The value the function received is a reference to the object the caller is using. Anything the function does to the object that value refers to will be seen by the caller and it will be working with those changes from that point on.</p>\n\n<p>As is clear from those definitions, the fact that the reference is passed by value is irrelevant. If we were to accept that definition, then these terms become meaningless and all languages everywhere are only Pass By Value.</p>\n\n<p>No matter how you pass the reference in, it can only ever be passed by value. That isn\'t the point. The point is that you passed a reference to your own object to the function, not a copy of it. The fact that you can throw away the reference you received is irrelevant. Again, if we accepted that definition, these terms become meaningless and everyone is always passing by value.</p>\n\n<p>And no, C++\'s special "pass by reference" syntax is not the exclusive definition of pass by reference. It is purely a convenience syntax meant to make it so that you don\'t need to use pointer syntax after passing the pointer in. It is still passing a pointer, the compiler is just hiding that fact from you. It also still passes that pointer BY VALUE, the compiler is just hiding that from you.</p>\n\n<p>So, with this understanding, we can look at Java and see that it actually has both. All Java primitive types are always pass by value because you receive a copy of the caller\'s object and cannot modify their copy. All Java reference types are always pass by reference because you receive a reference to the caller\'s object and can directly modify their object. </p>\n\n<p>The fact that you cannot modify the caller\'s reference has nothing to do with pass by reference and is true in every language that supports pass by reference.</p>\n'}, {'answer_id': 37669835, 'author': 'Ravi Sanwal', 'author_id': 1195605, 'author_profile': 'https://Stackoverflow.com/users/1195605', 'pm_score': 3, 'selected': False, 'text': '<p>There is a very simple way to understand this.\nLets\'s take C++ pass by reference.</p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass Foo {\n    private:\n        int x;\n    public:\n        Foo(int val) {x = val;}\n        void foo()\n        {\n            cout&lt;&lt;x&lt;&lt;endl;\n        }\n};\n\nvoid bar(Foo&amp; ref)\n{\n    ref.foo();\n    ref = *(new Foo(99));\n    ref.foo();\n}\n\nint main()\n{\n   Foo f = Foo(1);\n   f.foo();\n   bar(f);\n   f.foo();\n\n   return 0;\n}\n</code></pre>\n\n<p>What is the outcome?</p>\n\n<pre>\n1\n1\n99\n99\n</pre>\n\n<p>So, after bar() assigned a new value to a "reference" passed in, it actually changed the one which was passed in from main itself, explaining the last f.foo() call from main printing 99.</p>\n\n<p>Now, lets see what java says.</p>\n\n<pre><code>public class Ref {\n\n    private static class Foo {\n        private int x;\n\n        private Foo(int x) {\n            this.x = x;\n        }\n\n        private void foo() {\n            System.out.println(x);\n        }\n    }\n\n    private static void bar(Foo f) {\n        f.foo();\n        f = new Foo(99);\n        f.foo();\n    }\n\n    public static void main(String[] args) {\n        Foo f = new Foo(1);\n        System.out.println(f.x);\n        bar(f);\n        System.out.println(f.x);\n    }\n\n}\n</code></pre>\n\n<p>It says:</p>\n\n<pre>\n1\n1\n99\n1\n</pre>\n\n<p>Voilà, the reference of Foo in main that was passed to bar, is still unchanged!</p>\n\n<p>This example clearly shows that java is not the same as C++ when we say "pass by reference". Essentially, java is passing "references" as "values" to functions, meaning java is pass by value.</p>\n'}, {'answer_id': 38550131, 'author': 'user1767316', 'author_id': 1767316, 'author_profile': 'https://Stackoverflow.com/users/1767316', 'pm_score': 6, 'selected': False, 'text': "<p><strong>In Java, method arguments are all passed by value :</strong></p>\n<p>Java arguments are <strong>all passed by value</strong> (the value  or reference is copied when used by the method) :</p>\n<p>In the case of primitive types, Java behaviour is simple:\nThe value is copied in another instance of the primitive type.</p>\n<p>In case of Objects, this is the same:\nObject variables are references (mem buckets holding only Object’s <strong>address</strong> instead of a primitive value) that was created using the &quot;new&quot; keyword, and are copied like primitive types.</p>\n<p>The behaviour can appear different from primitive types: Because the copied object-variable contains the same address (to the same Object).\nObject's <strong>content/members</strong> might still be modified within a method and later access outside, giving the illusion that the (containing) Object itself was passed by reference.</p>\n<p>&quot;String&quot; Objects appear to be a good <strong>counter-example</strong> to the urban legend saying that &quot;Objects are passed by reference&quot;:</p>\n<p>In effect, using a method, you will never be able, to update the value of a String passed as argument:</p>\n<p>A String Object, holds characters by an array declared <strong>final</strong> that can't be modified.\nOnly the address of the Object might be replaced by another using &quot;new&quot;.\nUsing &quot;new&quot; to update the variable, will not let the Object be accessed from outside, since the variable was initially passed by value and copied.</p>\n"}, {'answer_id': 39709353, 'author': 'Vivek Kumar', 'author_id': 5128145, 'author_profile': 'https://Stackoverflow.com/users/5128145', 'pm_score': 3, 'selected': False, 'text': '<p>Java does manipulate objects by reference, and all object variables are references. However, Java doesn\'t pass method arguments by reference; it passes them by value.</p>\n\n<p>Take the\xa0badSwap()\xa0method for example:</p>\n\n<pre><code>    public void badSwap(int var1, int\n var2{ int temp = var1; var1 = var2; var2 =\n temp; }\n</code></pre>\n\n<p>When\xa0badSwap()\xa0returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from\xa0int\xa0to\xa0Object, since Java passes object references by value as well. Now, here is where it gets tricky:</p>\n\n<pre><code>public void tricky(Point arg1, Point   arg2)\n{ arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; }\npublic static void main(String [] args) { \n\n Point pnt1 = new Point(0,0); Point pnt2\n = new Point(0,0); System.out.println("X:\n " + pnt1.x + " Y: " +pnt1.y);\n\n     System.out.println("X: " + pnt2.x + " Y:\n " +pnt2.y); System.out.println(" ");\n\n     tricky(pnt1,pnt2);\n System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);\n\n     System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); }\n</code></pre>\n\n<p>If we execute this\xa0main()\xa0method, we see the following output:</p>\n\n<p>X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0</p>\n\n<p>The method successfully alters the value ofpnt1, even though it is passed by value; however, a swap of\xa0pnt1\xa0and\xa0pnt2\xa0fails! This is the major source of confusion. In themain()\xa0method,\xa0pnt1\xa0and\xa0pnt2\xa0are nothing more than object references. When you passpnt1\xa0and\xa0pnt2\xa0to the\xa0tricky()\xa0method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually\xa0copies\xa0of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.</p>\n\n<p>Java copies and passes the\xa0reference\xa0by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.</p>\n'}, {'answer_id': 39767073, 'author': 'khakishoiab', 'author_id': 5797598, 'author_profile': 'https://Stackoverflow.com/users/5797598', 'pm_score': 4, 'selected': False, 'text': '<p>A simple test to check whether a language supports pass-by-reference is simply writing a traditional swap.\nCan you write a traditional swap(a,b) method/function in Java?</p>\n\n<p>A traditional swap method or function takes two arguments and swaps them such that variables passed into the function are changed outside the function. Its basic structure looks like</p>\n\n<p>(Non-Java) Basic swap function structure</p>\n\n<pre><code>swap(Type arg1, Type arg2) {\n    Type temp = arg1;\n    arg1 = arg2;\n    arg2 = temp;\n}\n</code></pre>\n\n<p>If you can write such a method/function in your language such that calling</p>\n\n<pre><code>Type var1 = ...;\nType var2 = ...;\nswap(var1,var2);\n</code></pre>\n\n<p>actually switches the values of the variables var1 and var2, the language supports pass-by-reference.\nBut <strong>Java does not allow such a thing</strong> as it supports passing the values only and not pointers or references.</p>\n'}, {'answer_id': 40593867, 'author': 'Soner from The Ottoman Empire', 'author_id': 4990642, 'author_profile': 'https://Stackoverflow.com/users/4990642', 'pm_score': 4, 'selected': False, 'text': "<p>The major cornerstone knowledge must be the quoted one,</p>\n\n<blockquote>\n  <p>When an object reference is passed to a method, the reference itself\n  is passed by use of <em>call-by-value</em>. However, since the value being\n  passed refers to an object, the copy of that value will still refer to\n  the same object referred to by its corresponding argument.</p>\n</blockquote>\n\n<p>Java: A Beginner's Guide, Sixth Edition, Herbert Schildt</p>\n"}, {'answer_id': 40631632, 'author': 'Taleev Aalam', 'author_id': 7051714, 'author_profile': 'https://Stackoverflow.com/users/7051714', 'pm_score': 3, 'selected': False, 'text': '<p>It seems everything is call by value in java as i have tried to understand by the following program</p>\n<p><strong>Class-S</strong></p>\n<pre><code>class S{\nString name=&quot;alam&quot;;\npublic void setName(String n){\nthis.name=n; \n}}\n</code></pre>\n<p><strong>Class-Sample</strong></p>\n<pre><code>    public class Sample{\n    public static void main(String args[]){\n    S s=new S();\n    S t=new S();\n    System.out.println(s.name);\n    System.out.println(t.name);\n    t.setName(&quot;taleev&quot;);\n    System.out.println(t.name);\n    System.out.println(s.name);\n    s.setName(&quot;Harry&quot;);\n    System.out.println(t.name);\n    System.out.println(s.name);\n    }}\n</code></pre>\n<p><strong>Output</strong></p>\n<blockquote>\n<p>alam</p>\n<p>alam</p>\n<p>taleev</p>\n<p>alam</p>\n<p>taleev</p>\n<p>harry</p>\n</blockquote>\n<p>As we have define class S with instance variable name with value <strong>taleev</strong> so for\nall the objects that we initialize from it will have the name variable with value of <strong>taleev</strong> but if we change the name\'s value of any objects then it is changing the name of only that copy of the class(Object) not for every class so after that also when we do <strong>System.out.println(s.name)</strong> it is printing <strong>taleev</strong> only we can not change the name\'s value that we have defined originally, and the value that we are changing is the object\'s value not the instance variable value so once we have define instance variable we are unable to change it</p>\n<p>So i think that is how it shows that java deals with <strong>values</strong> only not with the <strong>references</strong></p>\n<p>The memory allocation for the primitive variables can be understood by  <a href="http://www.informit.com/articles/article.aspx?p=31755&amp;seqNum=8" rel="nofollow noreferrer">this</a></p>\n'}, {'answer_id': 41393112, 'author': 'Rahul Kumar', 'author_id': 4958222, 'author_profile': 'https://Stackoverflow.com/users/4958222', 'pm_score': 4, 'selected': False, 'text': '<p>Java, for sure, without a doubt, is "pass by value". Also, since Java is (mostly) object-oriented and objects work with references, it\'s easy to get confused and think of it to be "pass by reference"</p>\n\n<p>Pass by value means you pass the value to the method and if the method changes the passed value, the real entity doesn\'t change. Pass by reference, on the other hand, means a reference is passed to the method, and if the method changes it, the passed object also changes.</p>\n\n<p>In Java, usually when we pass an object to a method, we basically pass the reference of the object as-a-value because that\'s how Java works; it works with references and addresses as far as Object in the heap goes.</p>\n\n<p>But to test if it is really pass by value or pass by reference, you can use a primitive type and references:</p>\n\n<pre><code>@Test\npublic void sampleTest(){\n    int i = 5;\n    incrementBy100(i);\n    System.out.println("passed ==&gt; "+ i);\n    Integer j = new Integer(5);\n    incrementBy100(j);\n    System.out.println("passed ==&gt; "+ j);\n}\n/**\n * @param i\n */\nprivate void incrementBy100(int i) {\n    i += 100;\n    System.out.println("incremented = "+ i);\n}\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>incremented = 105\npassed ==&gt; 5\nincremented = 105\npassed ==&gt; 5\n</code></pre>\n\n<p>So in both cases, whatever happens inside the method doesn\'t change the real Object, because the value of that object was passed, and not a reference to the object itself.</p>\n\n<p>But when you pass a custom object to a method, and the method and changes it, it will change the real object too, because even when you passed the object, you passed it\'s reference as a value to the method. Let\'s try another example:</p>\n\n<pre><code>@Test\npublic void sampleTest2(){\n    Person person = new Person(24, "John");\n    System.out.println(person);\n    alterPerson(person);\n    System.out.println(person);\n}\n\n/**\n * @param person\n */\nprivate void alterPerson(Person person) {\n    person.setAge(45);\n    Person altered = person;\n    altered.setName("Tom");\n}\n\nprivate static class Person{\n    private int age;\n    private String name; \n\n    public Person(int age, String name) {\n        this.age=age;\n        this.name =name;\n    }\n\n    public int getAge() {\n        return age;\n    }\n\n    public void setAge(int age) {\n        this.age = age;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        builder.append("Person [age=");\n        builder.append(age);\n        builder.append(", name=");\n        builder.append(name);\n        builder.append("]");\n        return builder.toString();\n    }\n\n}\n</code></pre>\n\n<p>In this case, the output is:</p>\n\n<pre><code>Person [age=24, name=John]\nPerson [age=45, name=Tom]\n</code></pre>\n'}, {'answer_id': 41901960, 'author': 'Raja', 'author_id': 1952852, 'author_profile': 'https://Stackoverflow.com/users/1952852', 'pm_score': 3, 'selected': False, 'text': '<p>I tried to simplify the examples above, keeping only the essense of the problem.\nLet me present this as a story that is easy to remember and apply correctly.\nThe story goes like this:\nYou have a pet dog, Jimmy, whose tail is 12 inches long.\nYou leave it with a vet for a few weeks while you are travelling abroad.</p>\n\n<p>The vet doesn\'t like the long tail of Jimmy, so he wants to cut it by half.\nBut being a good vet, he knows that he has no right to mutilate other people\'s dogs.\nSo he first makes a clone of the dog (with the <em>new</em> key word) and cuts the tail of the clone.\nWhen the dog finally returns to you, it has the original 12 inch tail in tact. Happy ending !</p>\n\n<p>The next time you travel, you take the dog, unwittingly, to a wicked vet. \nHe is also a hater of long tails, so he cuts it down to a miserable 2 inches. \nBut he does this to your dear Jimmy, not a clone of it.\nWhen you return, you are shocked to see Jimmy pathetically wagging a 2 inch stub.</p>\n\n<p>Moral of the story: When you pass on your pet, you are giving away whole and unfettered\ncustody of the pet to the vet. He is free to play any kind of havoc with it.\nPassing by <em>value</em>, by <em>reference</em>, by <em>pointer</em> are all just technical wrangling. \nUnless the vet clones it first, he ends up mutilating the original dog.</p>\n\n<pre><code>public class Doggie {\n\n    public static void main(String...args) {\n        System.out.println("At the owner\'s home:");\n        Dog d = new Dog(12);\n        d.wag();\n        goodVet(d);\n        System.out.println("With the owner again:)");\n        d.wag();\n        badVet(d);\n        System.out.println("With the owner again(:");\n        d.wag();\n    }\n\n    public static void goodVet (Dog dog) {\n        System.out.println("At the good vet:");\n        dog.wag();\n        dog = new Dog(12); // create a clone\n        dog.cutTail(6);    // cut the clone\'s tail\n        dog.wag();\n    }\n\n    public static void badVet (Dog dog) {\n        System.out.println("At the bad vet:");\n        dog.wag();\n        dog.cutTail(2);   // cut the original dog\'s tail\n        dog.wag();\n    }    \n}\n\nclass Dog {\n\n    int tailLength;\n\n    public Dog(int originalLength) {\n        this.tailLength = originalLength;\n    }\n\n    public void cutTail (int newLength) {\n        this.tailLength = newLength;\n    }\n\n    public void wag()  {\n        System.out.println("Wagging my " +tailLength +" inch tail");\n    }\n}\n\nOutput:\nAt the owner\'s home:\nWagging my 12 inch tail\nAt the good vet:\nWagging my 12 inch tail\nWagging my 6 inch tail\nWith the owner again:)\nWagging my 12 inch tail\nAt the bad vet:\nWagging my 12 inch tail\nWagging my 2 inch tail\nWith the owner again(:\nWagging my 2 inch tail\n</code></pre>\n'}, {'answer_id': 43113746, 'author': 'Basheer AL-MOMANI', 'author_id': 4251431, 'author_profile': 'https://Stackoverflow.com/users/4251431', 'pm_score': 4, 'selected': False, 'text': '<p>Unlike some other languages, Java does not allow you to choose between pass-by-value and pass-by-reference.</p>\n\n<p>All arguments are passed by value. </p>\n\n<p>A method call can pass two <code>types of values</code>to a method</p>\n\n<ul>\n<li>copies of primitive values (e.g., values of type int and double)</li>\n<li>copies of references to objects.</li>\n</ul>\n\n<p><code>Objects themselves cannot be passed to methods</code>. When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.</p>\n\n<p>This is also true for reference-type parameters. If you modify a reference-type parameter so that it refers to another object, only the parameter refers to the new object—the reference stored in the caller’s variable still refers to the original object.</p>\n\n<p>References: <a href="https://www.safaribooksonline.com/library/view/javatm-how-to/9780133813036/ch07lev2sec11.html" rel="noreferrer">Java™ How To Program (Early Objects), Tenth Edition</a> </p>\n'}, {'answer_id': 43290680, 'author': 'Himanshu arora', 'author_id': 3664592, 'author_profile': 'https://Stackoverflow.com/users/3664592', 'pm_score': 6, 'selected': False, 'text': "<p>Java is a pass by value(stack memory)</p>\n<p>How it works</p>\n<ul>\n<li><p>Let's first understand that where java stores primitive data type and object data type.</p>\n</li>\n<li><p>Primitive data types itself and object references are stored in the stack.\nObjects themselves are stored in the heap.</p>\n</li>\n<li><p>It means, Stack memory stores primitive data types and also the\naddresses of objects.</p>\n</li>\n<li><p>And you always pass a copy of the bits of the value of the reference.</p>\n</li>\n<li><p>If it's a primitive data type then these copied bits contain the value of the primitive data type itself, That's why when we change the value of argument inside the method then it does not reflect the changes outside.</p>\n</li>\n<li><p>If it's an object data type like <strong>Foo foo=new Foo()</strong> then in this case copy of the address of the object passes like file shortcut  , suppose we have a text file <strong>abc.txt</strong> at <strong>C:\\desktop</strong> and suppose we make shortcut of the same file and put this inside <strong>C:\\desktop\\abc-shortcut</strong> so when you access the file from <strong>C:\\desktop\\abc.txt</strong> and write <strong>'Stack Overflow'</strong> and close the file and again you open the file from shortcut then you write <strong>' is the largest online community for programmers to learn'</strong> then total file change will be <strong>'Stack Overflow is the largest online community for programmers to learn'</strong> which means it doesn't matter from where you open the file , each time we were accessing the same file , here we can assume <strong>Foo</strong> as a file and suppose foo stored at <strong>123hd7h</strong>(original address like <strong>C:\\desktop\\abc.txt</strong> ) address and <strong>234jdid</strong>(copied address like <strong>C:\\desktop\\abc-shortcut</strong> which actually contains the original address of the file inside) ..\nSo for better understanding make shortcut file and feel.</p>\n</li>\n</ul>\n"}, {'answer_id': 46026822, 'author': 'Supriya', 'author_id': 4233180, 'author_profile': 'https://Stackoverflow.com/users/4233180', 'pm_score': 4, 'selected': False, 'text': '<p>Java is pass by value. </p>\n\n<p>There are already great answers on this thread. Somehow, I was never clear on pass by value/reference with respect to primitive data types and with respect to objects. Therefore, I tested it out for my satisfaction and clarity with the following piece of code; might help somebody seeking similar clarity:</p>\n\n<pre><code>class Test    {\n\npublic static void main (String[] args) throws java.lang.Exception\n{\n    // Primitive type\n    System.out.println("Primitve:");\n    int a = 5;\n    primitiveFunc(a);\n    System.out.println("Three: " + a);    //5\n\n    //Object\n    System.out.println("Object:");\n    DummyObject dummyObject = new DummyObject();\n    System.out.println("One: " + dummyObject.getObj());    //555\n    objectFunc(dummyObject);\n    System.out.println("Four: " + dummyObject.getObj());    //666 (555 if line in method uncommented.)\n\n}\n\nprivate static void primitiveFunc(int b)    {\n    System.out.println("One: " + b);    //5\n    b = 10;\n    System.out.println("Two:" + b);    //10\n}\n\nprivate static void objectFunc(DummyObject b)   {\n    System.out.println("Two: " + b.getObj());    //555\n    //b = new DummyObject();\n    b.setObj(666);\n    System.out.println("Three:" + b.getObj());    //666\n}\n\n}\n\nclass DummyObject   {\n    private int obj = 555;\n    public int getObj() { return obj; }\n    public void setObj(int num) { obj = num; }\n}\n</code></pre>\n\n<p>If the line <code>b = new DummyObject()</code> is uncommented, the modifications made thereafter are made on a <em>new</em> object, a new instantiation. Hence, it is not reflected in the place where the method is called from. However, otherwise, the change is reflected as the modifications are only made on a "reference" of the object, i.e - b points to the same dummyObject. </p>\n\n<p>Illustrations in one of the answers in this thread (<a href="https://stackoverflow.com/a/12429953/4233180">https://stackoverflow.com/a/12429953/4233180</a>) can help gain a deeper understanding.</p>\n'}, {'answer_id': 46077533, 'author': 'Raj S. Rusia', 'author_id': 7178104, 'author_profile': 'https://Stackoverflow.com/users/7178104', 'pm_score': 5, 'selected': False, 'text': '<p>One of the biggest confusion in Java programming language is whether Java is <strong>Pass by Value</strong> or <strong>Pass by Reference</strong>.</p>\n\n<p>First of all, we should understand what is meant by pass by value or pass by reference.</p>\n\n<p><strong>Pass by Value:</strong> The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.</p>\n\n<p><strong>Pass by Reference:</strong> An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.</p>\n\n<p>Let’s say we have a class Balloon like below.</p>\n\n<pre><code>public class Balloon {\n\n    private String color;\n\n    public Balloon(){}\n\n    public Balloon(String c){\n        this.color=c;\n    }\n\n    public String getColor() {\n        return color;\n    }\n\n    public void setColor(String color) {\n        this.color = color;\n    }\n}\n</code></pre>\n\n<p>And we have a simple program with a generic method to swap two objects, the class looks like below.</p>\n\n<pre><code>public class Test {\n\n    public static void main(String[] args) {\n\n        Balloon red = new Balloon("Red"); //memory reference 50\n        Balloon blue = new Balloon("Blue"); //memory reference 100\n\n        swap(red, blue);\n        System.out.println("red color="+red.getColor());\n        System.out.println("blue color="+blue.getColor());\n\n        foo(blue);\n        System.out.println("blue color="+blue.getColor());\n\n    }\n\n    private static void foo(Balloon balloon) { //baloon=100\n        balloon.setColor("Red"); //baloon=100\n        balloon = new Balloon("Green"); //baloon=200\n        balloon.setColor("Blue"); //baloon = 200\n    }\n\n    //Generic swap method\n    public static void swap(Object o1, Object o2){\n        Object temp = o1;\n        o1=o2;\n        o2=temp;\n    }\n}\n</code></pre>\n\n<p>When we execute the above program, we get following output.</p>\n\n<pre><code>red color=Red\nblue color=Blue\nblue color=Red\n</code></pre>\n\n<p>If you look at the first two lines of the output, it’s clear that swap method didn’t work. This is because Java is passed by value, this swap() method test can be used with any programming language to check whether it’s pass by value or pass by reference.</p>\n\n<p>Let’s analyze the program execution step by step.</p>\n\n<pre><code>Balloon red = new Balloon("Red");\nBalloon blue = new Balloon("Blue");\n</code></pre>\n\n<p>When we use the new operator to create an instance of a class, the instance is created and the variable contains the reference location of the memory where the object is saved. For our example, let’s assume that “red” is pointing to 50 and “blue” is pointing to 100 and these are the memory location of both Balloon objects.</p>\n\n<p>Now when we are calling swap() method, two new variables o1 and o2 are created pointing to 50 and 100 respectively.</p>\n\n<p>So below code snippet explains what happened in the swap() method execution.</p>\n\n<pre><code>public static void swap(Object o1, Object o2){ //o1=50, o2=100\n    Object temp = o1; //temp=50, o1=50, o2=100\n    o1=o2; //temp=50, o1=100, o2=100\n    o2=temp; //temp=50, o1=100, o2=50\n} //method terminated\n</code></pre>\n\n<p>Notice that we are changing values of o1 and o2 but they are copies of “red” and “blue” reference locations, so actually, there is no change in the values of “red” and “blue” and hence the output.</p>\n\n<p>If you have understood this far, you can easily understand the cause of confusion. Since the variables are just the reference to the objects, we get confused that we are passing the reference so Java is passed by reference. However, we are passing a copy of the reference and hence it’s pass by value. I hope it clears all the doubts now.</p>\n\n<p>Now let’s analyze <strong>foo()</strong> method execution.</p>\n\n<pre><code>private static void foo(Balloon balloon) { //baloon=100\n    balloon.setColor("Red"); //baloon=100\n    balloon = new Balloon("Green"); //baloon=200\n    balloon.setColor("Blue"); //baloon = 200\n}\n</code></pre>\n\n<p>The first line is the important one when we call a method the method is called on the Object at the reference location. At this point, the balloon is pointing to 100 and hence it’s color is changed to Red.</p>\n\n<p>In the next line, balloon reference is changed to 200 and any further methods executed are happening on the object at memory location 200 and not having any effect on the object at memory location 100. This explains the third line of our program output printing blue color=Red.</p>\n\n<p>I hope above explanation clear all the doubts, just remember that variables are references or pointers and its copy is passed to the methods, so Java is always passed by value. It would be more clear when you will learn about Heap and Stack memory and where different objects and references are stored.</p>\n'}, {'answer_id': 46871427, 'author': 'NAGHMAAN MOHASEEN', 'author_id': 8808036, 'author_profile': 'https://Stackoverflow.com/users/8808036', 'pm_score': 4, 'selected': False, 'text': "<h3>Java is strictly passed by value</h3>\n\n<p>When I say <strong><em>pass by value</em></strong> it means whenever caller has invoked the callee the arguments(ie: the data to be passed to the other function) <strong>is copied</strong> and placed in the formal parameters (callee's local variables for receiving the input). Java makes data communications from one function to other function only in a pass by value environment.</p>\n\n<p>An important point would be to know that even C language is strictly passed by value only:<br>\n<em>ie:</em> Data is copied from caller to the callee and more ever the operation performed by the callee are on the same memory location and \nwhat we pass them is the address of that location that we obtain from (&amp;) operator and the identifier used in the formal parameters are declared to be a pointer variable (*) using which we can get inside the memory location for accessing the data in it.</p>\n\n<p>Hence here the formal parameter is nothing but mere aliases for that location. And any modifications done on that location is visible where ever that scope of the variable (that identifies that location) is alive.</p>\n\n<p>In Java, there is no concept of pointers (<em>ie:</em> there is nothing called a pointer variable), although we can think of reference variable as a pointer technically in java we call it as a handle. The reason why we call the pointer to an address as a handle in java is  because a pointer variable is capable of performing not just single dereferencing but multiple dereferencing \nfor example: <code>int *p;</code> in P means p points to an integer\nand <code>int **p;</code> in C means p is pointer to a pointer to an integer\nwe dont have this facility in Java, so its absolutely correct and technically legitimate to say it as an handle, also there are rules for pointer arithmetic in C. Which allows performing arithmetic operation on pointers with constraints on it. </p>\n\n<p>In C we call such mechanism of passing address and receiving them with pointer variables as <em>pass by reference</em> since we are passing their addresses and receiving them as pointer variable in formal parameter but at the compiler level that address is copied into pointer variable (since data here is address even then its data ) hence we can be 100% sure that C is Strictly passed by value (as we are passing data only)</p>\n\n<p>(and if we pass the data directly in C we call that as pass by value.)</p>\n\n<p>In java when we do the same we do it with the handles; since they are not called pointer variables like in (as discussed above) even though we are passing the references we cannot say its pass by reference since we are not collecting that with a pointer variable in Java.</p>\n\n<p>Hence Java <strong>strictly use pass by value mechanism</strong> </p>\n"}, {'answer_id': 47844599, 'author': 'Premraj', 'author_id': 1697099, 'author_profile': 'https://Stackoverflow.com/users/1697099', 'pm_score': 4, 'selected': False, 'text': '<p>Data is shared between functions by passing parameters. Now, there are 2 ways of passing parameters:</p>\n<ul>\n<li><p><strong>passed by reference :</strong> caller and callee use same variable for parameter.</p>\n</li>\n<li><p><strong>passed by value :</strong> caller and callee have two independent variables with same value.</p>\n</li>\n</ul>\n<p>Java uses <em><strong>pass by value</strong></em></p>\n<ul>\n<li>When passing primitive data, it copies the value of primitive data type.</li>\n<li>When passing object, it copies the address of object and passes to callee method variable.</li>\n</ul>\n<p>Java follows the following rules in storing variables:</p>\n<ul>\n<li>Local variables like primitives and object references are created on Stack memory.</li>\n<li>Objects are created on Heap memory.</li>\n</ul>\n<p>Example using primitive data type:</p>\n<pre><code>public class PassByValuePrimitive {\n    public static void main(String[] args) {\n        int i=5;\n        System.out.println(i);  //prints 5\n        change(i);\n        System.out.println(i);  //prints 5\n    }\n    \n    \n    private static void change(int i) {\n        System.out.println(i);  //prints 5\n        i=10;\n        System.out.println(i); //prints 10\n        \n    }\n}\n</code></pre>\n<p>Example using object:</p>\n<pre><code>public class PassByValueObject {\n    public static void main(String[] args) {\n        List&lt;String&gt; list = new ArrayList&lt;&gt;();\n        list.add(&quot;prem&quot;);\n        list.add(&quot;raj&quot;);\n        new PassByValueObject().change(list);\n        System.out.println(list); // prints [prem, raj, ram]\n        \n    }\n    \n    \n    private  void change(List list) {\n        System.out.println(list.get(0)); // prem\n        list.add(&quot;ram&quot;);\n        list=null;\n        System.out.println(list.add(&quot;bheem&quot;)); //gets NullPointerException\n    }\n}\n</code></pre>\n'}, {'answer_id': 48591063, 'author': 'Felypp Oliveira', 'author_id': 1977836, 'author_profile': 'https://Stackoverflow.com/users/1977836', 'pm_score': 5, 'selected': False, 'text': '<p>This is the best way to answer the question imo...</p>\n\n<p>First, we must understand that, in Java, the <em>parameter passing behavior</em>...</p>\n\n<pre><code>public void foo(Object param)\n{\n  // some code in foo...\n}\n\npublic void bar()\n{\n  Object obj = new Object();\n\n  foo(obj);\n}\n</code></pre>\n\n<p>is exactly the same as...</p>\n\n<pre><code>public void bar()\n{\n  Object obj = new Object();\n\n  Object param = obj;\n\n  // some code in foo...\n}\n</code></pre>\n\n<p>not considering stack locations, which aren\'t relevant in this discussion.</p>\n\n<p>So, in fact, what we\'re looking for in Java is how <em>variable assignment</em> works. I found it in <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html" rel="noreferrer">the docs</a> :</p>\n\n<blockquote>\n  <p>One of the most common operators that you\'ll encounter is the simple assignment operator "=" [...] <b>it assigns the value</b> on its right to the operand on its left:</p>\n  \n  <p>int cadence = 0;<br>\n   int speed = 0;<br>\n   int gear = 1;  </p>\n  \n  <p>This operator can also be used on objects to assign <b>object references</b> [...]</p>\n</blockquote>\n\n<p>It\'s clear how this operator acts in two distinct ways: assign values and assign references. The last, when it\'s an object... the first, when it isn\'t an object, that is, when it\'s a primitive. But so, can we understand that Java\'s function params can be <em>pass-by-value</em> and <em>pass-by-reference</em>? </p>\n\n<p>The truth is in the code. Let\'s try it:</p>\n\n<pre><code>public class AssignmentEvaluation\n{\n  static public class MyInteger\n  {\n    public int value = 0;\n  }\n\n  static public void main(String[] args)\n  {\n    System.out.println("Assignment operator evaluation using two MyInteger objects named height and width\\n");\n\n    MyInteger height = new MyInteger();\n    MyInteger width  = new MyInteger();\n\n    System.out.println("[1] Assign distinct integers to height and width values");\n\n    height.value = 9;\n    width.value  = 1;\n\n    System.out.println("-&gt;  height is " + height.value + " and width is " + width.value + ", we are different things! \\n");\n\n    System.out.println("[2] Assign to height\'s value the width\'s value");\n\n    height.value = width.value;\n\n    System.out.println("-&gt;  height is " + height.value + " and width is " + width.value + ", are we the same thing now? \\n");\n\n    System.out.println("[3] Assign to height\'s value an integer other than width\'s value");\n\n    height.value = 9;\n\n    System.out.println("-&gt;  height is " + height.value + " and width is " + width.value + ", we are different things yet! \\n");\n\n    System.out.println("[4] Assign to height the width object");\n\n    height = width;\n\n    System.out.println("-&gt;  height is " + height.value + " and width is " + width.value + ", are we the same thing now? \\n");\n\n    System.out.println("[5] Assign to height\'s value an integer other than width\'s value");\n\n    height.value = 9;\n\n    System.out.println("-&gt;  height is " + height.value + " and width is " + width.value + ", we are the same thing now! \\n");\n\n    System.out.println("[6] Assign to height a new MyInteger and an integer other than width\'s value");\n\n    height = new MyInteger();\n    height.value = 1;\n\n    System.out.println("-&gt;  height is " + height.value + " and width is " + width.value + ", we are different things again! \\n");\n  }\n}\n</code></pre>\n\n<p>This is the output of my run:</p>\n\n<pre>\nAssignment operator evaluation using two MyInteger objects named height and width\n\n[1] Assign distinct integers to height and width values\n->  height is 9 and width is 1, we are different things! \n\n[2] Assign to height\'s value the width\'s value\n->  height is 1 and width is 1, are we the same thing now? \n\n[3] Assign to height\'s value an integer other than width\'s value\n->  height is 9 and width is 1, we are different things yet! \n\n[4] Assign to height the width object\n->  height is 1 and width is 1, are we the same thing now? \n\n[5] Assign to height\'s value an integer other than width\'s value\n->  height is 9 and width is 9, we are the same thing now! \n\n[6] Assign to height a new MyInteger and an integer other than width\'s value\n->  height is 1 and width is 9, we are different things again! \n</pre>\n\n<p>In <em>[2]</em> we have distinct objects and assign one variable\'s value to the other. But after assigning a new value in <em>[3]</em> the objects had different values, which means that in <em>[2]</em> the assigned value was a copy of the primitive variable, usually called <strong>pass-by-value</strong>, otherwise, the values printed in <em>[3]</em> should be the same.</p>\n\n<p>In <em>[4]</em> we still have distinct objects and assign one object to the other. And after assigning a new value in <em>[5]</em> the objects had the same values, which means that in <em>[4]</em> the assigned object was not a copy of the other, which should be called <strong>pass-by-reference</strong>. But, if we look carefully in <em>[6]</em>, we can\'t be so sure that no copy was done... ?????</p>\n\n<p>We can\'t be so sure because in <em>[6]</em> the objects were the same, then we assigned a new object to one of them, and after, the objects had different values! How can they be distinct now if they were the same? They should be the same here too!  ?????</p>\n\n<p>We\'ll need to remember <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html" rel="noreferrer">the docs</a> to understand what\'s going on:</p>\n\n<blockquote>\n  <p>This operator can also be used on objects to assign <b>object references</b></p>\n</blockquote>\n\n<p>So our two variables were storing references... our variables had the same reference after <em>[4]</em> and different references after <em>[6]</em>... if such a thing is possible, this means that assignment of objects is done by copy of the object\'s reference, otherwise, if it was not a copy of reference, the printed value of the variables in <em>[6]</em> should be the same. So objects (references), just like primitives, are copied to variables through assignment, what people usually call <em>pass-by-value</em>. That\'s the only <em>pass-by-</em> in Java.</p>\n'}, {'answer_id': 49330809, 'author': 'mc01', 'author_id': 3216970, 'author_profile': 'https://Stackoverflow.com/users/3216970', 'pm_score': 3, 'selected': False, 'text': "<h2>PT 1: Of Realty Listings</h2>\n<p>There is a blue, 120sq-ft &quot;Tiny House&quot; currently parked at 1234 Main St with a nicely manicured lawn &amp; flower bed out front.</p>\n<p>A Realtor with a local firm is hired and told to keep a listing for that house.</p>\n<p>Let's call that Realtor &quot;Bob.&quot; Hi Bob.</p>\n<p>Bob keeps his Listing, which he calls <code>tinyHouseAt1234Main</code>, up to date with a webcam that allows him to note any changes to the actual house in real time. He also keeps a tally of how many people have asked about the listing.\nBob's integer <code>viewTally</code> for the house is at 42 today.</p>\n<p>Whenever someone wants info about the blue Tiny House at 1234 Main St, they ask Bob.</p>\n<p>Bob looks up his Listing <code>tinyHouseAt1234Main</code> and tells them all about it - the color, the nice lawn, the loft bed and the composting toilet, etc. Then he adds their inquiry to his <code>viewTally</code>. He doesn't tell them the real, physical address though, because Bob's firm specializes in Tiny Houses that could be moved at any time. The tally is now 43.</p>\n<p>At another firm, Realtors might explicitly say their listing &quot;points&quot; to the house at 1234 Main St, denoting this with a little <code>*</code> next to it, because they mainly deal with houses that rarely ever move (though presumably there are reasons for doing so). Bob's firm doesn't bother doing this.</p>\n<p>Now, of course Bob doesn't physically go and put the <em>actual</em> house on a truck to show it to clients directly - that would be impractical and a ridiculous waste of resources. Passing a full copy of his tally sheet is one thing, but passing around the whole house all the time is costly and ridiculous.</p>\n<p>(Aside: Bob's firm also doesn't 3D print new &amp; unique copies of a listed house every single time someone asks about it. That's what the upstart, similarly named web-based firm &amp; its spinoffs do - that's expensive and slower, and people often get the 2 firms confused, but they're quite popular anyway).</p>\n<p>At some other, older firms closer to the Sea, a realtor like Bob might not even exist to manage the Listings. Clients might instead consult the Rolodex &quot;Annie&quot; (<code>&amp;</code> for short) for the direct address of the house. Instead of reading off the referenced house details from the listing like Bob does, clients instead get the house address from Annie (<code>&amp;</code>), and go directly to 1234 Main St, sometimes w/no idea what they might find there.</p>\n<p>One day, Bob's firm begins offering a new automated service that needs the listing for a house the client is interested in.</p>\n<p>Well, the person with that info is Bob, so the client has Bob call up the service and send it a copy of the listing.</p>\n<p><code>jobKillingAutomatedListingService(Listing tinyHouseAt1234Main, int viewTally)</code> Bob sends along ...</p>\n<p>The service, on its end, calls this Listing <code>houseToLookAt</code>, but really what it receives is an exact copy of Bob's listing, with the exact same VALUEs in it, that refer to the house at 1234 Main St.</p>\n<p>This new service also has its own internal tally of how many people have viewed the listing. The service accepts Bob's tally out of professional courtesy, but it doesn't really care and overwrites it entirely with its own local copy anyway. It's tally for today is 1, while Bob's is still 43.</p>\n<p>The realty firms call this &quot;pass-by-value&quot; since Bob's passing the current value of his <code>viewTally</code> and his Listing <code>tinyHouseAt1234Main</code>. He's not actually passing along the entire physical house, because that's impractical. Nor is he passing the real physical address like Annie(<code>&amp;</code>) would do.</p>\n<p>But he IS passing a copy of <em>the value OF</em> the reference he has to the house. Seems like a silly pedantic difference in some ways, but that's how his firm works ...\n..............</p>\n<h2>PT II: Where things get confusing and dangerous ...</h2>\n<p>The new automated service, not being all functional and math-oriented like some other trendy financial &amp; scientific firms, can have unforeseen side effects...</p>\n<p>Once given a Listing object it allows clients to <em>actually</em> repaint the REAL house at 1234 Main St, using a remote drone robot fleet! It allows clients to control a robot bulldozer to ACTUALLY dig up the flower bed! This is madness!!!</p>\n<p>The service also lets clients completely redirect <code>houseToLookAt</code> to some other house at another address, without involving Bob or his listing. All of a sudden they could be looking at 4321 Elm St. instead, which has no connection whatsoever to Bob's listing (thankfully they can't do anymore damage).</p>\n<p>Bob watches all this on his realtime webcam.\nResigned to the drudgery of his sole job responsibility, he tells clients about the new ugly paint job &amp; sudden lack of curb appeal. His Listing <em>is</em> still for 1234 Main St., after all. The new service's <code>houseToLookAt</code> couldn't change that. Bob reports the details of his <code>tinyHouseAt1234Main</code> accurately and dutifully as always, until he gets fired or the house is destroyed entirely by The Nothing.</p>\n<p>Really the only thing the service CAN'T do with its <code>houseToLookAt</code> copy of the Bob's original listing is change the address from 1234 Main St. to some other address, or to a void of nothingness, or to some random type of object like a Platypus. Bob's Listing still always points to 1234 Main St, for whatever it's still worth. He passes its current value around like always.</p>\n<p>This bizarre side-effect of passing a listing to the new automated service is confusing for people who ask about how it works. Really, what's the difference between the ability to remotely control robots that alter the state of the house at 1234 Main, vs. <em>actually</em> physically going there and wreaking havoc because Annie gave you the address??</p>\n<p>Seems like kind of a nitpicky semantic argument if what you generally care about is the <em>state</em> of the house in the listing being copied and passed around, right?</p>\n<p>I mean, if you were in the business of actually picking up houses and physically moving them to other addresses (not like mobile or Tiny Homes where that's sort of an expected function of the platform), or you were accessing, renaming, and shuffling entire neighborhoods like some sort of low-level God-playing madman, THEN maybe you'd care more about passing around those specific address references instead of just copies of the the latest value of the house details ...</p>\n"}, {'answer_id': 49640653, 'author': 'Michael', 'author_id': 4109266, 'author_profile': 'https://Stackoverflow.com/users/4109266', 'pm_score': 5, 'selected': False, 'text': '<p>Unlike some other languages, Java does not allow you to choose between pass-by-value and pass-by-reference—all arguments are passed by value. A method call can pass two types of values to a method—copies of primitive values (e.g., values of int and double) and copies of references to objects.</p>\n\n<p>When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.</p>\n\n<p>When it comes to objects, objects themselves cannot be passed to methods. So we pass the reference(address) of the object. We can manipulate the original object using this reference.</p>\n\n<p><strong>How Java creates and stores objects:</strong> When we create an object we store the object’s address in a reference variable. Let\'s analyze the following statement.</p>\n\n<pre><code>Account account1 = new Account();\n</code></pre>\n\n<p>“Account account1” is the type and name of the reference variable, “=” is the assignment operator, “new” asks for the required amount of space from the system. The constructor to the right of keyword new which creates the object is called implicitly by the keyword new. Address of the created object(result of right value, which is an expression called "class instance creation expression") is assigned to the left value (which is a reference variable with a name and a type specified) using the assign operator.</p>\n\n<p>Although an object’s reference is passed by value, a method can still interact with the referenced object by calling its public methods using the copy of the object’s reference. Since the reference stored in the parameter is a copy of the reference that was passed as an argument, the parameter in the called method and the argument in the calling method refer to the same object in memory.</p>\n\n<p>Passing references to arrays, instead of the array objects themselves, makes sense for performance reasons. Because everything in Java is passed by value, if array objects were passed,\na copy of each element would be passed. For large arrays, this would waste time and consume\nconsiderable storage for the copies of the elements.</p>\n\n<p>In the image below you can see we have two reference variables(These are called pointers in C/C++, and I think that term makes it easier to understand this feature.) in the main method. Primitive and reference variables are kept in stack memory(left side in images below). array1 and array2 reference variables "point" (as C/C++ programmers call it) or reference to a and b arrays respectively, which are objects (values these reference variables hold are addresses of objects) in heap memory (right side in images below).</p>\n\n<p><a href="https://i.stack.imgur.com/sF7QZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sF7QZ.png" alt="Pass by value example 1"></a></p>\n\n<p>If we pass the value of array1 reference variable as an argument to the reverseArray method, a reference variable is created in the method and that reference variable starts pointing to the same array (a). </p>\n\n<pre><code>public class Test\n{\n    public static void reverseArray(int[] array1)\n    {\n        // ...\n    }\n\n    public static void main(String[] args)\n    {\n        int[] array1 = { 1, 10, -7 };\n        int[] array2 = { 5, -190, 0 };\n\n        reverseArray(array1);\n    }\n}\n</code></pre>\n\n<p><a href="https://i.stack.imgur.com/W1wgZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W1wgZ.png" alt="Pass by value example 2"></a></p>\n\n<p>So, if we say </p>\n\n<pre><code>array1[0] = 5;\n</code></pre>\n\n<p>in reverseArray method, it will make a change in array a.</p>\n\n<p>We have another reference variable in reverseArray method (array2) that points to an array c. If we were to say </p>\n\n<pre><code>array1 = array2;\n</code></pre>\n\n<p>in reverseArray method, then the reference variable array1 in method reverseArray would stop pointing to array a and start pointing to array c (Dotted line in second image).</p>\n\n<p>If we return value of reference variable array2 as the return value of method reverseArray and assign this value to reference variable array1 in main method, array1 in main will start pointing to array c.</p>\n\n<p>So let\'s write all the things we have done at once now.</p>\n\n<pre><code>public class Test\n{\n    public static int[] reverseArray(int[] array1)\n    {\n        int[] array2 = { -7, 0, -1 };\n\n        array1[0] = 5; // array a becomes 5, 10, -7\n\n        array1 = array2; /* array1 of reverseArray starts\n          pointing to c instead of a (not shown in image below) */\n        return array2;\n    }\n\n    public static void main(String[] args)\n    {\n        int[] array1 = { 1, 10, -7 };\n        int[] array2 = { 5, -190, 0 };\n\n        array1 = reverseArray(array1); /* array1 of \n         main starts pointing to c instead of a */\n    }\n}\n</code></pre>\n\n<p><a href="https://i.stack.imgur.com/5hRyX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5hRyX.png" alt="enter image description here"></a></p>\n\n<p>And now that reverseArray method is over, its reference variables(array1 and array2) are gone. Which means we now only have the two reference variables in main method array1 and array2 which point to c and b arrays respectively. No reference variable is pointing to object (array) a. So it is eligible for garbage collection.</p>\n\n<p>You could also assign value of array2 in main to array1. array1 would start pointing to b.</p>\n'}, {'answer_id': 50391764, 'author': 'asok', 'author_id': 5092157, 'author_profile': 'https://Stackoverflow.com/users/5092157', 'pm_score': 3, 'selected': False, 'text': '<p>Java is only passed by value. there is no pass by reference, for example, you can see the following example.</p>\n\n<pre><code>package com.asok.cop.example.task;\npublic class Example {\n    int data = 50;\n\n    void change(int data) {\n        data = data + 100;// changes will be in the local variable \n        System.out.println("after add " + data);\n        }\n\n    public static void main(String args[]) {\n        Example op = new Example();\n        System.out.println("before change " + op.data);\n        op.change(500);\n        System.out.println("after change " + op.data);\n    }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>before change 50\nafter add 600\nafter change 50\n</code></pre>\n\n<p>as Michael says in the comments:</p>\n\n<blockquote>\n  <p>objects are still passed by value even though operations on them behave like pass-by-reference. Consider <code>void changePerson(Person person){ person = new Person(); }</code> the callers reference to the person object will remain unchanged. Objects themselves are passed by value but their members can be affected by changes. To be true pass-by-reference, we would have to be able to reassign the argument to a new object and have the change be reflected in the caller.</p>\n</blockquote>\n'}, {'answer_id': 51522896, 'author': 'georgeawg', 'author_id': 5535245, 'author_profile': 'https://Stackoverflow.com/users/5535245', 'pm_score': 4, 'selected': False, 'text': '<h2>Java passes primitive types by value and class types by reference</h2>\n\n<p>Now, people like to bicker endlessly about whether "pass by reference" is the correct way to describe what Java et al. actually do. The point is this:</p>\n\n<ol>\n<li>Passing an object does not copy the object.</li>\n<li>An object passed to a function can have its members modified by the function.</li>\n<li>A primitive value passed to a function cannot be modified by the function. A copy is made.</li>\n</ol>\n\n<p>In my book that\'s called passing by reference.</p>\n\n<p>&#8212; <a href="https://www.quora.com/profile/Brian-Bi" rel="noreferrer">Brian Bi</a> - <a href="https://www.quora.com/Which-programming-languages-are-pass-by-reference#" rel="noreferrer">Which programming languages are pass by reference?</a></p>\n'}, {'answer_id': 54373107, 'author': 'Sanjeev', 'author_id': 1028560, 'author_profile': 'https://Stackoverflow.com/users/1028560', 'pm_score': 7, 'selected': False, 'text': '<p>There are already great answers that cover this. I wanted to make a small contribution by sharing a <strong>very simple example</strong> (which will compile) contrasting the behaviors between Pass-by-reference in c++ and Pass-by-value in Java.</p>\n<p>A few points:</p>\n<ol>\n<li>The term &quot;reference&quot; is a overloaded with two separate meanings. In Java it simply means a pointer, but in the context of &quot;Pass-by-reference&quot; it means a handle to the original variable which was passed in.</li>\n<li><strong>Java is Pass-by-value</strong>. Java is a descendent of C (among other languages). Before C, several (but not all) earlier languages like FORTRAN and COBOL supported PBR, but C did not. PBR allowed these other languages to make changes to the passed variables inside sub-routines. In order to accomplish the same thing (i.e. change the values of variables inside functions), C programmers passed pointers to variables into functions. Languages inspired by C, such as Java, borrowed this idea and continue to pass pointer to methods as C did, except that Java calls its pointers References. Again, this is a different use of the word &quot;Reference&quot; than in &quot;Pass-By-Reference&quot;.</li>\n<li><strong>C++ allows Pass-by-reference</strong> by declaring a reference parameter using the &quot;&amp;&quot; character (which happens to be the same character used to indicate &quot;the address of a variable&quot; in both C and C++). For example, if we pass in a pointer by reference, the parameter and the argument are not just pointing to the same object. Rather, they are the same variable. If one gets set to a different address or to null, so does the other.</li>\n<li>In the C++ example below I\'m passing a <strong>pointer</strong> to a null terminated string <strong>by reference</strong>. And in the Java example below I\'m passing a Java reference to a String (again, the same as a pointer to a String) by value. Notice the output in the comments.</li>\n</ol>\n<p>C++ pass by reference example:</p>\n<pre><code>using namespace std;\n#include &lt;iostream&gt;\n\nvoid change (char *&amp;str){   // the \'&amp;\' makes this a reference parameter\n    str = NULL;\n}\n\nint main()\n{\n    char *str = &quot;not Null&quot;;\n    change(str);\n    cout&lt;&lt;&quot;str is &quot; &lt;&lt; str;      // ==&gt;str is &lt;null&gt;\n}\n</code></pre>\n<p>Java pass &quot;a Java reference&quot; by value example</p>\n<pre><code>public class ValueDemo{\n    \n    public void change (String str){\n        str = null;\n    }\n\n     public static void main(String []args){\n        ValueDemo vd = new ValueDemo();\n        String str = &quot;not null&quot;;\n        vd.change(str);\n        System.out.println(&quot;str is &quot; + str);    // ==&gt; str is not null!!\n                                                // Note that if &quot;str&quot; was\n                                                // passed-by-reference, it\n                                                // WOULD BE NULL after the\n                                                // call to change().\n     }\n}\n</code></pre>\n<p><strong>EDIT</strong></p>\n<p>Several people have written comments which seem to indicate that either they are not looking at my examples or they don\'t get the c++ example. Not sure where the disconnect is, but guessing the c++ example is not clear. I\'m posting the same example in pascal because I think pass-by-reference looks cleaner in pascal, but I could be wrong. I might just be confusing people more; I hope not.</p>\n<p>In pascal, parameters passed-by-reference are called &quot;var parameters&quot;. In the procedure setToNil below, please note the keyword \'var\' which precedes the parameter \'ptr\'. When a pointer is passed to this procedure, it will be passed <strong>by reference</strong>. Note the behavior: when this procedure sets ptr to nil (that\'s pascal speak for NULL), it will set the argument to nil--you can\'t do that in Java.</p>\n<pre><code>program passByRefDemo;\ntype \n   iptr = ^integer;\nvar\n   ptr: iptr;\n   \n   procedure setToNil(var ptr : iptr);\n   begin\n       ptr := nil;\n   end;\n\nbegin\n   new(ptr);\n   ptr^ := 10;\n   setToNil(ptr);\n   if (ptr = nil) then\n       writeln(\'ptr seems to be nil\');     { ptr should be nil, so this line will run. }\nend.\n</code></pre>\n<p><strong>EDIT 2</strong></p>\n<p>Some excerpts from <strong>&quot;THE Java Programming Language&quot;</strong> by Ken Arnold, <strong>James Gosling (the guy who invented Java)</strong>, and David Holmes, chapter 2, section 2.6.5</p>\n<blockquote>\n<p><strong>All parameters to methods are passed &quot;by value&quot;</strong>. In other words,\nvalues of parameter variables in a method are copies of the invoker\nspecified as arguments.</p>\n</blockquote>\n<p>He goes on to make the same point regarding objects . . .</p>\n<blockquote>\n<p>You should note that when the parameter is an object reference, it is\nthe object reference-not the object itself-that is <strong>passed &quot;by value&quot;</strong>.</p>\n</blockquote>\n<p>And towards the end of the same section he makes a broader statement about java being only pass by value and never pass by reference.</p>\n<blockquote>\n<p>The Java programming language <strong>does not pass objects by reference; it</strong>\n<strong>passes object references by value</strong>. Because two copies of the same\nreference refer to the same actual object, changes made through one\nreference variable are visible through the other. There is exactly one\nparameter passing mode-<strong>pass by value</strong>-and that helps keep things\nsimple.</p>\n</blockquote>\n<p>This section of the book has a great explanation of parameter passing in Java and of the distinction between pass-by-reference and pass-by-value and it\'s by the creator of Java. I would encourage anyone to read it, especially if you\'re still not convinced.</p>\n<p>I think the difference between the two models is very subtle and unless you\'ve done programming where you actually used pass-by-reference, it\'s easy to miss where two models differ.</p>\n<p>I hope this settles the debate, but probably won\'t.</p>\n<p><strong>EDIT 3</strong></p>\n<p>I might be a little obsessed with this post. Probably because I feel that the makers of Java inadvertently spread misinformation. If instead of using the word &quot;reference&quot; for pointers they had used something else, say\ndingleberry, there would\'ve been no problem. You could say, &quot;Java passes dingleberries by value and not by reference&quot;, and nobody would be confused.</p>\n<p>That\'s the reason only Java developers have issue with this. They look at the word &quot;reference&quot; and think they know exactly what that means, so they don\'t even bother to consider the opposing argument.</p>\n<p>Anyway, I noticed a comment in an older post, which made a balloon analogy which I really liked. So much so that I decided to glue together some clip-art to make a set of cartoons to illustrate the point.</p>\n<p><strong>Passing a reference by value</strong>--Changes to the reference are not reflected in the caller\'s scope, but the changes to the object are. This is because the reference is copied, but the both the original and the copy refer to the same object.\n<a href="https://i.stack.imgur.com/RvkqU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RvkqU.png" alt="Passing Object references By Value" /></a></p>\n<p><strong>Pass by reference</strong>--There is no copy of the reference. Single reference is shared by both the caller and the function being called. Any changes to the reference or the Object\'s data are reflected in the caller\'s scope.\n<a href="https://i.stack.imgur.com/SHXkC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SHXkC.png" alt="Pass by reference" /></a></p>\n<p><strong>EDIT 4</strong></p>\n<p>I have seen posts on this topic which describe the low level implementation of parameter passing in Java, which I think is great and very helpful because it makes an abstract idea concrete. However, to me the question is more about <strong>the behavior described in the language specification</strong> than about the technical implementation of the behavior. This is an exerpt from the <a href="https://docs.oracle.com/javase/specs/jls/se19/html/jls-8.html#jls-8.4.1" rel="noreferrer">Java Language Specification, section 8.4.1</a> :</p>\n<blockquote>\n<p>When the method or constructor is invoked (§15.12), <strong>the values of the\nactual argument expressions initialize newly created parameter\nvariables, each of the declared type, before execution of the body of\nthe method or constructor.</strong> The Identifier that appears in the\nDeclaratorId may be used as a simple name in the body of the method or\nconstructor to refer to the formal parameter.</p>\n</blockquote>\n<p>Which means, java creates a copy of the passed parameters before executing a method. Like most people who studied compilers in college, I used <a href="https://rads.stackoverflow.com/amzn/click/com/0201100886" rel="noreferrer" rel="nofollow noreferrer">&quot;The Dragon Book&quot;</a> which is <strong>THE</strong> compilers book. It has a good description of &quot;Call-by-value&quot; and &quot;Call-by-Reference&quot; in Chapter 1. The Call-by-value description matches up with Java Specs exactly.</p>\n<p>Back when I studied compilers-in the 90\'s, I used the first edition of the book from 1986 which pre-dated Java by about 9 or 10 years. However, I just ran across a copy of the <a href="https://rads.stackoverflow.com/amzn/click/com/B009TGD06W" rel="noreferrer" rel="nofollow noreferrer">2nd Eddition</a> from 2007 <strong>which actually mentions Java!</strong> Section 1.6.6 labeled &quot;Parameter Passing Mechanisms&quot; describes parameter passing pretty nicely. Here is an excerpt under the heading &quot;Call-by-value&quot; which mentions Java:</p>\n<blockquote>\n<p>In call-by-value, the actual parameter is evaluated (if it is an\nexpression) or copied (if it is a variable). The value is placed in\nthe location belonging to the corresponding formal parameter of the\ncalled procedure. <strong>This method is used in C and Java, and is a common\noption in C++ , as well as in most other languages.</strong></p>\n</blockquote>\n'}, {'answer_id': 55923549, 'author': 'moldovean', 'author_id': 959876, 'author_profile': 'https://Stackoverflow.com/users/959876', 'pm_score': 4, 'selected': False, 'text': '<p>Long story short: </p>\n\n<ol>\n<li>Non-primitives: Java passes the <em>Value of the Reference</em>.  </li>\n<li>Primitives: just value. </li>\n</ol>\n\n<p>The End.</p>\n\n<p>(2) is too easy. Now if you want to think of what (1) implies, imagine you have a class Apple:</p>\n\n<pre><code>class Apple {\n    private double weight;\n    public Apple(double weight) {\n        this.weight = weight;\n    }\n    // getters and setters ...\n\n}\n</code></pre>\n\n<p>then when you pass an instance of this class to the main method:</p>\n\n<pre><code>class Main {\n    public static void main(String[] args) {\n        Apple apple = new Apple(3.14);\n        transmogrify(apple);\n        System.out.println(apple.getWeight()+ " the goose drank wine...";\n\n    }\n\n    private static void transmogrify(Apple apple) {\n        // does something with apple ...\n        apple.setWeight(apple.getWeight()+0.55);\n    }\n}\n</code></pre>\n\n<p>oh.. but you probably know that, you\'re interested in what happens when you do something like this:</p>\n\n<pre><code>class Main {\n    public static void main(String[] args) {\n        Apple apple = new Apple(3.14);\n        transmogrify(apple);\n        System.out.println("Who ate my: "+apple.getWeight()); // will it still be 3.14? \n\n    }\n\n    private static void transmogrify(Apple apple) {\n        // assign a new apple to the reference passed...\n        apple = new Apple(2.71);\n    }\n\n\n}\n</code></pre>\n'}, {'answer_id': 57068881, 'author': 'Amit Sharma', 'author_id': 9892438, 'author_profile': 'https://Stackoverflow.com/users/9892438', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Java passes parameters by value, There is no option of passing a reference in Java.</strong></p>\n\n<p>But at the complier binding level layer, It uses reference internally not exposed to the user.</p>\n\n<p>It is essential as it saves a lot of memory and improves speed.</p>\n'}, {'answer_id': 57229012, 'author': 'natwar kumar', 'author_id': 3957354, 'author_profile': 'https://Stackoverflow.com/users/3957354', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public class Test {\n\n    static class Dog {\n        String name;\n\n        @Override\n        public int hashCode() {\n            final int prime = 31;\n            int result = 1;\n            result = prime * result + ((name == null) ? 0 : name.hashCode());\n            return result;\n        }\n\n        @Override\n        public boolean equals(Object obj) {\n            if (this == obj)\n                return true;\n            if (obj == null)\n                return false;\n            if (getClass() != obj.getClass())\n                return false;\n            Dog other = (Dog) obj;\n            if (name == null) {\n                if (other.name != null)\n                    return false;\n            } else if (!name.equals(other.name))\n                return false;\n            return true;\n        }\n\n        public String getName() {\n            return name;\n        }\n\n        public void setName(String nb) {\n            this.name = nb;\n        }\n\n        Dog(String sd) {\n            this.name = sd;\n        }\n    }\n    /**\n     * \n     * @param args\n     */\n    public static void main(String[] args) {\n        Dog aDog = new Dog("Max");\n\n        // we pass the object to foo\n        foo(aDog);\n        Dog oldDog = aDog;\n\n        System.out.println(" 1: " + aDog.getName().equals("Max")); // false\n        System.out.println(" 2 " + aDog.getName().equals("huahua")); // false\n        System.out.println(" 3 " + aDog.getName().equals("moron")); // true\n        System.out.println(" 4 " + " " + (aDog == oldDog)); // true\n\n        // part2\n        Dog aDog1 = new Dog("Max");\n\n        foo(aDog1, 5);\n        Dog oldDog1 = aDog;\n\n        System.out.println(" 5 : " + aDog1.getName().equals("huahua")); // true\n        System.out.println(" part2 : " + (aDog1 == oldDog1)); // false\n\n        Dog oldDog2 = foo(aDog1, 5, 6);\n        System.out.println(" 6 " + (aDog1 == oldDog2)); // true\n        System.out.println(" 7 " + (aDog1 == oldDog)); // false\n        System.out.println(" 8 " + (aDog == oldDog2)); // false\n    }\n\n    /**\n     * \n     * @param d\n     */\n    public static void foo(Dog d) {\n        System.out.println(d.getName().equals("Max")); // true\n\n        d.setName("moron");\n\n        d = new Dog("huahua");\n        System.out.println(" -:-  " + d.getName().equals("huahua")); // true\n    }\n\n    /**\n     * \n     * @param d\n     * @param a\n     */\n    public static void foo(Dog d, int a) {\n        d.getName().equals("Max"); // true\n\n        d.setName("huahua");\n    }\n\n    /**\n     * \n     * @param d\n     * @param a\n     * @param b\n     * @return\n     */\n    public static Dog foo(Dog d, int a, int b) {\n        d.getName().equals("Max"); // true\n        d.setName("huahua");\n        return d;\n    }\n}\n</code></pre>\n\n<p>The sample code to demonstrate the impact of changes to the  object at different functions . </p>\n'}, {'answer_id': 57616177, 'author': 'grindlewald', 'author_id': 10240338, 'author_profile': 'https://Stackoverflow.com/users/10240338', 'pm_score': 3, 'selected': False, 'text': '<p>First let\'s understand Memory allocation in Java:\nStack and Heap are part of Memory that JVM allocates for different purposes. The stack memory is pre-allocated to thread, when it is created, therefore, a thread cannot access the Stack of other thread. But Heap is available to all threads in a program.</p>\n\n<p>For a thread, Stack stores all local data, metadata of program, primitive type data and object reference. And, Heap is responsible for storage of actual object.</p>\n\n<pre><code>Book book = new Book("Effective Java");\n</code></pre>\n\n<p>In the above example, the reference variable is "book" which is stored in stack. The instance created by new operator -> new Book("Effective Java") is stored in Heap. The ref variable "book" has address of the object allocated in Heap. Let\'s say the address is 1001.</p>\n\n<p><a href="https://i.stack.imgur.com/uw7tE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uw7tE.png" alt="enter image description here"></a></p>\n\n<p>Consider passing a primitive data type i.e. int, float, double etc.</p>\n\n<pre><code>public class PrimitiveTypeExample { \n    public static void main(string[] args) {\n       int num = 10;\n       System.out.println("Value before calling method: " + num);\n       printNum(num);\n       System.out.println("Value after calling method: " + num);\n    }\n    public static void printNum(int num){\n       num = num + 10;\n       System.out.println("Value inside printNum method: " + num);\n    }\n}\n</code></pre>\n\n<p>Output is:\nValue before calling method: 10\nValue inside printNum method: 20\nValue after calling method: 10</p>\n\n<p>int num =10; -> this allocates the memory for "int" in Stack of the running thread, because, it is a primitive type.  Now when printNum(..) is called, a private stack is created within the same thread. When "num" is passed to this method, a copy of "num" is created in the method stack frame.\nnum = num+10; -> this adds 10 and modifies the the int variable within the method stack frame.\nTherefore, the original num outside the method stack frame remains unchanged.</p>\n\n<p>Consider, the example of passing the object of a custom class as an argument.</p>\n\n<p><a href="https://i.stack.imgur.com/J1XRW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/J1XRW.png" alt="enter image description here"></a></p>\n\n<p>In the above example, ref variable "book" resides in stack of thread executing the program, and the object of class Book is created in Heap space when program executes new Book(). This memory location in Heap is referred by "book". When "book" is passed as method argument, a copy  of "book" is created in  private stack frame of method within the same stack of thread. Therefore, the copied reference variable points to the same object of class "Book" in the Heap.</p>\n\n<p><a href="https://i.stack.imgur.com/ggqd5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ggqd5.png" alt="enter image description here"></a></p>\n\n<p>The reference variable within method stack frame sets a new value to same object. Therefore, it is reflected when original ref variable "book" gets its value.\nNote that in case of passing reference variable, if it is initialized again in called method, it then points to new memory location and any operation does not affect the previous object in the Heap.</p>\n\n<p>Therefore, when anything is passed as method argument, it is always the Stack entity - either primitive or reference variable. We never pass something that is stored in Heap. Hence, in Java, we always pass the value in the stack, and it is pass by value.</p>\n'}, {'answer_id': 58038425, 'author': 'Rose', 'author_id': 11725130, 'author_profile': 'https://Stackoverflow.com/users/11725130', 'pm_score': 2, 'selected': False, 'text': '<p>I think this simple explanation might help you understand as I wanted to understand this same thing when I was struggling through this.</p>\n\n<p>When you pass a primitive data to a function call it\'s content is being copied to the function\'s argument and when you pass an object it\'s reference is being copied to the function\'s argument. Speaking of object, you can\'t change the copied reference-<em>the argument variable is referencing to</em> in the calling function.</p>\n\n<p>Consider this simple example, String is an object in java and when you change the content of a string the reference variable will now point to some new reference as String objects are immutable in java.</p>\n\n<pre class="lang-java prettyprint-override"><code>String name="Mehrose";  // name referencing to 100\n\nChangeContenet(String name){\n name="Michael"; // refernce has changed to 1001\n\n} \nSystem.out.print(name);  //displays Mehrose\n</code></pre>\n\n<p>Fairly simple because as I mentioned you are not allowed to change the copied reference in the calling function. But the problem is with the array when you pass an array of String/Object. Let us see.</p>\n\n<pre class="lang-java prettyprint-override"><code>String names[]={"Mehrose","Michael"};\n\nchangeContent(String[] names){\n  names[0]="Rose";\n  names[1]="Janet"\n\n}\n\nSystem.out.println(Arrays.toString(names)); //displays [Rose,Janet]\n</code></pre>\n\n<p>As we said that we can\'t change the copied reference in the function call and we also have seen in the case of a single String object. The reason is names[] variable referencing to let\'s say 200 and names[0] referencing to 205 and so on. You see we didn\'t change the names[] reference it still points to the old same reference still after the function call but now names[0] and names[1] reference has been changed. We Still stand on our definition that we can\'t change the reference variable\'s reference so we didn\'t.</p>\n\n<p>The same thing happens when you pass a Student object to a method and you are still able to change the Student name or other attributes, the point is we are not changing the actual Student object rather we are changing the contents of it</p>\n\n<p>You can\'t do this</p>\n\n<pre class="lang-java prettyprint-override"><code>Student student1= new Student("Mehrose");\n\nchangeContent(Student Obj){\n obj= new Student("Michael") //invalid\n obj.setName("Michael")  //valid\n\n}\n</code></pre>\n'}, {'answer_id': 58704042, 'author': 'DeC', 'author_id': 7888956, 'author_profile': 'https://Stackoverflow.com/users/7888956', 'pm_score': 3, 'selected': False, 'text': '<p>A: Java does manipulate objects by reference, and all object variables are references. However, Java doesn\'t pass method arguments by reference; it passes them by value.</p>\n\n<p>Take the badSwap() method for example:</p>\n\n<pre><code>public void badSwap(int var1, int var2)\n{\n  int temp = var1;\n  var1 = var2;\n  var2 = temp;\n}\n</code></pre>\n\n<p>When badSwap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well. Now, here is where it gets tricky:</p>\n\n<pre><code>public void tricky(Point arg1, Point arg2)\n{\n  arg1.x = 100;\n  arg1.y = 100;\n  Point temp = arg1;\n  arg1 = arg2;\n  arg2 = temp;\n}\npublic static void main(String [] args)\n{\n  Point pnt1 = new Point(0,0);\n  Point pnt2 = new Point(0,0);\n  System.out.println("X: " + pnt1.x + " Y: " +pnt1.y); \n  System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);\n  System.out.println(" ");\n  tricky(pnt1,pnt2);\n  System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); \n  System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);  \n}\n</code></pre>\n\n<p>If we execute this main() method, we see the following output:</p>\n\n<pre><code>X: 0 Y: 0\nX: 0 Y: 0\nX: 100 Y: 100\nX: 0 Y: 0\n</code></pre>\n\n<p>The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.</p>\n\n<p><a href="https://i.stack.imgur.com/wLEj7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wLEj7.png" alt="enter image description here"></a><br>\nFigure 1. After being passed to a method, an object will have at least two references</p>\n\n<p>Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail.The method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.</p>\n'}, {'answer_id': 60141523, 'author': 'Mr.Robot', 'author_id': 5486740, 'author_profile': 'https://Stackoverflow.com/users/5486740', 'pm_score': 4, 'selected': False, 'text': '<p>I see that all answers contain the same: pass by value. However, a recent Brian Goetz update on project Valhalla actually answers it differently:</p>\n<blockquote>\n<p>Indeed, it is a common “gotcha” question about whether Java objects are passed by value or by reference, and <strong>the answer is “neither”: object references are passed by value.</strong></p>\n</blockquote>\n<p>You can read more here: <a href="http://cr.openjdk.java.net/%7Ebriangoetz/valhalla/sov/02-object-model.html" rel="noreferrer">State of Valhalla. Section 2: Language Model</a></p>\n<p><strong>Edit:</strong> Brian Goetz is Java Language Architect, leading such projects as Project Valhalla and Project Amber.</p>\n<p><strong>Edit-2020-12-08</strong>: Updated <a href="https://github.com/openjdk/valhalla-docs/blob/main/site/design-notes/state-of-valhalla/02-object-model.md" rel="noreferrer">State of Valhalla</a></p>\n'}, {'answer_id': 64289407, 'author': 'Alexandr', 'author_id': 511804, 'author_profile': 'https://Stackoverflow.com/users/511804', 'pm_score': 2, 'selected': False, 'text': "<p>I'd say it in another way:</p>\n<p>In java references are passed (but not objects) and these references are passed-by-value  (the reference itself is copied and you have 2 references as a result and you have no control under the 1st reference in the method).</p>\n<p>Just saying: pass-by-value might be not clear enough for beginners. For instance in Python the same situation but there are articles, which describe that they call it <code>pass-by-reference</code>, only cause references are used.</p>\n"}, {'answer_id': 64409378, 'author': 'Duleepa Wickramasinghe', 'author_id': 6582191, 'author_profile': 'https://Stackoverflow.com/users/6582191', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Java always passes parameters by value.</strong>\n<br>All object references in Java are passed by value. This means that a copy of the value will be passed to a method. But the trick is that passing a copy of the value also changes the real value of the object.</p>\n<p>Please refer to the below example,</p>\n<pre><code>public class ObjectReferenceExample {\n\n    public static void main(String... doYourBest) {\n            Student student = new Student();\n            transformIntoHomer(student);\n            System.out.println(student.name);\n    }\n\n    static void transformIntoDuleepa(Student student) {\n            student.name = &quot;Duleepa&quot;;\n    }\n}\nclass Student {\n    String name;\n}\n</code></pre>\n<p>In this case, it will be Duleepa!\n<br>The reason is that Java object variables are simply references that point to real objects in the memory heap.\nTherefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.</p>\n'}, {'answer_id': 64946506, 'author': 'Pallav Khare', 'author_id': 11913248, 'author_profile': 'https://Stackoverflow.com/users/11913248', 'pm_score': 3, 'selected': False, 'text': "<p>Java is always pass by value, not pass by reference</p>\n<p>First of all, we need to understand what pass by value and pass by reference are.</p>\n<p><strong>Pass by value</strong> means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.</p>\n<p><strong>Pass by reference</strong> (also called pass by address) means that a copy of the address of the actual parameter is stored.</p>\n<p>Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:</p>\n<pre><code>public class PassByValue {\n    public static void main(String[] args) {\n        Test t = new Test();\n        t.name = &quot;initialvalue&quot;;\n        new PassByValue().changeValue(t);\n        System.out.println(t.name);\n    }\n    \n    public void changeValue(Test f) {\n        f.name = &quot;changevalue&quot;;\n    }\n}\n\nclass Test {\n    String name;\n}\n</code></pre>\n<p>The output of this program is:</p>\n<pre><code>changevalue\nLet's understand step by step:\n</code></pre>\n<p>Test t = new Test();\nAs we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .</p>\n<p>first illustration</p>\n<pre><code>new PassByValue().changeValue(t);\n</code></pre>\n<p>When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.</p>\n<p>second illustration</p>\n<p>If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.</p>\n<p>To understand this more clearly, consider the following example:</p>\n<pre><code>public class PassByValue {\n    public static void main(String[] args) {\n        Test t = new Test();\n        t.name = &quot;initialvalue&quot;;\n        new PassByValue().changeRefence(t);\n        System.out.println(t.name);\n    }\n    \n    public void changeRefence(Test f) {\n        f = null;\n    }\n}\n\nclass Test {\n    String name;\n}\n</code></pre>\n<p>Will this throw a NullPointerException? No, because it only passes a copy of the reference. In the case of passing by reference, it could have thrown a NullPointerException, as seen below:</p>\n<p>third illustration</p>\n<p>Hopefully this will help.</p>\n"}, {'answer_id': 65460603, 'author': 'jack', 'author_id': 8932910, 'author_profile': 'https://Stackoverflow.com/users/8932910', 'pm_score': 4, 'selected': False, 'text': "<p>Not to repeat, but one point to those who might still be confused after reading many answers:</p>\n<ul>\n<li><code>pass by value</code> in Java is <strong>NOT EQUAL</strong> to <code>pass by value</code> in C++, though it sounds like that, which is probably why there's confusion</li>\n</ul>\n<p>Breaking it down:</p>\n<ul>\n<li><code>pass by value</code> in C++ means passing the value of the object (if object), literarily the copy of the object</li>\n<li><code>pass by value</code> in Java means passing the address value of the object (if object), not really the &quot;value&quot; (a copy) of the object like C++</li>\n<li>By <code>pass by value</code> in Java, operating on an object (e.g. <code>myObj.setName(&quot;new&quot;)</code>) inside a function <strong>has effects</strong> on the object outside the function; by <code>pass by value</code> in C++, it has <strong>NO</strong> effects on the one outside.</li>\n<li>However, by <code>pass by reference</code> in C++, operating on an object in a function <strong>DOES</strong> have effects on the one outside! Similar (<em>just similar, not the same</em>) to <code>pass by value</code> in Java, no?.. and people always repeat &quot;<em>there's no pass by reference in Java</em>&quot;, =&gt; <strong>BOOM, confusion starts...</strong></li>\n</ul>\n<p>So, friends, all is just about the <strong>difference</strong> of terminology definition (across languages), you just need to know how it works and that's it (<em>though sometimes a bit confusing how it's called I admit</em>)!</p>\n"}, {'answer_id': 66506089, 'author': 'ömer.bozkurt', 'author_id': 5003351, 'author_profile': 'https://Stackoverflow.com/users/5003351', 'pm_score': 0, 'selected': False, 'text': '<p>If you want it to put into a single sentence to understand and remember easily, simplest answer:</p>\n<p>Java is always <strong>pass the value with a new reference</strong></p>\n<p>(So you can modify the original object but can not access the original reference)</p>\n'}, {'answer_id': 66523582, 'author': 'charles', 'author_id': 4086871, 'author_profile': 'https://Stackoverflow.com/users/4086871', 'pm_score': 2, 'selected': False, 'text': '<p>Here a more precise definition:</p>\n<ul>\n<li><strong>Pass/call by value:</strong> Formal parameter is like a local variable in\nscope of function, it evaluates to actual parameter at the moment of\nfunction call.</li>\n<li><strong>Pass/call by reference:</strong> Formal parameter is just a alias for the real\nvalue, any change of it in the scope of function can have side\neffects outside in any other part of code.</li>\n</ul>\n<p>So in C/C++ you can create a function that swaps two values passed using the references:</p>\n<pre><code>void swap(int&amp; a, int&amp; b) \n{\n    int tmp = a; \n    a = b; \n    b = tmp; \n}\n</code></pre>\n<p>You can see it has a unique reference to a and b, so we do not have a copy, tmp just hold unique references.</p>\n<p>The same function in java does not have side effects, the parameter passing is just like the code above without references.</p>\n<p>Although java work with pointers/references, the parameters are not unique pointers, in each attribution, they are copied instead just assigned like C/C++</p>\n'}, {'answer_id': 66649532, 'author': 'Alex de Kruijff', 'author_id': 12486085, 'author_profile': 'https://Stackoverflow.com/users/12486085', 'pm_score': 1, 'selected': False, 'text': '<p>There are only two versions:</p>\n<ul>\n<li>You can pass the value i.e. (4,5)</li>\n<li>You can pass an address i.e. 0xF43A</li>\n</ul>\n<p>Java passes primivates as values and objects as addresses. Those who say, &quot;address are values too&quot;, do not make a distinction between the two. Those who focus on the effect of the swap functions focus on what happens after the passing is done.</p>\n<p>In C++ you can do the following:</p>\n<pre><code>Point p = Point(4,5);\n</code></pre>\n<p>This reserves 8 bytes on the stack and stores (4,5) in it.</p>\n<pre><code>Point *x = &amp;p;\n</code></pre>\n<p>This reserves 4 bytes on the stack and stores 0xF43A in it.</p>\n<pre><code>Point &amp;y = p;\n</code></pre>\n<p>This reserves 4 bytes on the stack and stores 0xF43A in it.</p>\n<ol>\n<li><p>I think everyone will agree that a call to f(p) is a pass-by-value if the definition of f is f(Point p). In this case an additional 8 bytes being reserved and (4,5) being copied into it. When f changes p the the the original is guarantieed to be unchanged when f returns.</p>\n</li>\n<li><p>I think that everyone will agree that a call to f(p) is a pass-by-reference if the definition of f is f(Point &amp;p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes p the the original is guarantieed to be changed when f returns.</p>\n</li>\n<li><p>A call to f(&amp;p) is also pass-by-reference if the definition of f is f(Point *p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes *p the the original is guarantieed to be changed when f returns.</p>\n</li>\n<li><p>A call to f(x) is also pass-by-reference if the definition of f is f(Point *p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes *p the the original is guarantieed to be changed when f returns.</p>\n</li>\n<li><p>A call to f(y) is also pass-by-reference if the definition of f is f(Point &amp;p). In this case an additional 4 bytes being reserved and 0xF43A being copied into it. When f changes p the the original is guarantieed to be changed when f returns.</p>\n</li>\n</ol>\n<p>Sure what happens after the passing is done differs, but that is only a language construct. In the case of pointer you have to use -&gt; to access the members and in the case of references you have to use .. If you want to swap the values of the original then you can do tmp=a; a=b; b=tmp; in the case of references and tmp=*a; *b=tmp; *a=tmp for pointers. And in Java you would have do: tmp.set(a); a.set(b); b.set(tmp). Focussing on the assignment statement statement is silly. You can do the exact same thing in Java if you write a little bit of code.</p>\n<p>So Java passes primivates by values and objects by references. And Java copy values to achieve that, but so does C++.</p>\n<p>For completeness:</p>\n<pre><code>Point p = new Point(4,5);\n</code></pre>\n<p>This reserves 4 bytes on the stack and stores 0xF43A in it and reserves 8 bytes on the heap and stores (4,5) in it.</p>\n<p>If you want to swap the memory locations like so</p>\n<pre><code>void swap(int&amp; a, int&amp; b) {\n    int *tmp = &amp;a;\n    &amp;a = &amp;b;\n    &amp;b = tmp;\n}\n</code></pre>\n<p>Then you will find that you run into the limitations of your hardware.</p>\n'}, {'answer_id': 67232841, 'author': 'v010dya', 'author_id': 2893496, 'author_profile': 'https://Stackoverflow.com/users/2893496', 'pm_score': -1, 'selected': False, 'text': '<p>Every single answer here is tying to take pass pointer by reference from other languages and show how it is impossible to do in Java. For whatever reason nobody is attempting to show how to implement pass-object-by-value from other languages.</p>\n<p>This code shows how something like this can be done:</p>\n<pre><code>public class Test\n{\n    private static void needValue(SomeObject so) throws CloneNotSupportedException\n    {\n        SomeObject internalObject = so.clone();\n        so=null;\n        \n        // now we can edit internalObject safely.\n        internalObject.set(999);\n    }\n    public static void main(String[] args)\n    {\n        SomeObject o = new SomeObject(5);\n        System.out.println(o);\n        try\n        {\n            needValue(o);\n        }\n        catch(CloneNotSupportedException e)\n        {\n            System.out.println(&quot;Apparently we cannot clone this&quot;);\n        }\n        System.out.println(o);\n    }\n}\n\npublic class SomeObject implements Cloneable\n{\n    private int val;\n    public SomeObject(int val)\n    {\n        this.val = val;\n    }\n    public void set(int val)\n    {\n        this.val = val;\n    }\n    public SomeObject clone()\n    {\n        return new SomeObject(val);\n    }\n    public String toString()\n    {\n        return Integer.toString(val);\n    }\n}\n</code></pre>\n<p>Here we have a function <code>needValue</code> and what it does is right away create a clone of the object, which needs be implemented in the class of the object itself and the class needs to be marked as <code>Cloneable</code>. It is not essential to set <code>so</code> to <code>null</code> after that, but i have done so here to show that we are not going to be using that reference after that.</p>\n<p>It may well be that Java does not have pass-by-reference semantics, but to call the language &quot;pass-by-value&quot; is along the lines of wishful thinking.</p>\n'}, {'answer_id': 67294696, 'author': 'frostcs', 'author_id': 1027385, 'author_profile': 'https://Stackoverflow.com/users/1027385', 'pm_score': 3, 'selected': False, 'text': '<p><strong>For simplicity and verbosity</strong>\nIts <code>pass reference by value</code>:</p>\n<pre><code>public static void main(String[] args) {\n    Dog aDog = new Dog(&quot;Max&quot;);\n    Dog oldDog = aDog;\n\n    // we pass the object to foo\n    foo(aDog);\n    // aDog variable is still pointing to the &quot;Max&quot; dog when foo(...) returns\n    aDog.getName().equals(&quot;Max&quot;); // true\n    aDog.getName().equals(&quot;Fifi&quot;); // false\n    aDog == oldDog; // true\n}\n\npublic static void foo(Dog d) {\n    d.getName().equals(&quot;Max&quot;); // true\n    // change d inside of foo() to point to a new Dog instance &quot;Fifi&quot;\n    d = new Dog(&quot;Fifi&quot;);\n    d.getName().equals(&quot;Fifi&quot;); // true\n}\n</code></pre>\n'}, {'answer_id': 68760297, 'author': 'Wellington Costa', 'author_id': 8576876, 'author_profile': 'https://Stackoverflow.com/users/8576876', 'pm_score': 2, 'selected': False, 'text': "<p>Java uses pass-by-value, but the effects differ whether you are using primitive or a reference type.</p>\n<p>When you pass a primitive type as an argument to a method, it's getting a copy of the primitive and any changes inside the block of the method won't change the original variable.</p>\n<p>When you pass a reference type as an argument to a method, it's still getting a copy but it's a copy of the reference to the object <strong>(in other words, you are getting a copy of the memory address in the heap where the object is located)</strong>, so any changes in the object inside the block of the method will affect the original object outside the block.</p>\n"}, {'answer_id': 69063599, 'author': 'Sam Ginrich', 'author_id': 9437799, 'author_profile': 'https://Stackoverflow.com/users/9437799', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Guess, the common canon is wrong based on inaccurate language</strong></p>\n<p>Authors of a programming language do not have the authority to rename established programming concept.</p>\n<p>Primitive Java types <code>byte, char, short, int, long float, double</code> are definitely passed by value.</p>\n<p>All other types are <code>Objects</code>: Object members and parameters technically <strong>are  references</strong>.</p>\n<p>So these &quot;references&quot; are passed &quot;by value&quot;, but there occurs no object construction on the stack. Any change of object members (or elements in case of an array) apply to the same original Object; such reference precisely meets the logic of pointer of an instance passed to some function in any C-dialect, where we used to call this <strong>passing an object by reference</strong></p>\n<p>Especially we do have this thing <strong>java.lang.NullPointerException</strong>, which makes no sense in a pure by-value-concept</p>\n'}, {'answer_id': 70586240, 'author': 'Sam Ginrich', 'author_id': 9437799, 'author_profile': 'https://Stackoverflow.com/users/9437799', 'pm_score': -1, 'selected': False, 'text': "<p>After following an exhaustive discussion, I think it's time to put all serious results together in a snippet.</p>\n<pre><code>/**\n * \n * @author Sam Ginrich\n * \n * All Rights Reserved!\n * \n */\npublic class JavaIsPassByValue\n{\n\n    static class SomeClass\n    {\n        int someValue;\n\n        public SomeClass(int someValue)\n        {\n            this.someValue = someValue;\n        }\n    }\n\n    static void passReferenceByValue(SomeClass someObject)\n    {\n        if (someObject == null)\n        {\n            throw new NullPointerException(\n                    &quot;This Object Reference was passed by Value,\\r\\n   that's why you don't get a value from it.&quot;);\n        }\n        someObject.someValue = 49;\n    }\n\n    public static void main(String[] args)\n    {\n        SomeClass someObject = new SomeClass(27);\n        System.out.println(&quot;Here is the original value: &quot; + someObject.someValue);\n\n        passReferenceByValue(someObject);\n        System.out.println(\n                &quot;\\nAs ´Java is pass by value´,\\r\\n   everything without exception is passed by value\\r\\n   and so an object's attribute cannot change: &quot;\n                    + someObject.someValue);\n\n        System.out.println();\n        passReferenceByValue(null);\n    }\n</code></pre>\n<p>}</p>\n<p>One can easily see from the output, that in Java everything is passed by value, so simple!</p>\n<pre><code>Here is the original value: 27\n\nAs ´Java is pass by value´,\n   everything without exception is passed by value\n   and so an object´s attribute cannot change: 49\n\n'Exception in thread &quot;main&quot; java.lang.NullPointerException: This Object Reference was passed by value,\n   that´s why you don´t get a value from it. \n    at JavaIsPassByValue.passReferenceByValue(JavaIsPassByValue.java:26)\n    at JavaIsPassByValue.main(JavaIsPassByValue.java:43)\n</code></pre>\n"}, {'answer_id': 70791100, 'author': 'Alexander Kalinowski', 'author_id': 17676158, 'author_profile': 'https://Stackoverflow.com/users/17676158', 'pm_score': -1, 'selected': False, 'text': '<p><strong>&quot;I am a Junior Java Developer and I would like to know if Java uses Call-by-Value or Call-by-Reference?&quot;</strong></p>\n<p>There is no universal answer to that and there cannot be for it\'s a <strong>false dichotomy</strong>. We have 2 different terms (Call-by-Value/Call-by-Reference) but at least 3(!) different ways of handling said data when passing it to a method:</p>\n<ol>\n<li>Our data is copied and the copy fed to a method. Changes to the copy do not propagate outside.(Think an <code>int</code> in Java or C++ or C#.)</li>\n<li>A pointer (the memory address) of our data is fed to the method instead. Changes to our data do propagate outside. We can also point to some new instance, leaving our original data dangling. (Think pointers in C++.)</li>\n<li>Like #2, except we can only change the original data but not what our pointer is pointing too. (Think instances passed as parameters in Java.)</li>\n</ol>\n<p>It\'s uncontentious in the OO world that #1 is <em>Call-by-Value</em> and #2 is <em>Call-by-Reference</em>.\nHowever, since we have only two terms for three options, there is no clear delineation between the two terms, thanks to option #3.</p>\n<p><strong>&quot;What does that mean for me?&quot;</strong></p>\n<p>It means that within the Java sphere you may reasonably assume #3 to be assumed under Call-by-Value (or the more verbal gymnastics term, Call-References-by-Value).</p>\n<p>However, in the wider OO world, it means you have to ask for an <em>explicit</em> delineation between Call-by-Value and Call-by-Reference, specifically how the other party classifies #3.</p>\n<p><strong>&quot;But I read that the JLS defines it as Call-by-Value!&quot;</strong></p>\n<p>Which is why your initial assumption when dealing with Java developers should be the above. The JLS has much less authority outside of Java, however.</p>\n<p><strong>&quot;Why would Java developers insist on their own terminology?&quot;</strong></p>\n<p>It\'s not for me to speculate but I think it\'s fair to point out that there is some potential problems with #2 (what is clearly Call-by-Reference), as hinted at, leading to Call-by-Reference not having the best of reputation everywhere.</p>\n<p><strong>&quot;Is there a solution to this mess?&quot;</strong></p>\n<p>3 options, only 2 ubiquitous names. The obvious exit is a 3rd term that gains equal wide-spread use as Call-by-Value and Call-by-Reference (and which is less confusing than Call-References-by-Value, perhaps <a href="https://www.sciencedirect.com/topics/computer-science/call-by-reference" rel="nofollow noreferrer">Call-by-Sharing</a>). Until then you need to presume or <strong>ask</strong>, as outlined above.</p>\n<p><em>Ultimately, it does not matter what we call it, for as long as we understand each other and there is no confusion.</em></p>\n'}, {'answer_id': 73769927, 'author': 'ADITYA AHLAWAT', 'author_id': 15142774, 'author_profile': 'https://Stackoverflow.com/users/15142774', 'pm_score': -1, 'selected': False, 'text': '<p><strong>Is Java a pass-by-value or reference? Prove it.</strong></p>\n<p>Java strictly enforces pass-by-value. Passing the parameters by using pass-by-values does not affect/alter the original variable. In the following program, we have initialized a variable called \'x\' with some value and used the pass-by-value technique to demonstrate how the value of the variable remains unchanged.</p>\n<p><strong>Code:</strong></p>\n<pre><code>public class Main \n{    \n   public static void main(String[] args)\n   { \n       //Original value of \'x\' will remain unchanged \n       // in case of call-by-value \n   \n       int x = 5;\n       System.out.println( &quot;Value of x before call-by-value: &quot; + x);\n       // 5\n\n       processData(x);\n       System.out.println(&quot;Value of x after call-by-value: &quot; + x);\n       // 5\n   }\n   public static void processData(int x) \n   { \n       x=x+10;          \n   }\n}\n</code></pre>\n<p>Now coming to the meaning - the value of x did not change in the main function - this is called pass by value.</p>\n<p>If the value changes in the main function it is called pass by reference.</p>\n<p><a href="https://pediaa.com/what-is-the-difference-between-pass-by-value-and-pass-by-reference/" rel="nofollow noreferrer">difference between pass by value and pass by reference</a></p>\n<p><strong>What is Pass by Value?</strong></p>\n<p>In pass by value, the value of a function parameter is copied to another location of the memory. When accessing or modifying the variable within the function, it accesses only the copy. Thus, there is no effect on the original value.</p>\n<p><strong>What is Pass by Reference?</strong></p>\n<p>In pass by reference, the memory address is passed to that function. In other words, the function gets access to the actual variable.</p>\n<p>Difference Between Pass by Value and Pass by Reference</p>\n<p><strong>Definition</strong></p>\n<p>Pass by value refers to a mechanism of copying the function parameter value to another variable while the pass by reference refers to a mechanism of passing the actual parameters to the function. Thus, this is the main difference between pass by value and pass by reference.</p>\n<p><strong>Changes</strong></p>\n<p>In pass by value, the changes made inside the function are not reflected in the original value. On the other hand, in pass by reference, the changes made inside the function are reflected in the original value. Hence, this is another difference between pass by value and pass by reference.</p>\n<p><strong>Actual Parameter</strong></p>\n<p>Moreover, pass by value makes a copy of the actual parameter. However, in pass by reference, the address of the actual parameter passes to the function.</p>\n'}]
['https://Stackoverflow.com/questions/40480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4315/']