Skip to main content
Engineering LibreTexts

2.7: Java Program for Call by Value and Reference

  • Page ID
  • To better explain the concept of call by value and call by reference, the following Java program is used.

    public class CallingConventions {
               public static void func(int a, final int b[])
                a = 7;
                b[0] = 7; 
               public static void main(String... argv) {
                   int a = 5;
                   int b[] = {5};
                   System.out.println("Before call, a = " + a + " and b[0] = " + b[0]);
                   func(a, b);
                   System.out.println("After call, a = " + a + " and b[0] = " + b[0]);

    Note that when this program is run, the value of a is not changed by the function, but the value of b[0] is changed. What is happening is very much analogous to the previously presented MIPS program which prompted for a string. In this case the variable a is a value type, e.g. the variable stores the value. In the case of the variable b, the values are stored in an array, and those values cannot be stored in a single data value (or register). So what is stored in b is the a reference to the array, or simply the address of b in memory. Thus b is a reference type.

    Note that in both cases when calling the function something is essentially copied into a memory location (in our MIPS program registers). But if the value is copied, it cannot be changed. If the reference is copied, while the reference cannot be changed, the value which is referred to can.

    This will become very important when discussing subprograms and arrays later in the text.

    7 C++ uses null terminated strings, but can also define strings as instances of the String class. Instances of the String class are very different from null terminated strings, so do not confuse the two.

    • Was this article helpful?