Methods in Java

A method is a block of code that performs a specific task. It is a set of instructions that can be called or invoked to perform an action. They are also called functions.

The signature of a method in Java consists of the method name and the parameter list. It helps to uniquely identify and differentiate one method from another. The return type is not part of the method signature.

The general syntax of a method signature in Java is as follows:

accessModifier returnType methodName(parameterList)

Let's break down each component of the method signature:

  • accessModifier: The access modifier are used to control the visibility and accessibility of methods from other parts of the program.
  • returnType: The return type specifies the type of value that the method will return after performing its task. It can be any valid data type in Java, or it can be void if the method does not return any value.
  • methodName: The method name is a unique identifier for the method. It should be chosen descriptively to indicate the purpose or action performed by the method.
  • parameterList: The parameter list is a comma-separated list of parameters enclosed within parentheses. Each parameter consists of the parameter type followed by the parameter name. Parameters are optional and can be used to pass data into the method for processing.

Here is an example of a method signature:

public double sum(double num1, double num2)

In this example, the method signature consists of:

  • accessModifier: public
  • returnType: double (the method returns a double data type value)
  • methodName: sum
  • parameterList: (double num1, double num2) (two double parameters named num1 and num2)


Creating Methods in Java

In Java, methods can be created with a return type or be declared as void, indicating whether they return a value or not. 

When deciding on the access modifier for a method in Java, you need to consider the desired visibility and access level for the method. A method declared with the public access modifier can be invoked from anywhere in the program. A method declared with the protect access modifier is accessible within its own class, subclasses (even if they are in different packages), and other classes within the same package. A method with private access modifier is accessible only within the class where it is declared and not accessible from any other classes, even subclasses or classes in the same package. A method with default access modifier is accessible only within the same package. To declared with default access modifer, create a method without access modifier.

A return type method is declared with a specific data type (e.g., int, double, String) that indicates the type of value it will return. The method uses the return keyword followed by an expression to return a value of the specified type. The calling code can assign the returned value to a variable or use it in further calculations or operations.

Here is an example of how you can create methods with Return Type in Java:

public double sum(double num1, double num2) {
   double result = num1 + num2;
   return result;
}

In the above example, the public keyword makes the method accessible from anywhere in the program code. The method is named sum and has a return type of double, which means it will return a value of type double. It takes two parameters of type double named num1 and num2.

Inside the method, the two input numbers (num1 and num2) are added together and the result is stored in a variable called result. Finally, the result variable is returned using the return keyword.

To use this method, you can call it from another part of your code, providing two double values as arguments. The method will perform the addition and return the result as a double value.

Example:

public class Sample {

   public static void main(String[] args) {

	Sample sample = new Sample();

	double sumResut = sample.sum(10, 14);
	System.out.println(sumResut);

   }

   public double sum(double num1, double num2) {
	double result = num1 + num2;
	return result;
   }

}

Output:

24.0


A void method does not have a return type, which means it does not return any value. The method performs a task, such as displaying output, modifying data, or executing a series of steps. It does not use the return keyword or provide a value after the method's execution. The calling code simply invokes the method and continues with the next instruction.

Here's an example of a method with void return type:

public void greet(String message, String name) {
   String finalMessage  = String.format(message, name);
   System.out.println(finalMessage);
}

The example method shown above is declared with the public keyword, which allows it to be accessed from any part of the program code. The method is named greet and has a return type of void, which means it does not return any value. It takes two parameters: message, which is a String representing a greeting message template, and name, which is a String representing the name of the person being greeted.

Inside the method, a new String variable called finalMessage is declared. The String.format method is used to combine the message template with the name parameter, resulting in a formatted greeting message. The formatted message is then assigned to the finalMessage variable.

Finally, the finalMessage is printed to the console using the System.out.println method, which displays the greeting message.

To use this method, you can call it from another part of your code, passing a greeting message template and a name as arguments. The method will format the message with the provided name and print it to the console.

Example:

public class Sample {

   public static void main(String[] args) {

      Sample sample = new Sample();

      sample.greet("Hello, %s! Welcome to Hello Universe.", "Jake");
   }

   public void greet(String message, String name) {
      String finalMessage = String.format(message, name);
      System.out.println(finalMessage);
   }

Output:

Hello, Jake! Welcome to Hello Universe.


Use Return Type or Void Method?

You should use a return type method when you need to perform a computation and provide a result back to the calling code for further use or processing.

You should use a void method when you need to perform an action, modify data, or execute a sequence of steps without returning a specific value.


Method Types in Java

In Java, methods can be classified into several types based on their characteristics and usage. Here are some commonly recognized types of methods:

Method TypeDescription
Instance Methods
Instance methods are associated with objects of a class. They operate on the specific instance variables and can access other instance methods and variables of the same class. Instance methods are invoked on an instance of the class using the dot notation (objectName.methodName()).
Static Methods
Static methods belong to the class itself rather than individual instances. They can be called directly on the class itself without creating an instance. Static methods cannot access instance variables or methods directly, but they can access other static methods and static variables.
Getter and Setter Methods
Getter methods, also known as accessor methods, are used to retrieve the values of private instance variables. Setter methods, also known as mutator methods, are used to modify or set the values of private instance variables. They provide controlled access to the private fields of a class.
Constructor Methods
Constructor methods are special methods used to initialize objects of a class. They have the same name as the class and are called implicitly when an object is created using the new keyword. Constructors can have parameters or be parameterless.
Overloaded Methods
Overloaded methods are methods with the same name but different parameter lists within the same class. They allow multiple methods with the same name to perform different operations based on the type, number, or order of parameters.
Recursive Methods
Recursive methods are methods that call themselves, either directly or indirectly, to solve a problem by breaking it down into smaller subproblems. They typically have a base case that terminates the recursion and one or more recursive calls that solve the smaller subproblems.
Abstract Methods
Abstract methods are declared in abstract classes or interfaces but do not have a method body. They provide a contract for the subclasses or implementing classes to define their own implementation of the method.
Final Methods
Final methods cannot be overridden by subclasses. They are declared with the final modifier to prevent any modification in the method implementation.
Varargs Methods
Varargs methods allow a variable number of arguments to be passed to the method. They are declared using an ellipsis (...) in the method parameter, and the arguments are treated as an array within the method.

These are some of the common types of methods in Java, each serving a specific purpose and providing different functionality within a class or program.


Invoking Methods in Java

To invoke or call a method in Java, do the following:

  • Identity the name of the method you want to call. Make sure you know the method's name and the parameters it expects (if any).
  • Identify the object or class on which the method is defined. Methods are associated with either an object (instance methods) or a class (static methods). You need to determine whether the method is an instance method or a static method.

Invoke the method using the appropriate syntax:

To invoke an instance method, create an object (instance) of the class if the method is an instance method. Use the object name, followed by a dot (.) operator, to call the method. Provide the necessary arguments (if any) within parentheses.

Example:

ExampleClass obj = new MyClass(); // Create an object of MyClass
obj.myMethod(); // Call the instance method myMethod()


To invoke static method, call it directly on the class itself, without creating an instance. Use the class name, followed by a dot (.) operator, to call the static method. Provide the necessary arguments (if any) within parentheses.

Example:

ExampleClass .myStaticMethod(); // Call the static method myStaticMethod()

Make sure that the method you are invoking is visible and accessible from the current scope (based on its access modifier). Also, ensure that the method name, parameters, and return type match the method's declaration.

By following these steps, you can successfully invoke methods in Java to execute their code and accomplish specific tasks in your program.