Skip to main content

Registration is now open for this year's LibreFest! Join us virtually the week of July 13.

Register here
Engineering LibreTexts

3.5: Passing a Value and Passing a Reference

  • Page ID
    15073
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)

    The effect of passing arguments to a method differs depending on whether you are passing a value of primitive type (such as 5 or true) or a value of reference type (such as “Hello” or game1). When an argument of primitive type is passed to a method, a copy of the argument is passed to the formal parameter. For example, consider the class shown in Figure 3.7. Note that we have an int variable k, which initially stores the value 5, and a method myMethod(), which takes an int parameter n. In this case, when we invoke myMethod(k), k’s value (5) is copied into n and stored there during the method.

    public class PrimitiveCall
    {
       public static void myMethod(int n)
       {   System.out.println("myMethod: n= " + n);
           n = 100;
           System.out.println("myMethod: n= " + n);
       } // myMethod()
    
       public static void main(String argv[])
       {   int k = 5;
           System.out.println("main: k= " + k);
           myMethod(k);
           System.out.println("main: k= " + k);
       } // main()
    } // PrimitiveCall

    Figure 3.7: Passing a primitive value to a method.

    One implication of passing a copy of a primitive value to a method is that the original value of k in main() cannot be altered from inside the method. Thus, the output generated by PrimitiveCall would be

      main: k= 5
      myMethod: n= 5
      myMethod: n= 100
      main: k= 5

    Note that in main(), k’s value is printed both before and after myMethod() is called, but that its value remains unaffected even though n’s value is changed within the method. This is because myMethod() contains just a copy of k’s value, not k itself. Any changes to the copy within myMethod() leave k unaltered (See Fig. 3.8).

    clipboard_ef05a2a06f68f319bceffe33c742d7e04.png

    Figure 3.8: Tracing the state of variables k and n in PrimitiveCall (a) Just before calling myMethod(k) in main. (b) Just before executing the body of myMethod(). (c) Just after executing the body of myMethod(). (d) After flow of control returns to main().

    JAVA LANGUAGE RULE

    Passing a Primitive Value. When a value of a primitive type, like boolean or int, is passed to a method, a copy of the value is passed. That’s why its original value remains unchanged outside the method, even if the copy is changed inside the method.

    In contrast to this, when an argument of a reference type is passed to a method, a copy of the reference to the object itself is assigned to the parameter. For example, in the case of a String parameter or a OneRowNim parameter, the method would be given a reference to the object–that is, the address of the object. The object itself is not passed, because it would be too inefficient to copy the entire object with all its data and methods. However, because the object’s reference gives the object’s location in memory, the method will have access to the object and can make changes to the original object from within the method.

    For example, consider the ReferenceCall class (Fig. 3.9). In this case, myMethod() takes a parameter g of type OneRowNim.

    public class ReferenceCall
    {
        public static void myMethod(OneRowNim g)
        {   System.out.print("myMethod: Number of sticks: ");
            System.out.println(g.getSticks());
            g.takeSticks(3);
            System.out.print("myMethod: Number of sticks: ");
            System.out.println(g.getSticks());
        } // myMethod()
    
        public static void main(String argv[])
        {   OneRowNim game = new OneRowNim(10);
             System.out.print("main: Number of sticks: ");
             System.out.println(game.getSticks());
             myMethod(game);
             System.out.print("main: Number of sticks: ");
             System.out.println(game.getSticks());
        }// main()
    } // ReferenceCall

    Figure 3.9: Passing a reference value to a method.

    Because a instance is an object, g is a reference variable. So when myMethod(game) is invoked in main(), a reference to game is passed to myMethod(). Note that in myMethod(), we use takeSticks(3) to change the number of sticks of g from 10 to 7 and that this change persists even after the method returns control to main(). The reason is that during the method’s execution, both game and g refer to the exact same object (see Fig. 3.10).

    clipboard_e331543b34ef33d4869f2ff6b73dde4ad.png

    Figure 3.10: Tracing the state of OneRowNim object in ReferenceCall (a) Just before calling myMethod(game). (b) Just before executing the body of myMethod(). (c) Just after executing the body of myMethod(). (d) After flow of control returns to main().

    The output generated by ReferenceCall would be

      main: Number of sticks: 10
      myMethod: Number of sticks: 10
      myMethod: Number of sticks: 7
      main: Number of sticks: 7

    This illustrates that when passing a reference variable to a method, it is possible for the method to change the state of the object associated with the reference variable. In subsequent chapters we will see ways to make use of this feature of reference parameters.

    JAVA LANGUAGE RULE

    Passing a Reference. When a reference to an object is passed to a method, any changes made to the object from within the method will persist when the method is finished executing.

    JAVA DEBUGGING TIP

    Side Effects. An unintended change to an object is called a side effect. Care should be taken in designing methods that the method does not produce unwanted side effects in objects passed as reference parameters.

     


    This page titled 3.5: Passing a Value and Passing a Reference is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform.