A Java method is a group of statements that are always executed together with the purpose of producing a certain result in response to a certain input. A method has a name, either a set of input parameters or no parameters at all, a body inside {} brackets, and a return type or void keyword that indicates that message does not return any value. Here is an example of a method:
int multiplyByTwo(int i){
int j = i * 2;
return j;
}
In the preceding code snippet, the method name is multiplyByTwo. It has one input parameter of type int. The method name and the list of parameter types are together called method signature. The number of input parameters is called arity. Two methods have the same signature if they have the same name, the same arity, and the same sequence of types in the list of input parameters.
The same preceding method can be re-written in many styles and with the same result:
int multiplyByTwo(int i){
return i * 2;
}
Another style is as follows:
int multiplyByTwo(int i){ return i * 2; }
Some programmers prefer the most compact style, to be able to see as much code as possible on the screen. But that could decrease another programmer's ability to understand the code, which could lead to programming defects.
Another example is a method without input parameters:
int giveMeFour(){ return 4; }
It is quite useless. In reality, a method without parameters would read data from a database, for example, or from another source. We showed this example just to demonstrate the syntax.
Here is an example of code that does nothing:
void multiplyByTwo(){ }
The preceding method does nothing and returns nothing. The syntax requires indicating the absence of a return value using the keyword void. In reality, methods without return values are often used to record data to a database or to send something to a printer, to an email server, to another application (using web-services, for example), and so on.
And just for a complete overview, here is an example of a method with many parameters:
String doSomething(int i, String s, double a){
double result = Math.round(Math.sqrt(a)) * i;
return s + Double.toString(result);
}
The above method extracts a square root from the third parameter, multiplies it to the first parameter, converts the result into a string, and attaches (concatenates) the result to the second parameter. The types and methods from the class Math used will be covered in Chapter 5, Java Language Elements and Types. These calculations do not make much sense and are provided just for illustration purposes.