Java - Methods

Methods are blocks of code that perform specific tasks and can be called and executed multiple times within a program. Methods allow for code reuse, modularization, and abstraction, making your code more organized and easier to understand.

Defining Method

In Java, a method is defined within a class and consists of a method signature and a method body. The method signature specifies the name of the method, the return type (if any), and the parameters (if any). The method body contains the code that is executed when the method is called.

Here's the syntax for defining a method:


            modifier returnType methodName(parameters) {
                // Method body
            }                      
        

Let's break down the different components of a method:

  • Modifier: Optional keyword that specifies the access level and behavior of the method (e.g., public, private, protected).
  • Return Type: The data type of the value that the method returns. Use void if the method does not return any value.
  • Method Name: The name that identifies the method. Choose a meaningful and descriptive name.
  • Parameters: Optional input values that can be passed to the method. Multiple parameters are separated by commas.
  • Method Body: The block of code that contains the statements to be executed when the method is called.

Here's an example of a method that calculates the sum of two numbers and returns the result:


            public int sum(int a, int b) {
                int result = a + b;
                return result;
            }                                
        
Calling Methods

Once a method is defined, you can call and execute it by using its name followed by parentheses. If the method has parameters, you pass the corresponding values inside the parentheses. If the method has a return type, you can assign the returned value to a variable or use it in other computations.

Here's an example that demonstrates calling the sum method:


            class SumFunction{
                public static int sum(int a, int b) {
                  int result = a + b;
                  return result;
                }
              
                public static void main(String[] args){
                  int x = 5;
                  int y = 3;
                  
                  int sumResult = sum(x, y);
                  System.out.println("The sum is: " + sumResult);
                }
            }