Tutorial 4: Functions


Overview on this Tutorial:

1. Simple Function (FunctionTest1.java)

2. Pass Array to a Function (FunctionTest2.java)


Simple Function (FunctionTest1.java):

1. Similar to other Programming, you can define function in Java. The syntax of a (simple) function in Java is:

<Returned Type> <Function Name> (<Parameter List>) {
    <Function Body>
}

And a corresponding example is:

int sum(int x, int y) {
    int z = x+y;
    return z;
}

2. "Returned Type" specifies the type of returned value. There usually exist a "return" statement in the function Body, specifying what values to be returned (for example, "return z;").

3. When "Returned Type" is "void" (nothing to be returned), there could be no return statement. ("void" function is similar to "procedure" in Pascal.)

4. Followed by "Returned Type", we have to give a function name. The function name is usually unique (in the same scope); otherwise, the parameter list should be different.

5. You can have zero or more parameter in the parameter list, each of them can have different type.

6. Now consider a call of the function "sum":

int a = 3;
int b = 4;
int c = sum(a, b);

7. The value of "a" will be passed to "x", and the value of "b" will be passed to "y". The value of "z" is returned, that is "sum(a,b)".

8. A simpler way to call: "sum(3, 4);"

9. Note that in the example, "x" and "y" are copies of "a" and "b" respectively.

Practice: Try to explain why the function swapFail() fails to swap two integers.

 


Pass Array to a Function (FunctionTest2.java):

1. You can also pass array to a function.

void swapInt(int[] x) {
    int temp = x[0];
    x[0] = x[1];
    x[1] = temp;
}


public void startApp() {
    int [ ] z = {3, 4};
    // ...
}

2. In the example, z is an integer array. Actually, z is said to be an "object" of Array "class". For objects, the variables only store the "reference". ("class" and "object" will be introduced later, and you may think that "reference" is just an address of the storage).

z =>

 

3
4

3. When z is pass as a parameter, the reference (address) is copied.

4. That is, z and x also store the same reference (address).

x,z =>

 

3
4

5. So now the function "swapInt()" can work correctly.