Methods in Java with examples

A method in Java is a section of code that completes a particular task. Large, complex programs are divided into smaller, easier-to-manage pieces using this technique. Classes contain declarations of methods, which are accessible from anywhere in the program.

A method, in other words, is a block of code that performs a specific task and can be called (invoked) from other parts of the program. Methods are used to encapsulate functionality, encourage code reuse, and improve the code's maintainability and readability.

Method definition in Java

In Java, the basic syntax for defining a method is as follows:

[access modifier] [static] [return type] [method name]([parameter list]) {
   // method body or block of code to define the method
   
   return [return value];
}

In the above general form of the method definition in Java,

Java method example

The following Java program is an example demonstrating the method.

Java Code
public class MethodExample {
    public static void main(String[] args) {
        myMethod();
    }
    
    public static void myMethod() {
        System.out.println("Hello there, I'm Edwin");
    }
}
Output
Hello there, I'm Edwin

In this example, I define a class called MethodExample, which contains two methods: main() and myMethod(). The execution of a Java program always begins with the main() method. Inside the main() method, the method myMethod() was invoked or called, which in turn caused the program to output "Hello there, I'm Edwin" to the output console.

The myMethod() method is defined as a static method, which means that it belongs to the class rather than to an instance of the class.

Now let's create another example demonstrating the methods with parameters in Java.

Java Code
public class MethodExample {
    public static void main(String[] args) {
        int a = 50;
        int b = 100;
        myMethod(a, b);
    }

    public static void myMethod(int x, int y) {
        int sum = x + y;
        System.out.println("The sum of " + x + " and " + y + " is " + sum);
    }
}
Output
The sum of 50 and 100 is 150

In the main method, two integer variables a and b are declared and initialized with the values 50 and 100 respectively. Then, the myMethod method is called with a and b as arguments. The myMethod method takes two integer parameters x and y, calculates their sum and assigns it to a local variable named sum. It then prints a message on the console which includes the values of x, y and sum using string concatenation.

When the myMethod method is called in the main method, it receives the values of a and b as arguments and performs the addition operation on them, and then prints the result on the output console.

The "x" and the "y" variables inside the "myMethod" are considered the formal parameters, which receive the copies of "a" and "b". So anything changed does not reflect the original value of "a" and "b" inside the main function. So this way of calling a method in Java with parameters can be called a call-by-value approach. However, to work with the actual value of the arguments passed to the method from the main method, you can approach it using the call-by-reference. As an example:

Java Code
public class JavaMethodExample {
    public static void main(String[] args) {
        int a = 100;
        int b = 200;

        // Swap using call by value
        swapByValue(a, b);
        System.out.println("After swapping using the call-by-value approach:\n a = " + a + ", b = " + b);

        // Swap using call by reference
        int[] arr = new int[]{a, b};
        swapByReference(arr);
        System.out.println("\nAfter swapping using the call-by-reference approach:\n a = " + arr[0] + ", b = " + arr[1]);
    }

    public static void swapByValue(int x, int y) {
        int temp = x;
        x = y;
        y = temp;
    }

    public static void swapByReference(int[] arr) {
        int temp = arr[0];
        arr[0] = arr[1];
        arr[1] = temp;
    }
}
Output
After swapping using the call-by-value approach:
 a = 100, b = 200

After swapping using the call-by-reference approach:
 a = 200, b = 100

In the call by reference approach, the actual parameters (a and b) are stored in an array and a reference to this array is passed to the swapByReference method. This means that the formal parameter (arr) of the method points to the same memory location as the actual parameter array.

Java method that returns a value

The following Java program uses a method named "FindSum()" to find the sum of two values and returns the addition or summation value.

Java Code
public class MethodExample {
    public static void main(String[] args) {
        int a = 50;
        int b = 100;
        int sum = FindSum(a, b);
        System.out.println("The sum of " + a + " and " + b + " is " + sum);
    }
    
    public static int FindSum(int m, int n) {
        int result = m + n;
        return result;
    }
}
Output
The sum of 50 and 100 is 150

Now let's modify the above program to allow the user to enter the values of "a" and "b" at run time of the program.

Java Code
import java.util.Scanner;

public class MethodExample {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter the value of a: ");
        int a = input.nextInt();
        System.out.print("Enter the value of b: ");
        int b = input.nextInt();
        
        int sum = FindSum(a, b);
        System.out.println("\nThe sum of " + a + " and " + b + " is " + sum);
        
        input.close();
    }
    
    public static int FindSum(int m, int n) {
        int result = m + n;
        return result;
    }
}
Output
Enter the value of a: 10
Enter the value of b: 20

The sum of 10 and 20 is 30

In the following code fragment from this example:

public static int FindSum(int m, int n) {
   int result = m + n;
   return result;
}

Methods such as instance methods, constructors, abstract methods, and so on will be covered later in this Java tutorial series. Because these methods fall under the category of object-oriented concepts, they will be discussed or covered after the fundamentals of object-oriented concepts such as classes and objects have been covered. Don't worry, just keep following or continuing this tutorial series; everything needed for beginners will be covered one by one.

Java Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!