Learn Java Basics
About Lesson

A function header includes the following components:

  1. Access modifier: It specifies the level of access to the function. There are four types of access modifiers in Java: public, private, protected, and default (no access modifier).

  2. Return type: It specifies the data type of the value that the function returns, if any. If the function does not return a value, then the return type is specified as “void”.

  3. Function name: It is the name of the function, which should be meaningful and descriptive.

  4. Parameters: It is a comma-separated list of input parameters to the function. Each parameter consists of a data type and a parameter name.

The function header syntax in Java is as follows:

[access modifier] [static] [final] [return type] [function name] ([parameter list]) [throws exception list]

Here is an example function header in Java:

public static int calculateSum(int num1, int num2) throws Exception {
// Function body goes here
}

In this example, the function header includes:

  • Access modifier: “public”
  • Static keyword: Indicates that the function is a static method
  • Return type: “int”
  • Function name: “calculateSum”
  • Parameters: “int num1” and “int num2”
  • Throws exception list: “throws Exception” indicates that this function can throw an exception of type Exception, and it must be handled by the calling code.

Working of Function

A function is a self-contained block of code that performs a specific task. Functions help to break down large, complex problems into smaller, more manageable pieces. In Java, functions are also known as methods. Here is an example of a simple function in Java:

public static int calculateSum(int num1, int num2) {
int sum = num1 + num2;
return sum;
}

This function is named calculateSum and takes two integer parameters num1 and num2. It calculates the sum of the two numbers and returns the result as an integer.

Now let’s see how this function works by calling it from another part of the program:

int result = calculateSum(3, 5);
System.out.println(result);

In this code, we are calling the calculateSum function and passing two arguments 3 and 5. The function then calculates the sum of the two numbers and returns the result, which is stored in the variable result. Finally, the result is printed to the console using the System.out.println statement.

When this program is executed, the output will be:

8

This is because the calculateSum function takes the input values of 3 and 5, calculates their sum as 8, and returns that value to the calling code. The calling code then stores the result in the result variable and prints it to the console.

In this way, functions help to organize code into reusable blocks that can be called from anywhere in the program, making code easier to read, write, and maintain.

Join the conversation