Java Methods

Java methods are blocks of code that can be called to perform specific tasks or actions. Methods can be used to simplify complex code, reuse code, and make it more modular. In this tutorial, we will discuss the basics of Java methods and how to use them. Also, see Java Constructor with examples.

Method Syntax and Declaration

A Java method header is the first line of a method declaration and specifies the method’s name, return type, and parameter list. The general syntax of a method header is:

access_modifier return_type method_name(parameter_list) {
    // method body
   // return value
}

Let’s take a closer look at each component of the method header:

  1. Access modifier: This specifies the visibility of the method. It can be public, private, protected, or no modifier (also known as “default” access).
  2. Return type: This specifies the type of value that the method returns. If the method doesn’t return a value, the return type should be void.
  3. Method name: This is the name of the method. It should be a descriptive name that indicates what the method does.
  4. Parameter list: This is a comma-separated list of parameters that the method takes as input. Each parameter consists of a type and a name.

Here are some examples of method headers:

public int add(int num1, int num2) {
    // method body
}

private void printMessage(String message) {
    // method body
}

protected double calculateAverage(double[] numbers) {
    // method body
}

boolean isEven(int number) {
    // method body
}

In the above examples, the access modifiers are public, private, and protected, respectively. The return types are int, void, double, and boolean, respectively. The method names are add, printMessage, calculateAverage, and isEven, respectively. The parameter lists are (int num1, int num2), (String message), (double[] numbers), and (int number), respectively.

It’s important to note that the parameter list can be empty if the method doesn’t take any input. In that case, the method header would look like this:

public void methodName() {
    // method body
}

Java Method Naming Conventions

The naming convention of a method in Java follows the same guidelines as the naming convention for variables, which is known as camelCase.

According to the convention, the method name should begin with a lowercase letter, and the first letter of each subsequent word should be capitalized. There should be no spaces or underscores between words, and the name should be descriptive enough to indicate the function of the method.

For example, a method that calculates the area of a rectangle could be named “calculateArea” or “getRectangleArea”. It’s important to choose a meaningful name that accurately reflects the purpose of the method to make the code more readable and understandable.

In addition, it’s common practice to use verbs as method names, since methods are actions that perform specific tasks. For example, “calculate”, “print”, “display”, “get”, “set”, “add”, “remove”, and “validate” are all common verbs used as method names in Java programming.

Calling a Method

A method can be called by using its name followed by parentheses, which may contain arguments if the method requires them. Here is an example of how to call the add method:

int sum = add(5, 10);

In this example, we are calling the add method with arguments 5 and 10. The method will return the sum of the two numbers, which is stored in the sum variable.

Flow chart for a Java method call
java method calling
Complete code example
package method;

/**
 * Java method example
 * 
 * @author Mamun Kayum
 *
 */
public class JavaMethodExample {
	public static void main(String[] args) {
		JavaMethodExample example = new JavaMethodExample();
		// calling a method using class object
		example.callAdd();
	}

	public int add(int num1, int num2) {
		int result = num1 + num2;
		return result;
	}

	public void callAdd() {
		// calling a method from another
		int sum = add(5, 10);
		System.out.println("Sum is: " + sum);
	}
}

Types of Method

In Java, there are four types of methods: instance methods, static methods, abstract methods, and final methods. Each type of method serves a unique purpose and has specific characteristics.

  1. Instance methods

Instance methods are associated with an instance of a class and can access the class’s instance variables. They can also call other instance methods and modify the state of the object. To call an instance method, you need to create an instance of the class.

Example:

public class MyClass {
    int x = 5;

    public void instanceMethod() {
        System.out.println("This is an instance method. x = " + x);
    }

    public static void main(String[] args) {
        MyClass myObject = new MyClass();
        myObject.instanceMethod();
    }
}

Output:

This is an instance method. x = 5
  1. Static methods

Static methods are associated with a class and not an instance of a class. They cannot access instance variables and can only access static variables. They can be called using the class name without creating an instance of the class.

Example:

public class MyClass {
    static int x = 5;

    public static void staticMethod() {
        System.out.println("This is a static method. x = " + x);
    }

    public static void main(String[] args) {
        MyClass.staticMethod();
    }
}

Output:

This is a static method. x = 5
  1. Abstract methods

Abstract methods are declared in abstract classes or interfaces and do not have an implementation. They must be implemented by the class that extends the abstract class or implements the interface.

Example:

public abstract class MyAbstractClass {
    public abstract void abstractMethod();
}

public class MyClass extends MyAbstractClass {
    public void abstractMethod() {
        System.out.println("This is an abstract method.");
    }

    public static void main(String[] args) {
        MyClass myObject = new MyClass();
        myObject.abstractMethod();
    }
}

Output:

This is an abstract method.
  1. Final methods

Final methods cannot be overridden by a subclass. They are often used to ensure that a method cannot be changed by a subclass.

Example:

public class MyClass {
    public final void finalMethod() {
        System.out.println("This is a final method.");
    }

    public static void main(String[] args) {
        MyClass myObject = new MyClass();
        myObject.finalMethod();
    }
}

class MySubClass extends MyClass {
    // This method cannot override the finalMethod() in the superclass
}

Output:

This is a final method.

Understanding the different types of methods in Java is important for writing effective and efficient code. By selecting the appropriate method type for a specific task, you can improve the overall quality and maintainability of your code.

Method Overloading

Java allows you to define multiple methods with the same name but with different parameters. This is called method overloading. Java determines which method to call based on the number and types of arguments passed.

Example:

public int add(int num1, int num2){ 
    int result = num1 + num2; 
    return result; 
}

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

In this example, we have defined two methods with the same name, add. The first method takes two integer parameters, and the second method takes two double parameters. When we call the add method with integer parameters, Java will call the first add method, and when we call the add method with double parameters, Java will call the second add method.

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author