Java Methods

What is Method in Java?

In Java, a method is a block of code that defines the behavior or actions that an object or class can perform. It is one of the fundamental structure blocks of object-oriented programming in Java and is used to encapsulate a specific functionality or set of operations. Methods allow you to achieve actions, manipulate data, and execute algorithms within classes.

Method Declaration

Method declarations generally consist of 6 components:

  1. Modifier: It specifies the method’s access type. i.e. from where it can be accessed in your application. In Java, we have 4 types of access specifications:
  •  public: it is accessible in all classes in your application.
  • protected: It is available within the defined class and any of its subclasses.
  •  private: It is only accessible inside the class where it is defined.
  •  default: It is declared/defined without using any modifier. It can be accessed within the same class and package that its class is defined.
  1. Return type: The return type specifies the data type of the value returned by the method, or it’s void if it doesn’t return a value. It is Mandatory in syntax.
  2. Method Name: The rules for field names also apply to method names, but the convention is a little different. In syntax, it is mandatory.
  3. Parameter list: The enclosed parentheses defines a comma-separated list of the input parameters, preceded by their data type. If there are no parameters, it is necessary to use empty parentheses (). It is not mandatory in syntax.
  4. Exceptions List: The exceptions you expect the method to throw away, you can specify those exceptions(s). It is not mandatory in syntax.
  5. Method body: It is enclosed in brackets. To perform your intended operations, you need to execute the code. It is not mandatory in syntax.

Create a Method

Here is an example to explain the syntax of a method:

Syntax:

public int methodName() {

// body

}

Here,

  • public − modifier
  • int− return type
  • methodName− the name of the method

The method definition consists of one method heading and one method body. The fundamental Java method syntax is as follows:

accessModifier returnType methodName() {

// Method body – the code that defines the behavior of the method

// It can include any valid Java statements and expressions

// Optionally, it may return a value using the “return” keyword if the returnType is not “void”

}

Let’s break down the components:

  1. accessModifier: This is an optional keyword that determines the visibility of the method. In Java, there are four access modifiers.It can be one of the following: public, private, protected, or default(no access modifier specified).
  2. returnType: The data type of the value that the method returns. If the method does not return any value, the void keyword is used.
  3. methodName: The name of the method. It follows the same naming conventions as variable names (e.g., camelCase).

Example of a simple method in Java:

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

Explanation:

  1.  We have a class called MyClass with a static method named printMessage().
  2. The printMessage() method is defined with the static keyword, indicating that it is a static method and doesn’t require an instance of the class to be called.
  3. The method’s return type is void, meaning it doesn’t return any value.
  4. All that is printed in the method body is the phrase “This is a static method.”

Call a Method

In Java, method-calling statements are used to execute a method defined within a class. When you call a method, you are essentially instructing the program to execute the code inside that method, and it may or may not return a value depending on the method’s return type. Let’s explore how method-calling statements work:

The syntax to call a method in Java is as follows:

methodName();

Explanation:

  1. methodName: This is the name of the method you want to call. It should match the method’s defined name in the class.
  2. ‘()'(parentheses): The empty parentheses indicate that the method doesn’t take any arguments. When calling a method without arguments, you still need to include the empty parentheses to invoke the method.

Let’s consider a simple Java class with a method that doesn’t take any arguments:

public class MyClass {
    // This is a static method without arguments.
    public static void printMessage() {
        System.out.println("This is a static method.");     
    }

    public static void main(String[] args) {
        // Call the static method directly without instantiation
        printMessage();
    }
}

Explanation:

  1. We have a class called MyClass with a static method named printMessage().
  2. The printMessage() method is defined with the static keyword, indicating that it is a static method.
  3. The method doesn’t have any parameters or arguments, denoted by empty parentheses ‘()’. This means the method does not require any input values to perform its task.
  4. The method’s return type is void, meaning it doesn’t return any value.
  5. The method body simply prints the message “Hello, welcome!” to the console.
  6. In the main method, we directly call the static method printMessage() without creating an instance of MyClass. We can do this because static methods are associated with the class itself and can be called directly using the class name.

Output:

This is a static method.

Using methods in Java has several advantages, such as:

  1. Reusability: Methods enable writing code once and using it multiple times, enhancing code modularity and ease of maintenance.
  2. Abstraction: Methods abstract complex logic, providing a simple interface for others to use. This improves code readability and comprehension.
  3. Readability Improvement: Breaking code into smaller, well-named methods enhances readability and comprehension.
  4. Encapsulation: Methods encapsulate complex logic and data, simplifying code management and maintenance.
  5. Separation of Concerns: Employing methods allows separating different code parts, assigning distinct responsibilities to different methods, and improving code organization.
  6. Enhanced Modularity: Methods promote breaking code into smaller, manageable units, leading to improved code modularity.
  7. Improved Testability: Organizing code into smaller units facilitates easier testing and debugging.
  8. Performance Improvement: Well-structured methods can enhance performance by reducing code execution overhead and enabling better code caching and optimization.

 

Visited 1 times, 1 visit(s) today

Comments are closed.

Close