HOME HTML EDITOR C JAVA PHP

Java Methods: Handling Program Logic

In Java, a method is a collection of statements grouped together to perform a specific operation. It helps in making the code modular and easy to manage.

Did you know? Methods are the key to the DRY (Don't Repeat Yourself) principle. Instead of writing the same logic multiple times, you write it once in a method and call it whenever needed!

1. What is a Method in Java?

A Java method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.

There are two types of methods in Java:

2. Method Declaration

A method must be declared within a class. It is defined with the name of the method, followed by parentheses ().

Core components include:

3. Difference: Static vs Instance Methods

Choosing the right type of method depends on whether the logic belongs to the class or an individual object:

Static Method

Belongs to the class. Can be called without creating an object. Marked with the static keyword.

Instance Method

Belongs to the object. Requires an instance (object) of the class to be invoked.

Abstract Method

A method that has no implementation. It acts as a blueprint for subclasses to override.

4. Essential Method Concepts

Master these concepts to write efficient Java code:

  1. Method Overloading: Multiple methods having the same name but different parameters.
  2. Return Values: Using the return keyword to output a result back to the caller.
  3. Method Overriding: When a subclass provides a specific implementation for a method already defined in its parent class.
  4. Recursion: The technique of making a function call itself.

5. Comparison: Parameters vs Arguments

Feature Method Parameters Method Arguments
Definition Variables defined in the method signature. The actual values passed during the call.
Placement Inside the method header. Inside the calling statement.

6. Code Example

public class Calculator {
  // Defining a method with return type 'int'
  public int multiply(int a, int b) {
    return a * b;
  }

  public static void main(String[] args) {
    Calculator obj = new Calculator();
    // Calling the method
    int result = obj.multiply(5, 4);
    System.out.println("Result: " + result);
  }
}

Final Verdict

Understanding methods is the first step toward clean and professional code. They improve readability and make debugging much easier.

Next: Learn Java Classes & Objects →