Java: Methods - Example

Example

This example shows a simple method that computes the area of a rectangle:
    1. int computeArea(int width, int height) {
    2.     int area;   // This is a local variable
    3.     area = width * height;
    4.     return area;
    5. }
Line 1 is the method header. The first int indicates that the value this method returns is going to be an integer. The name of the function is "computeArea", and it has two integer parameters: width and height.

The body of the method starts with the left brace, "{", on the end of the first line. The "{" doesn't have to be on the same line as the header, but this is a common style.

The body of this simple function contains a declaration on line 2, an assignment statement in line 3, and a return statement on line 4. If a method returns a value, then there must be at least one return statement. A void method (one which does not return a value), does not require a return statement, and will automatically return at the end of the method.