Methods

In Java, a method is a set of instructions that performs a specific task. Methods are used to break down large programs into smaller, more manageable pieces. They also make programs more modular and easier to understand. Here is a tutorial on Java methods:

Defining a Method

To define a method, you must specify its name, return type, and parameter list (if any). Here is the basic syntax for defining a method:

returnType methodName(parameterList) {
  // method body
  return returnValue;
}

Here is an example of a method that takes two integers as parameters and returns their sum:

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

Calling a Method

To call a method, you must specify its name and pass in any required parameters. Here is the basic syntax for calling a method:

returnType result = methodName(argumentList);

Here is an example of calling the sum method defined earlier:

int a = 5;
int b = 7;
int result = sum(a, b);
System.out.println(result);
public static void greet(String name) {
  System.out.println("Hello, " + name + "!");
}

This method can be called from anywhere in the program.

Overloading Methods

In Java, you can define multiple methods with the same name as long as they have different parameter lists. This is called method overloading. Here is an example:

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

public static int sum(int a, int b, int c) {
return a + b + c;
}

These two methods have the same name, but they take different numbers of parameters. You can call each method with the appropriate number of arguments.

int a = 5;
int b = 7;
int c = 10;

int result1 = sum(a, b);
int result2 = sum(a, b, c);

System.out.println(result1);
System.out.println(result