Functions in Java

When we write codes in Java, they may not be longer than 1-2 pages. But at the professional and industrial levels, when programmers write codes, they are of minimum 50000 lines of code and their length extend as per the size of the program and its features and specifications.

When we commit some mistake or feel the necessity of some modifications, we can easily scroll upwards or downwards and then make necessary changes.

But the same approach for solving this problem in a program of say 80000 lines of code is absolutely not feasible.

Thus the concept of ‘functions’ in Java has been introduced in Java.

Let us understand this as a simplified example:

Suppose you are asked to find the factorial of two given integers, say 5 and 7. The following code will be:

class factorial

{

   public static void main()

      {

int a=5, b=7;

int i;

//Highlighted f=1;

for(i=1;i<=a;i++)

   f=f*i;

System.out.println("Factorial of"+a+" is: "+f);

//Highlighted f=1;

for(i=1;i<=b;i++)

   f=f*i;

System.out.println("Factorial of"+b+" is: "+f);

      }

}

You can observe the part of the code that is highlighted is repeated twice, both the segments of the code are performing the same task of calculating the factorial of the numbers stored in the variables a and b respectively. So for the same task, we have to write the code twice as well as it will accumulate a significant amount of memory space.

Thus functions can be used to solve this problem. The solution would be creating a separate function for factorial calculation and applying them as many times as wanted.

In short, Function can be defined as a program segment or module that can be used in different instances in the program simultaneously with the main function. Functions are also known as member methods or simply Methods.

 

Functions in Java