What are methods in Java?

A Java method is a collection of statements that are grouped together to perform an operation.

When you call the System.out.println()method, for example, the system actually executes several statements in order to display a message on the console.


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.


Following code demonstrates how to write a method in Java. This method takes two parameters num1 and num2 and returns the maximum between the two −

public static int minFunction(int n1, int n2) {
   int min;
   if (n1 > n2)
      min = n2;
      min = n1;
   return min;