Methods in Java: Parameterized, Non-Parameterized and Methods returning values

Methods are an important part of a class. It defines the functions that are performed on the instance variables. Also, it might define other variables in its body and has a name other than the class name. It contains a set of statements that are executed when the method is called. It usually performs a specific task according to the programmer.

General Form of a Method

The general form of a method is shown below:

modifier returnType MethodName(Parameter-list) {
    //body of method
}
  • The modifier might or might not be mentioned according to the user- public, private, protected. When the modifier is not mentioned it is taken to be the default.
  • Return type specifies the type of the return value- void, int, float, double, char, boolean, etc.
  • MethodName can be anything that the user wants(generally something related to the function it performs) other than the class name.
  • Parameter-list is specified according to the requirement. It might or might not be present.

Naming conventions for methods

Typically a method can have any name that the programmer wants but and it can also be any legal identifier but the conventions make it easier for the programmer and the compiler to understand the code. Let us have a look at those conventions:

  • The method name should start with a lowercase.
  • Method names are usually verbs or beings with a verb in case it is a multi word method.
  • Multiword methods should have the second word(for two-word method name) or following words starting with a capital letter i.e. in camel case.
  • Methods usually have unique names inside a class but can also have same names in case of method overloading.

Here are a few examples of method naming conventions:

int calculateSum(int a, int b) {}

public void display() {}

public abstract void push(int item);

Parameterized and Non-Parameterized Methods

Java allows us to create two types of methods based on the parameter list. These are given below:

  • Parameterized methods: These methods contain a parameter list or an argument list which receives a value from the calling method.
  • Non-Parameterized methods: These methods do not have any parameter-list. The programmer can simply call the function without sending any values to the function.

Understanding Parameterized methods

The parameter is the variable definition in the method definition. Their type is specified in the parameter and is separated with commas. It is important to understand what type of parameter a function has and how it operates on them. There are two types of parameters: Formal Parameter and Actual Parameter.

  • Formal Parameter: Formal parameter is the one that is present in the function definition. This parameter receives the arguments that are passed to the method. For example:
public int sum(int a, int b) {    //this is the formal parameter
    //body
}
  • Actual Parameter: Actual parameter is the one that is present in the function call statement. This parameter sends the arguments that are passed to the method. For example:
ob.sum(num1, num2);    //this is the actual parameter

Note: Argument refers to the value that is being passed by the calling method to the called method.


Calling A Method

Calling a method refers to the process of invoking a method to perform its set of steps by the calling method. Now, there are two ways of calling a method in Java:

  • Call by Value: In call by value the actual value of the variable is passed as an argument and any changes made to it is not reflected in the actual value. This is done by passing the data directly or by passing a primitive variable holding the value. For example:
/*
 *This program shows call by value in Java. It calculates the sum of two numbers.
 */

import java.util.Scanner;

class CallByValue {

    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);
        int x, y;
        System.out.println("Enter two numbers : ");
        x = in.nextInt();
        y = in.nextInt();

        CallByValue ob = new CallByValue();
        //sending the values to the method sum and printing the sum that is returned. This is the actual parameter.
        System.out.println("The sum is : " + ob.sum(x, y));
    }

    /**
     * The method sum receives two values from the main method and returns their sum
     */
    public int sum(int a, int b) {//this is the formal parameter
        int s = a + b;
        return s; //return statement
    }
}

Output:-
Enter two numbers : 
45
78
The sum is : 123
  • Call by Reference: Call by reference refers to the process of passing the value of the address of the variables in place of the actual data, so, any changes made are reflected in the actual value. In languages like c,c++ the call by reference is achieved with the help of pointers but Java does not support pointers. In Java, we use the object reference to pass the value.
    Now since I have already mentioned that we send the address value of the variable it is actually a pass by value and there is no such pass by reference in Java. So it feels like we have sent the reference of the reference but basically, it is simply pass by value because every function call will have a new variable pointed to the same object whereas in the case of pass by reference same reference is used when passed to a method.
/**
 * This program shows call by reference(nah - call by value) in Java.
 * It calculates the square of a number.
 */

import java.util.Scanner;

class CallByValue2 {

    /**
     * The method Square receives an integer object from the main method
     * and returns the square of the value it contains
     */
    public static int square(Integer a) { //this is the formal parameter
        return a * a; //return statement
    }

    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);
        int x;
        System.out.print("Enter a number : ");
        x = in.nextInt();

        Integer intOb = new Integer(x);
        //sending the object's reference contained address to the method square where "a"
        // will be a new variable pointing to the same Integer object
        // and printing the value that is returned.
        // This is the actual parameter.
        System.out.println("The square is : " + square(intOb));
    }
}

Output:-
Enter a number : 6
The square is : 36

Methods with return type and the void keyword

Return type refers to the data type of the value that a method returns. The data types are usually primitives but can also have reference data types. The return type is defined in the method declaration as shown above. It is important to note that if the return type of the method is specified as int then it can only return int values and not double or any other data type values. This is true for all other data types. The return value should have the same data type as the return type of the method. Otherwise, the programmer will give an error.

Any method that doesn’t returns a value is declared with the keyword void. This does not mean that it cannot contain a return statement. It can contain a return statement to branch out to the calling method anytime as desired by the programmer. For example:

public void square(int num) {
    //body of method
    return;
}

If the programmer tries to return a value from a method declared as void then he/she will get a compiler error. Here is an example of both return type methods and methods declared as void:

/*
 *This program shows return type and the function of the void keyword. It calculates the square of a number and displays it.
 */

import java.util.Scanner;

class ReturnType {

    /*the main function also has the return type as void here so it does not return any value*/
    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);
        int x;
        System.out.print("Enter a number : ");
        x = in.nextInt();

        ReturnType ob = new ReturnType();
        //calling function display() which in turn calls square() and uses the value returned by square() as parameter.
        ob.display(ob.square(x));
    }

    /*this function has the return type as int and returns an integer value*/
    int square(int a) {
        return a * a;
    }

    /*this function has the return type as void so it does not return any value*/
    void display(int b) {
        System.out.println("The square of the number is : " + b);
    }
}

Output:-
Enter a number : 7
The square of the number is : 49

So, that’s all for this tutorial. Hope this helps and you like the tutorial. Do ask for any queries in the comment box and provide your valuable feedback. Do come back for more because learning paves way for a better understanding.

Keep Coding!! Happy Coding!! 🙂