Functions

Java does not support functions outside classes. In OOP function inside class is called a method.

function example
/* 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

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.