Defining a Function in Java

Before discussing function definitions, first let us be aware of Access Specifiers:

Access Specifiers:

Access Specifiers are those keywords that are used to define the scope of a member method’s usage in a program.

They are:

  • Private: When a function is declared as private, they can be used only within their class.
  • Public:  When a function is declared as public, they can be used even outside the visibility of the class.
  • Protected: When a function is declared as Protected, they can be used within their class but can be inherited to another class.

Now let us understand how to define a function:

<Access Specifier> <Return Type> <Function Name> (<Parameters>)
      // Body

The list of the parameters is separated by commas.


public void factorial(int a)
  int i;
  System.out.println("Factorial of"+a+" is: "+f);

Here the return type of the function factorial() is void thus it will not return anything.

A function thus has the following components:

→Function Head

→Function Body

→ Return Value (if any)

Function head is the part where the access specifiers, return type and name of the function is defined.

Function Body is the set of statements wrapped within the curly braces of the function.

Return value is the statement within the function body which specifies the value that is to be returned by the function.  


return n;
Defining a Function in Java