Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You have several choices. The one that makes the most sense really depends on what you're trying to do.</p> <p><strong>Choice 1: make toyNumber a public member variable in a class</strong></p> <pre><code>class MyToy { public int toyNumber; } </code></pre> <p>then pass a reference to a MyToy to your method.</p> <pre><code>void play(MyToy toy){ System.out.println("Toy number in play " + toy.toyNumber); toy.toyNumber++; System.out.println("Toy number in play after increement " + toy.toyNumber); } </code></pre> <p><strong>Choice 2: return the value instead of pass by reference</strong></p> <pre><code>int play(int toyNumber){ System.out.println("Toy number in play " + toyNumber); toyNumber++; System.out.println("Toy number in play after increement " + toyNumber); return toyNumber } </code></pre> <p>This choice would require a small change to the callsite in main so that it reads, <code>toyNumber = temp.play(toyNumber);</code>.</p> <p><strong>Choice 3: make it a class or static variable</strong></p> <p>If the two functions are methods on the same class or class instance, you could convert toyNumber into a class member variable.</p> <p><strong>Choice 4: Create a single element array of type int and pass that</strong></p> <p>This is considered a hack, but is sometimes employed to return values from inline class invocations.</p> <pre><code>void play(int [] toyNumber){ System.out.println("Toy number in play " + toyNumber[0]); toyNumber[0]++; System.out.println("Toy number in play after increement " + toyNumber[0]); } </code></pre>
    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. 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