Methods and Parameters

Other languages use: subroutine, sub, function, procedure...

A method is a section of code with a name, eg:


private void myTask(){
    x=4;
    y=5;
}
To call it up (invoke it) - we put:
myTask();

Passing parameters to the method

All programming languages have parameter-passing - v.important!

Example: A method which adds any two integers together, and leaves the result in sum. We declare it:

private void addUp(int a, int b) {
sum=a+b;
}

a and b are termed the 'formal parameters'

Here are some invocations/calls:

int  d=7, e=3;
addUp(5,6);
addUp(d,4);
addUp(d+e, 1);

Note: what values does sum take, above?


The layout of a class


class Fred.... {
    private int sum, n = 0;  // 'instance variables' -global to all methods of class

    public aMethod(){
        int n=3;
        addUp(n,6);
    }

    private void addUp(int a, int b) {
       sum=a+b;
    }

 }

Scopes

Where names clash, local variables and formal parameters take precedence, e.g:

Analogy of parameters - hi-fi amp


          --------------------
          |                   |
      ----|CD-IN              |
 input    |                   |
          |       AMP         |----- to speaker....
 sockets  |                   |
          |                   |
      ----|TAPE-IN            |
          |                   |
           -------------------

Using 'return'

What if we want the caller of the method to choose where to put the result? here is addUp done this way:
private int addUp(int a, int b){
int temp;
temp=a+b;
return temp;
}
here are some calls:
int e,f;
e=addUp(3,4);
f=5 + addUp(e, 2);
label1.setText("answer is " + addUp(8,9));

addUp(5,6); //ERROR- nowhere for returned value to go!