Methods In Java

In Java, a method serves the purpose of executing a particular task, contributing to the simplification and reusability of the program.

What Is a Method in Java?

A function is a segment of code containing a series of statements or a block of code that is organized to carry out a specific task or function. Its purpose is to promote the ability to reuse code. By defining a function once, it can be utilized multiple times without the need to rewrite the code repetitively. Additionally, it facilitates simple alterations and enhances the clarity of the code by simply adding or eliminating a portion of code. The function is executed solely upon being called or invoked.

One of the pivotal methods in Java is the main function. For further information on the main method, please visit the following resource: Java Main Method.

Advantages of Using Methods

The following are the advantages of using methods in Java:

  • Reusability: Methods provide code reusability. Once a method is defined, it can be called multiple times from various parts of the program.
  • Modularity: Methods help break down complex problems into smaller, manageable pieces.
  • Maintainability: With methods, updating and debugging code becomes easier since changes in one part of the program do not necessarily impact other parts.
  • Abstraction: Methods provide a way to encapsulate implementation details, exposing only the necessary parts to the users.
  • Method Naming Rules

When creating a method, it is important to follow naming conventions. The method's name should begin with a lowercase letter and be a verb. If the method name consists of multiple words, the first word should be a verb followed by an adjective or noun. Each word in the method name should start with a capital letter, except for the first word. For instance:

Single-Word Method Name: sum, area

Method Naming with Multiple Words: calculateCircleArea, compareStrings

Another scenario that can occur is when a method shares its name with another method within the same class, which is referred to as method overloading.

To read more Java Naming Convention

Method Declaration

The method declaration contains details regarding method characteristics like access level, output type, method name, and parameters. It consists of six elements referred to as the method header, as illustrated in the figure below.

Method Signature

Each method is defined by its method signature, which is an essential part of its declaration. The method signature consists of the method's name and its parameter list.

Access Specifier

Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifiers:

  • public: The method is accessible to all classes when we use the public specifier in our application.
  • private: When we use a private access specifier, the method is accessible only in the classes in which it is defined.
  • protected: When we use a protected access specifier, the method is accessible within the same package or subclasses in a different package.
  • default: When we do not use any access specifier in the method declaration, Java uses the default access specifier by default. It is visible only from the same package.
  • Return Type

The return type in programming refers to the data type that a method gives back. It can be a primitive data type, an object, a collection, void, and so on. When a method doesn't yield any value, we specify it with the void keyword.

Method Name

A method is identified by a distinct name that characterizes its functionality. For instance, when developing a method to subtract two numbers, it is essential to name it appropriately like subtraction. The method is called into action based on its designated name.

Parameter List

The parameter list consists of various parameters delineated by commas and enclosed within a set of parentheses. Each parameter includes the data type along with the variable name. In case the method does not have any parameters, the parentheses should be left empty.

Method Body

It is an integral component of the method declaration, encompassing all the tasks to be executed, enclosed by curly braces.

The content of the method is encapsulated within curly braces {} and comprises the instructions that establish the behavior or operation of the method. For instance, let’s examine the subsequent code excerpt.

Example

public class Example {

    // Method definition

    public int add(int a, int b) {

        int sum = a + b; // Method body

        return sum; // Return statement

    }

}

Types of Methods

In Java, there exist two categories of methods:

  • Predefined Method
  • User-defined Method

To read more Types of Methods in Java

1. Predefined Method

Predefined methods in Java class libraries refer to the methods that have already been defined. They are also called standard library methods or built-in methods. These methods can be easily utilized in a program by simply invoking them at any stage.

Predefined methods such as String.length, String.equals, String.compareTo, Math.sqrt, Math.pow, and more are available for use in programming.

Executing a predefined method in our program triggers the execution of a set of code associated with that specific method in the background.

Example

Example

public class Main {

  public static void main(String[] args) {

    // pow() is an in-built function defined in the Math class

    System.out.println("2 raised to the power of 5 is: " + Math.pow(2, 5));

  }

}

Output:

Output

2 raised to the power of 5 is: 32.0

2. User-Defined Method

A method created by a user or developer is referred to as a user-defined method. User-defined methods are adjustable and can be tailored to meet specific needs.

Calling User defined Method

In the Java programming language, the way a method is called or invoked is determined by its classification as either static or non-static.

When a method is declared as static, it can be invoked directly by referencing the class name or within the same class itself. It's important to remember that even for static methods, an object still needs to be created in order to make the method call.

Syntax

It has the following syntax:

Example

static void display() {

// code

} 

Empolyee.display(); // no need to create an object

When dealing with a non-static method, it is necessary to instantiate an object of the class and utilize it to invoke the method.

Please remember that attempting to invoke a non-static method from a static context without an object will result in a compile-time error. Non-static methods are associated with instances rather than the class directly.

Example

Empolyee emp = new Empolyee();

emp.display(); // method called using object reference

Example

Consider the following example illustrating the process of invoking a custom function in Java.

Example

public class Main {

	// Static method

	static void greet() {

		System.out.println("Hello from the static method!");

	}

	// Non-static method

	void farewell() {

		System.out.println("Goodbye from a non-static method!");

	}

	public static void main(String args[]) {

		Main obj = new Main();

		obj.farewell(); //calling non-static method

		Main.greet(); //calling static method

	}

}

Output:

Output

Goodbye from a non-static method!

Hello from the static method!

Input Required

This code uses input(). Please provide values below: