Methods in Java

Java 8Object Oriented ProgrammingProgramming

A Java method is a collection of statements that are grouped together to perform an operation. Let us no see the syntax to create a method in Java −

public static int methodName(int a, int b) {
   // body
}

Here,

  • public static − modifier

  • int − return type

  • methodName − name of the method

  • a, b − formal parameters

  • int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is shown in the following syntax −

modifier returnType nameOfMethod (Parameter List) {
   // method body
}

The syntax shown above includes −

  • modifier − It defines the access type of the method and it is optional to use.

  • returnType − Method may return a value.

  • nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.

  • Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.

  • method body − The method body defines what the method does with the statements.

Let us now see an example to create and call a method in Java. Here, we are also passing parameter values −

Example

public class Demo {
   public static void main(String[] args) {
      int a = 30;
      int b = 45;
      System.out.println("Before swapping, a = " + a + " and b = " + b);
      // Invoke the swap method
      swapFunction(a, b);
      System.out.println("\n**Now, Before and After swapping values will be same here**:");
      System.out.println("After swapping, a = " + a + " and b is " + b);
   }
   public static void swapFunction(int a, int b) {
      System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
      // Swap n1 with n2
      int c = a;
      a = b;
      b = c;
      System.out.println("After swapping(Inside), a = " + a + " b = " + b);
   }
}

Output

Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45
raja
Published on 24-Sep-2019 07:19:04
Advertisements