Functions in Java

The goal of every programmer is to save time in both programming and debugging. However, there comes a time when you write hundreds of lines of code. It’s very frustrating having to repeat the same code now and then. It is more frustrating when your code gets some error, and you will need to debug the whole program.

Improve your programming expertise by using functions. Functions help in avoiding ambiguity. You will agree that breaking down the code into smaller chunks in functions will help you organize your work, and debugging becomes easy. Why repeat the same lines of code several places where you can put it inside a function and call it whenever you need to perform that task. Code reusability saves a lot of time.

In this tutorial, we will spare some time and discuss functions. In java, a method is the same as a function. All the functions must be defined within a class. By that, we can summarize by defining a Java method as a function belonging to a class. A function is a named unit of code that can be invoked anywhere in the class.

Example:

public class Main {
    public static void myFuntion() {
        // Do something here
    }
}
Structure-of-a-fuction
Structure-of-a-function

Syntax of a function

Public static void myFuction(String name, int age )
{
// fuction code
}
  • Access specifier – this shows the scope of availability of a fuction. ‘Public’ means that the function can be called from aywhere in the program. We have other access specifiers such as private and protected.Protected, the method can only be called within the class and its subslcasses. Private can oly be called inside the class
  • Modifier – ‘static’ is optional in a fuction defination. In this case static means  the function is a not an object of the main class but a method that belongs to the main class.
  • Retur type – We have functions that return a value and functions that do not return anything. Void, means that the function does not have a return value. If the fuction was to return a value, replace void with the data type of the returned value.
  • Function name – This the name of the function
  • Parameter list – it informs the compiler about the data type it will receive and the value to be returned.

Advantages of functions in Java

  1. Reusability of code – functions help in removing repetition of code in a program. With functions you can define it once and call it anywhere in the program to perform the task you need and you are not limited to the number of times you call the function.  Lastly it’s simple to relace the functions into libraries. This allows them to be used by more than one program.

2. Divide and conquer – Using functions helps break a program into smaller manageable chunks, hence making debugging and testing easier. Functions help in collaboration by breaking up the work into tasks for team development.

Types of fuctions

Computational functions – these functions perform mathematical operations and return the result. e.g., Math. sqrt. ()

Manipulative functions – they return 0 or 1, representing the success or failure of an operation.

Procedural functions – these are mostly the inbuilt functions. They perform an action but do not return a value, e.g., System.out.print()

How to call a functio in java

Calling a static method

We can call a method by writing the method’s name followed by the parenthesis and a semicolon. When a method is called, the program task to be performed is transferred to the method.
Example:

public class myFunction {
 
    static void functionExample() {
        System.out.println("You have called me! My name is: functionExample!");
    }
 
    public static void main(String[] args) {
        fuctionExample();
    }
}

Output:

You have called me! My name is: functionExample!

From the above example, we called a static method. To call a static method, we do not need to create an object of the class in which the method is defined.

Calling a pre-defined method

These are methods that are pre-defined in classes. To call this method, you can call them by their name. You will need to create an object because it’s a method of the class object.

    public class myfunction  
    {  
    public static void main(String[] args)   
    {  
    int a = 49;      
    double ans=Math.sqrt(a);  
    System.out.println("The square root of the object is: "+ans);  
    }  
    }  

Calling a user defined method

This is where we create a method and then call it when we need to use it. The user-defined method can be a static method or a non-static method.

public class functionExample  
    {  
  
    //user-defined static method
    static void show()   
     {  
       System.out.println("This is a static method.");  
     }  
    //user-defined non-static method  
    void display()   
    {  
    System.out.println("This is a non-static method.");  
    }  
    public static void main(String[] args)   
    {  
    //calling static method without using the object  
    show();
      
    //creating an object of the class  
    functionExample fun=new functionExample();  
    //calling non-static method  
    fun.display(); 
    }  
    }  

From the above example, we created a static user-defined method show() and non-static user-defined methods display(). We call a static method directly without creating an object, but for a non-static method, we created an object of the class to call it.

Method overloading

Method overloading is when the class contains two or more methods with the same name. The methods can be differentiated by the number of parameters, return type, or the type of parameters.
Example:

int sum( int a, int b);
double sum( double a, double b);

The two above methods have the same name but different return types. The first method will return an int while the second method returns a double.

int function(double number);
int function(double number, int position);

From the above example, the two functions have the same name but differ in the number of parameters. The first method has 1 parameter, while the second method contains 2 parameters.

The compiler distinguishes which function is called based on what is passed during the function call.
Example:

public class Main
{
  static int sum(int a, int b)   
    {  
    return a + b;  
    } 
  static double sum(double a, double b)   
    {  
    return a + b;  
    }  
    
  public static void main(String[] args)   
    { 
        
    int x = sum(10, 20);  
    double y = sum(10.20,20.10);  
    
    System.out.println("Summation of integer values = " +x);  
    System.out.println("Summation of double values = " +y);  
    }  
}  

Output:

Summation of integer values = 30
Summation of double values = 30.3

Conclusion

In java, static methods belong to a class; hence we do not need to create an object when calling these methods. However, for the non-static method, we need to create an object because the methods belong to objects. Functions describe an action to be performed. Creating functions helps in avoiding code ambiguity in your program and allows code reusability. In this tutorial, we have discussed what functions in java are, creating the functions and calling the function.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *