Chapter - 5 Methods

5.1 Introduction to Methods

  • Methods: Blocks of reusable code that perform specific tasks.
  • Purpose: Improves code modularity and reusability.

Syntax of a Method

modifier returnType methodName(parameters) {
    // Method body
    return value; // Optional if returnType is void
}

Example

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

Components of a Method

  1. Modifier: Determines access level (e.g., public, private).
  2. Return Type: Specifies the type of value returned (int, void, etc.).
  3. Method Name: Identifier for the method.
  4. Parameters: Inputs passed to the method.
  5. Method Body: Contains executable code.

5.2 Defining and Calling Methods

  • Define methods in the same class or another class.
  • Use the method name to call a method, passing arguments if necessary.

Example

public class MethodExample {
    public static void main(String[] args) {
        int result = multiply(4, 5);
        System.out.println(“Result: ” + result);
    }
 
    public static int multiply(int a, int b) {
        return a * b;
    }
}
Output: Result: 20

5.3 Passing Arguments

Pass by Value

  • Java passes arguments by value, copying the variable’s value.
  • Changes to parameters do not affect the original variable.

Example

public static void main(String[] args) {
    int x = 10;
    modifyValue(x);
    System.out.println(x); // Output: 10
}
 
public static void modifyValue(int num) {
    num = 20;
}

5.4 Return Statements

  • Return Type: Specifies the type of value returned.
  • Use the return keyword to send a value back to the calling method.

Example

public static double calculateArea(double radius) {
    return 3.14 * radius * radius;
}

5.5 Void Methods

  • Void Methods: Do not return any value.
  • Use void as the return type.

Example

public static void printMessage() {
    System.out.println(“Hello, World!”);
}

5.6 Method Overloading

  • Overloaded Methods: Methods with the same name but different parameter lists.
  • Enables multiple methods with different argument types or counts.

Example

public static int add(int a, int b) {
    return a + b;
}
 
public static double add(double a, double b) {
    return a + b;
}

Calling Overloaded Methods

int sum1 = add(5, 10);       // Calls the int version
double sum2 = add(3.5, 4.5); // Calls the double version

5.7 Scope of Variables

  • Local Variables: Declared inside a method; accessible only within that method.
  • Class Variables: Declared outside methods but within the class.

Example

public class VariableScope {
    static int classVariable = 10; // Class variable
 
    public static void main(String[] args) {
        int localVariable = 20; // Local variable
        System.out.println(localVariable + classVariable);
    }
}

5.8 Static vs Instance Methods

Static Methods

  • Called without creating an object of the class.
  • Defined using the static keyword.

Example

public class StaticExample {
    public static void greet() {
        System.out.println(“Hello, Static World!”);
    }
}
 
StaticExample.greet();

Instance Methods

  • Require an object to be called.

Example

public class InstanceExample {
    public void greet() {  System.out.println(“Hello, Instance World!”);
    }
}
InstanceExample obj = new InstanceExample();
obj.greet();

5.9 Recursive Methods

  • Methods that call themselves.
  • Useful for problems that can be divided into smaller subproblems (e.g., factorial, Fibonacci).
Example: Factorial
public static int factorial(int n) {
    if (n == 1) {
        return 1;
    }
    return n * factorial(n – 1);
}
Explanation
  1. Base case: Stops recursion when n == 1.
  2. Recursive call: Multiplies n with the result of factorial(n – 1).

5.10 Best Practices for Methods

  1. Use meaningful method names.
  2. Keep methods short and focused on a single task.
  3. Use comments to explain the purpose of the method.
  4. Avoid global variables; pass parameters instead.
  5.  Test methods independently to ensure correctness

Summary

  • Methods encapsulate reusable code and improve program structure.
  • Method overloading, recursion, and proper use of parameters enhance flexibility.
  • Differentiating between static and instance methods is essential for effective object-oriented programming
 

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.