Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Java's parameter passing is quite tricky - When an object is passed to a function, you can manipulate the object's fields but you cannot manipulate object itself. The object reference is passed by value. So, you can say:</p> <pre><code>class someClass{ int i = 5; } class Foo { static void func(someClass c) { c.i = 3; } } class MainClass{ public static void main(){ someClass c = new someClass(); System.out.println(c.i); Foo.func(c); System.out.println(c.i); } } </code></pre> <p>Expect your output to be:</p> <pre><code>5 3 </code></pre> <p>Changes to the fields of c persist.</p> <p>but if manipulate the object itself, this manipulation will only persist in <code>Foo.func()</code> and not outside that function:</p> <pre><code>class someClass{ int i = 5; } class Foo { static void func(someClass c) { c.i = new someClass(); c.i = 3; System.out.println(c.i); } } class MainClass{ public static void main(){ someClass c = new someClass(); System.out.println(c.i); Foo.func(c); System.out.println(c.i); } } </code></pre> <p>Expect your output to be:</p> <pre><code>5 3 5 </code></pre> <p>What has happened? c.i has the value 5 in <code>MainClass.main()</code> in <code>Foo.func()</code>, c itself is modified to point to another instance of <code>someClass</code>, containing the value 3. However, this change is not reflected to the actual object that has been passed. The <code>c</code> in <code>Foo.func()</code> and <code>MainClass.main()</code> are different objects now. That's why changes to the <code>c</code> of <code>Foo.func()</code> do not affect the <code>c</code> in <code>MainClass.main()</code>.</p>
    singulars
    1. This table or related slice is empty.
    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. 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