Skip to main content
Lesson 7 - More About Methods
Lesson MenuPreviousNext
  
Value Parameters and Returning Values page 4 of 10

  1. The word parameter is used to describe variables that pass information within a program. The simple process in Program 7-2 of passing a number (of gallons) to a method that will compute something (number of liters) is representative of a common occurrence in Java programming - passing values with parameters. Sometimes the word "argument" is used in place of parameter.

  2. We mentioned above that the parameter gallons is a formal parameter because it is named in the instantiation of the method. Another kind of parameter is a value parameter, which is used in a computation. In the computation amount * 3.785, amount is a value parameter.

  3. A value parameter has the following characteristics:

    1. This value parameter is a local variable. This means that it is valid only inside the block (method) in which it is declared.
    2. It receives a copy of the argument that was passed to the method. The value of 10 stored in gallons (inside main) is passed to the parameter amount (inside toLiters).
    3. The value parameter is a variable that can be modified within the method.

  4. In order for a method to return a value, there must be a return statement somewhere in the body of the method.

  5. If a method returns no value the term void should be used. For example:

    public void printHello( )
    {
       System.out.println("Hello world");
    } 
  6. A function (method) can have multiple parameters in its parameter list. For example:

    public double doMath (int a, double x)
    {
       ... code ...
       return doubleVal;
    }

    When this method is called, the arguments fed to the doMath method must be of an appropriate type. The first argument must be an integer. The second argument can be an integer because it will be promoted to a double.

    double dbl = doMath(2, 3.5);      //  this is okay
    double dbl = doMath(2, 3);        //  this is okay
    double dbl = doMath(1.05, 6.37);  //  this will not compile
    
  7. Value parameters are often described as one-way parameters. The information flows into a function but no information is passed back through the value parameters. A single value can be passed back using the return statement, but the formal parameters in the function remain unchanged.

  8. The formal parameters used to supply values for the value parameters can be either literal values (2, 3.5) or variables (a, x).

    double dbl = doMath(a, x);    // example using variables


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.