What is a variable that receives an argument that is passed into a method?

Dave Braunschweig

Overview

A parameter is a special kind of variable used in a function to refer to one of the pieces of data provided as input to the function. These pieces of data are the values of the arguments with which the function is going to be called/invoked. An ordered list of parameters is usually included in the definition of a function, so that, each time the function is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.

Discussion

Recall that the modular programming approach separates the functionality of a program into independent modules. To separate the functionality of one function from another, each function is given its own unique input variables, called parameters. The parameter values, called arguments, are passed to the function when the function is called. Consider the following function pseudocode:

Function CalculateCelsius (Real fahrenheit)
    Declare Real celsius
    
    Assign celsius = (fahrenheit - 32) * 5 / 9
Return Real celsius

If the CalculateCelsius function is called passing in the value 100, as in CalculateCelsius(100), the parameter is fahrenheit and the argument is 100. The terms parameter and argument are often used interchangeably. However, parameter refers to the variable identifier (fahrenheit) while argument refers to the variable value (100).

Functions may have no parameters or multiple parameters. Consider the following function pseudocode:

Function DisplayResult (Real fahrenheit, Real celsius)
    Output fahrenheit & "° Fahrenheit is " & celsius & "° Celsius"
End

If the DisplayResult function is called passing in the values 98.6 and 37.0, as in DisplayResults(98.6, 37.0), the argument or value for the fahrenheit parameter is 98.6 and the argument or value for the celsius parameter is 37.0. Note that the arguments are passed positionally. Calling DisplayResults(37.0, 98.6)would result in incorrect output, as the value of fahrenheit would be 37.0 and the value of celsius would be 98.6.

Some programming languages, such as Python, support named parameters. When calling functions using named parameters, parameter names and values are used, and positions are ignored. When names are not used, arguments are identified by position. For example, any of the following function calls would be valid:

What does this mean? How do I change a parameter? This short tutorial will help you figure out how parameter passing in Java works and will help you avoid some common mistakes.

First let's get the terminology straight. The terms "arguments" and "parameters" are used interchangeably; they mean the same thing. We use the term formal parameters to refer to the parameters in the definition of the method. In the example that follows, x and y are the formal parameters.

We use the term actual parameters to refer to the variables we use in the method call. In the following example, length and width are actual parameters.

    // Method definition
    public int mult(int x, int y)
    {
       return x * y;
    }

    // Where the method mult is used
    int length = 10;
    int width = 5;
    int area = mult(length, width);
Pass-by-value means that when you call a method, a copy of each actual parameter (argument) is passed.   You can change that copy inside the method, but this will have no effect on the actual parameter. Unlike many other languages, Java has no mechanism to change the value of an actual parameter. Isn't this very restrictive?  Not really. In Java, we can pass a reference to an object (also called a "handle")as a parameter. We can then change something inside the object; we just can't change what object the handle refers to.

Passing Primitive Types

Java has eight primitive data types: six number types, character and boolean. When any variables of these data types are passed as parameters to a method, their values will not change. Consider the following example:
  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
If tryPrimitives is called within the following code what will the final print statement produce?
    int ii = 1;
    double ff = 1.0;
    char cc = 'a';
    boolean bb = false;
    tryPrimitives(ii, ff, cc, bb);
    System.out.println("ii = " + ii + ", ff = " + ff +
                       ", cc = " + cc + ", bb = " + bb);

What is a variable that receives an argument that is passed into a method?
What's really happening here? When Java calls a method, it makes a copy of its actual parameters and sends the copies to the method where they become the formal parameters. Then when the method returns, those copies are discarded and the variables in the main code are the same as before.


Passing Object References

What if an argument to a method is an object reference? We can manipulate the object in any way except we cannot make the reference refer to a different object.

Suppose we have defined the following class:

class Record
{
  int num;
  String name;
}
Now we can pass the object as a parameter to a method:
  public static void tryObject(Record r)
  {
    r.num = 100;
    r.name = "Fred";
  }
In some other code we can create an object of our new class Record, set its fields, and call the method tryObject.
    Record id = new Record();
    id.num = 2;
    id.name = "Barney";
    tryObject(id);
    System.out.println(id.name + "  " + id.num);
The print statement prints out "Fred 100".

Note that the object's instances variables are changed in this case. Why? The reference to id is the argument to the method, so the method cannot be used to change that reference; i.e., it can't make id reference a different Record. But the method can use the reference to perform any allowed operation on the Record that it already references.

Side Note: It is often not good programming style to change the values of instance variables outside the object. Normally, the object would have a method to set the values of its instance variables.

We cannot however make the object parameter refer to a different object by reassigning the reference or calling new on the reference. For example the following method would not work as expected:

  public void createRecord(Record r, int n, String name)
  {
    r = new Record();
    r.num = n;
    r.name = name;
  }
We can still encapsulate the initialization of the Record in a method, but we need to return the reference.
  public Record createRecord(int n, String name)
  {
    Record r = new Record();
    r.num = n;
    r.name = name;
    return r;
  }

Passing Strings

When we write code with objects of class String, it can look as if strings are primitive data types. For example, when we assign a string literal to a variable, it looks no different than, say, assigning an number to an int variable. In particular, we don't have to use new. In fact, a string is an object, not a primitive. A new is required, and Java does it behind the scenes. It creates a new object of class String and initializes it to contain the string literal we have given it.
    String str = "This is a string literal.";
What is a variable that receives an argument that is passed into a method?

Because str is an object we might think that the string it contains might be changed when we pass str as a parameter to a method. Suppose we have the method tryString:

  public static void tryString(String s)
  {
    s = "a different string";
  }
When the following code is executed, what does the print statement produce?
  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
0

What is a variable that receives an argument that is passed into a method?
Why is this? Maybe this picture will help you understand what goes on behind the scenes. It is important to remember what Java does when it assigns a string literal to an object. A different String object is created and the reference variable is set to point to the newly created object. In other words the value of the formal parameter, s, has changed, but this does not affect the actual parameter str. In this example, s pointed to the string object that contains "This is a string literal". After the first statement of the method executes, s points to the new string, but str has not changed.

Like other objects, when we pass a string to a method, we can in principle, change things inside the object (although we can't change which string is referenced, as we just saw). However, this capability is not useful with string because strings are "immutable". They cannot be changed because the String class does not provide any methods to modify its local variables.

Questions

A: Pass-by-value in Java means

B: Given the following method:

  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
1what are the values of p and q after the following code executes?
  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
2

We have to use a bit of a trick to write a swap routine that works. 


Return values

Okay, so how do we change the values of variables inside methods? One way to do it is simply to return the value that we have changed. In the simple example below, we take two integers, a and b, as parameters and return a to the power of b.
  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
3Now when we call the method power, number gets assigned the value that power returns.
  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
4Since methods should be designed to be simple and to do one thing, you will often find that returning a value is enough, and that you don't need to change the value of any parameters to the method. Note that this does not help us write a swap method because a method can only return one value, and to write swap we need to change the value of two variables.

Question

C: Given the following method:
  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
5what are the values of p, q and r after the following code executes?
  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
6

Passing Arrays

Arrays are references. This means that when we pass an arrays as a parameter, we are passing its handle or reference. So, we can change the contents of the array inside the method.
  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
7When the following code is executed, the array a does indeed have the new values in the array.
  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
8The print statements produces "a[0] = x, a[1] = y, a[2] = z".

Question

D: Given the following method:
  public static void tryPrimitives(int i, double f, char c, boolean test)
  {
    i += 10;    //This is legal, but the new values
    c = 'z';    //won't be seen outside tryPrimitives.
    if(test)
      test = false;
    else 
      test = true;
  }
9what is the output after the following code is run?
    int ii = 1;
    double ff = 1.0;
    char cc = 'a';
    boolean bb = false;
    tryPrimitives(ii, ff, cc, bb);
    System.out.println("ii = " + ii + ", ff = " + ff +
                       ", cc = " + cc + ", bb = " + bb);
0

Summary

All you need to remember is thatAll arguments to methods in Java are pass-by-value.

That, combined with an understanding of the different between primitives and references and careful tracing will allow you to understand any Java method calls.

Which argument is passed to a method?

Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.

What is a value passed into a method called?

Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.