Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Java is always <strong>pass-by-value</strong>. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the <em>reference</em> to it. This is confusing to beginners.</p> <p>It goes like this:</p> <pre><code>public static void main(String[] args) { Dog aDog = new Dog("Max"); // we pass the object to foo foo(aDog); // aDog variable is still pointing to the "Max" dog when foo(...) returns aDog.getName().equals("Max"); // true aDog.getName().equals("Fifi"); // false } public static void foo(Dog d) { d.getName().equals("Max"); // true // change d inside of foo() to point to a new Dog instance "Fifi" d = new Dog("Fifi"); d.getName().equals("Fifi"); // true } </code></pre> <p>In the example above <code>aDog.getName()</code> will still return <code>"Max"</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>"Fifi"</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>"Fifi"</code> after the call to <code>foo</code>.</p> <p>Likewise:</p> <pre><code>public static void main(String[] args) { Dog aDog = new Dog("Max"); foo(aDog); // when foo(...) returns, the name of the dog has been changed to "Fifi" aDog.getName().equals("Fifi"); // true } public static void foo(Dog d) { d.getName().equals("Max"); // true // this changes the name of d to be "Fifi" d.setName("Fifi"); } </code></pre> <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> itself (except when <code>d</code> is changed to point to a different <code>Dog</code> instance like <code>d = new Dog("Boxer")</code>).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload