Functions
Java does not support functions outside classes. In OOP function inside class is called a method.
/* method syntax
<return-type-name> <method-name>([<param-type> <param-name>
[,<param-typeN> <param-nameN>]]){
// code to be executed
return <expr>
}
*/
passing arguments
A method can have a list of arguments in parentheses, separated by commas.
Java does not support default values for arguments.
Arguments with primitive types passed by value and object arguments by reference (more details).
The final keyword can be used with arguments to block primitive arguments from changing and object arguments from replacement of object reference
variable-length argument
Since Java 5 supports the variable-length arguments. It is known also as varargs. There are certain restrictions on the usage to avoid ambiguity:
- there can be only one variable-length argument
- the variable-length argument must be the last in list of arguments
- within function you refer to the argument as to the array
public static int sum(int... list){
int total = 0;
// add all the values in list array
for (int i = 0; i < list.length; i++){
total += list[i];
}
return total;
}
return value
The return statement finishes method execution and return specified value if necessary to caller.
The special type void is used to indicate that the method does not return any value. In this case, return may not be used or used without a return value.
overloading
Java supports methods overloading. This means, class can have several methods with same name but with different number of arguments or types of arguments.