Methods in Java:

A method is a block of code which is separated from the main method and performs specific operations or tasks. They are defined within the classes and can be called (invoked) to execute their code. Methods are used to encapsulate functionality and promote code reusability.

Syntax:

helloworld.java
type methodName(type paramName1, ...) {
    // Method body
}

  • returnType - Specifies the type of data value the method is returning.
  • methodName - The name of the method, which must be a valid identifier.
  • parameterTypeX - The data type of each parameter.
  • parameterNameX - The name of each parameter.

Note : If we do not need parameters, it is not necessary to write anything inside parentheses.


Method with return type void:

helloworld.java
public class Main {

    // This is a method names "hello"
    static void hello() {
      System.out.println("Hello World!");
    }
    // "hello" method ends

    
    // Main method starts
    public static void main(String[] args) {

      //Calling "hello" method 
      hello();
    }
  }

This hello() method will print "Hello World!". We can call methods multiple times.

Execution of our code starts from Main method. Everything inside main method will be executed by the compiler. If we write a method outside the main method, it will not be executed until we call it in our main method.


Method with return type int:

helloworld.java
public class Main {

    public int add() {
    	int a = 4, b = 1;
        return a + b;
    }

    // Main method starts
    public static void main(String[] args) {

        Main main = new Main(); 

        int result = main.add(); 
        System.out.println(result);
    }
}

Parameterized Methods:

Till now, we have studied about unparameterized methods. Now we will talk about parameterized methods.

Parameterized methods are the methods which take variables as parameters and perform operations on them. These methods are designed to take input values, process them, and possibly return a result or perform some action based on the provided parameters.


helloworld.java
public class Main {

    public int add(int a, int b) {
        return a + b;
    }

    // Main method starts
    public static void main(String[] args) {
        Main main = new Main(); 
        int result = main.add(1, 2); 
        System.out.println(result);
    }
}

Note : The return value of a method can be stored in a variable.


Parameters and Arguments:

When there is a variable in the main function and we need it in the other function then we pass it to other function when we call it(inside parentheses). We can pass multiple arguments to a method but they should be equal to the number of parameters.

Parameters : variables in parenthesis when we declare function.
Arguments : variables in parenthesis when we call function.

helloworld.java
public class Main {

    public void printName(String name) {
        System.out.println("My name is " + name);
    }

    // Main method starts
    public static void main(String[] args) {
    
        Main main = new Main();
        main.printName("John"); 
        main.printName("Ammy");
        main.printName("Sarah");
        
    }
}

In this example, we are calling the same function with different parameter values. The method printName will accept the parameters which we provide as arguments and use this value to execute the code inside the function.

Note : We will pass as many arguments as we want. The number of arguments and parameters must be same.


Method Overloading:

Method overloading allows us to define multiple methods with the same name in the same class but;
  • number of parameters will be different, Or
  • if same, their data types will be different


helloworld.java
public class Main {

    public int add(int a, int b) {
        return a + b;
    }

    public int add(int num1, int num2, int num3) {
        return num1 + num2 + num3;
    }

    // Main method starts
    public static void main(String[] args) {

        Main main = new Main(); 
        int result1 = main.add(1, 2); 
        System.out.println("Result: " + result1);

        int result2 = main.add(1, 2, 3); 
        System.out.println("Result: " + result2);


    }
}

This add method is overloaded as number of parameters is different.

Method Overloading with different data types of Parameters:

helloworld.java
public class Main {

    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }

    // Main method starts
    public static void main(String[] args) {

        Main main = new Main(); 
        int result1 = main.add(1, 2); 
        System.out.println("Result: " + result1);

        double result2 = main.add(1.3, 2.6); 
        System.out.println("Result: " + result2);


    }
}

This add method is overloaded as parameters have different data types.

Recursion:

Recursion means calling the method within the same method. This is done to break the one complicated problem into many simpler problems and then solving the simpler problems.

Let us consider an array of ten numbers and we want to sort it inascending order. It will be difficult. If we split our array into pairs of two and then try to sort it, it will be easy.


helloworld.java
public class Factorial {

    // Recursive function to calculate factorial
    public static int factorial(int n) {
        // Base case: if n is 0 or 1, return 1
        if (n == 0 || n == 1) {
            return 1;
        } else {
            // Recursive case: n! = n * (n-1)!
            return n * factorial(n - 1);
        }
    }

    public static void main(String[] args) {
        int n = 5;
        int result = factorial(n);
        System.out.println(n + "! = " + result);
    }
}

In this Example;

  • The factorial function calculates the factorial of n recursively.
  • The base case is when n is 0 or 1; in this case, the function returns 1.
  • In the recursive case, the function calls itself with n-1, which is a smaller problem, until it reaches the base case.
  • The result is calculated as n * factorial(n - 1).
When we run this program with n = 5, it calculates 5! by breaking it down into smaller multiplications and returns the result of 120. This is a simple example of how recursion works in Java to solve a problem by breaking it down into smaller, similar sub-problems.

Static VS Public Methods:

The difference between static and public methods is that static methods can be called without the creation of an object while public methods can only be accessed using object of the class.

As the concept of static and public method invloves object, you will have to learn about Object Oriented Programming.


Static Method:

helloworld.java
public class Main {
  // Static method to add two numbers
  public static int add(int a, int b) {
      return a + b;
  }

  public static void main(String[] args) {
      int result = Main.add(5, 3); 
      System.out.println("Sum: " + result);
  }
}

Public Method:

helloworld.java
public class Main {
  // Static method to add two numbers
  public int add(int a, int b) {
      return a + b;
  }

  public static void main(String[] args) {
  
    Main main = new Main(); 
      int result = main.add(5, 3); 
      
      System.out.println("Sum: " + result);
  }
}