How to declare, define and call a method in Java?

Java 8Object Oriented ProgrammingProgramming

Following is the syntax to declare a method in Java.

Syntax

modifier return_type method_name(parameters_list){
   //method body
}

Where,

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

  • return_type − Method may return a value.

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

  • parameters_list − The list of parameters, it is the type, order, and a 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.

Calling a method

For using a method, it should be called. There are two ways in which a method is called i.e., method returns a value or returning nothing (no return value).

Example

Following is the example to demonstrate how to define a method and how to call it −

Live Demo

public class ExampleMinNumber {
   public static void main(String[] args) {
      int a = 11;
      int b = 6;
      int c = minFunction(a, b);
      System.out.println("Minimum Value = " + c);
   }
   
   /** Returns the minimum of two numbers */
   public static int minFunction(int n1, int n2) {
      int min;
      if (n1 > n2){
         min = n2;
      } else {
         min = n1;
      }
      return min;
   }
}

Output

Minimum value = 6
raja
Published on 09-Feb-2018 06:59:27
Advertisements