xhtml
 

Procedures and Functions

Methods are divided roughly into procedures and functions.

Most of the methods that we've already seen in the exercises are procedures. A procedure is a block of code where the main aim is to do something, such as print out text. For example:

void print (int n)
{
   System.out.println("n = " + n);
}

The word void means that the method doesn't return a result. The word print is the name of the method, and it is very common for programmers to pick a verb for this. Then comes the argument list, giving the type and name of each argument. Then comes the block of code to be carried out.

With a function, the main aim is to return a result. For example, this method squares a number:

int square (int n)
{
   return n*n;
}

The differences between this and a procedure are the result type and the return statement. The first word, instead of being void, tells you what type of value the method returns. The method ends by returning a result expression.


Back