Functions are a way of breaking a large program
down into
smaller parts. They also allow the programmer to better
organize his or her logic so that it can be readily understood
by others. Think of a function as being a small program with
the exception that it can be passed things and it can return
something. For now we will declare our functions 'Public'.
Function are normally declared to be of a specific type, just
like the standard data types (int, String, char, float etc)
Later you will learn to refer to Functions as 'Methods' .
Functions can be passed things such as variables and arrays
etc. so that the function can play with the values in the variables
or arrays.
Functions have the ability to return a single value by using
the return command followed by the variable or value being
returned. NOTE:: Functions declared to be of type 'void'
will not return a value. All other type will return a value. These
values are returned back to the program that called the function.
Functions are called by referring to the name of the function
followed by an optional parameter list of things to be passed
to the function.
Functions can only play with variables that:
1 declared within the function (local)
2 values passed to the function
3 global variables declared above the function but not
inside another function
Examples of calling 3 functions
fun1(); // call a function
passing nothing
int a=3;
int b=11;
int c=fun2(a,b); //
call a function passing 2 values both int
// fun2 returns a value that is put into c
int scores[] = new
int[10]; // declare int array
fun3(scores); // call fun3
passing scores by reference
Examples of the 3 functions that were called above
public void
fun1() // void means no value
returned
{
JOptionPane.showMessageDialog(null,"hello");
}
public int fun2(int n1, int n2)
{
int n3;
n3 = n1 * n2;
return n3;
}
public void fun3(int
numbers[] ) // pass array by reference
{
for (int
a=0;a<10;a++)
numbers[a] = a * 10;
}
// note in the last function 'fun3' it puts values in 'numbers'
array
// but in fact it is putting values in the 'scores' array. Called
// passing by reference. 'numbers' is merely another name
// for the memory locations of the 'scores' array.