Skip to content

Methods

The method is nothing more than a set of instructions. We group the code in this way for several reasons:

  • If a piece of code is to be executed in many places, it is definitely better to create a method and run (call) it, than to copy the same piece of code repeatedly. This is important, because in case of an error, you need to correct it in one place, not in several.
  • Programs are large, without proper division, mastering the whole structure is very time consuming. A sensible division into smaller parts allows you to understand the code faster.

Definition

The syntax for defining the method is as follows:

<access modifiers> <type returned> <name of method>(<optional list of arguments>) {
    <body of the method>
}

Let's create a simple example of a method definition:

void printName(String name) {
    System.out.println("My name is: " + name);
}

This method accepts the name argument of the String type and displays its value easily.

In the above example, no access modifiers are used. These will be discussed in detail in the other section.

The part of the method declaration where we give the access modifiers, the returned type, the name of the method and an optional list of arguments is called the name of the method.

The method signature from the previous example is presented below:

void printName(String name)

Arguments

Methods may or may not accept any number of arguments. Just because it is possible does not mean that it should be done. In most cases, methods with a large number of arguments are a sign of poor quality code (aka. code smell).

If a method contains several arguments, they are separated by commas. Below is a method that calculates the difference between two integers:

int diff(int arg1, int arg2) {
    return arg1 - arg2;
}

The returned value

Methods can return values. The value returned by the method is preceded by the keyword return. In the method signature we additionally declare the returned type. This is illustrated by a simple example:

int returnedNumberExample() {
    return 5;
}

It is also possible that the method will not return any value. In this case, the declared type that our method returns is a special type of void, e.g., the `background' type:

void print() {
    System.out.println("Hello World!");
}

The value returned can be any simple variable or an [object] type (class_objects.md). We can also prematurely interrupt a method that does not return any values and exit it, using the keyword return without providing a value, e.g., [object_classes.md]:

void returnExample(int number) {
    if (number % 2 == 0) {
        return;
    }
    System.out.println(number);
}

The body of the method

The body of the method is the entire code contained between the curly brackets '{}'. For example, the body of the diff method defined in one of the above examples is:

return arg1 - arg2;

The body of the method above consists only of the value returned by the method, which was calculated on the basis of the arguments provided.

System.out.println("Hello World!");

As in the example above, the body of the method can only be a simple call of the printing method and the method does not return anything. Of course, method bodies can be more complicated and consist of many lines of code.

Calling a method

A clear distinction must be made between the definition of a method and its call. The definition, as we described earlier, is a declaration of the method together with the name of the method, the type returned, the arguments and its body. A method call is a reference to the method name with the appropriate parameters (or without parameters in the case of a non-argument method). An example of a method definition and its call is presented below:

// declaration of the method
int multiple(int arg1, int arg2, arg3) {
    return arg1 * arg2 * arg3;
}
// calling the method
int multipleValue = multiple(23, 2, 5); // 230

The method named multiple as defined in the input has three arguments with the following names: arg1 arg2 arg3, and as a result, returns the result of a multiplication of these arguments. When calling the method, refer to its name (in our case, multiple) with the corresponding values of the input parameters (remember the correct types, as in the definition).

Since our method returns a numeric value of int type, it is possible to assign the returned result to a variable of int type (according to the method definition).

Method naming

In Java it has been assumed that the names of the methods are written in the so-called camelCase standard, i.e. the following words are written together, starting each subsequent one with a capital letter (except the first). Examples are provided below:

  • sumElements
  • startProcessingData

The same principle applies to variable name declarations.