Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Methods and Recursion

Methods are one of the most important building blocks in Java. They allow developers to break large programs into smaller, manageable, and reusable pieces of code. By using methods, a program becomes easier to understand, test, debug, and maintain. Methods also promote code reusability and follow the principle of modular programming.


1. Method Declaration and Definition

Description

A method is a block of code that performs a specific task and is executed only when it is called. In Java, a method must be declared with a name, return type, and parameters (optional). The method definition contains the actual implementation of the logic.

General Syntax

accessModifier returnType methodName(parameters) {
    // method body
}

Components of a Method

  • Access Modifier – Defines visibility (public, private, protected)
  • Return Type – Specifies the type of value returned (int, String, void, etc.)
  • Method Name – Identifier used to call the method
  • Parameters – Input values passed to the method
  • Method Body – Contains executable statements

Example

public static void greet() {
    System.out.println("Welcome to Java Programming");
}

Explanation

The method greet() does not take any parameters and does not return any value. It simply prints a message.


2. Method Parameters and Return Types

Description

Parameters are variables used to receive values from the calling method. Return types specify what type of value a method sends back after execution.


Method with Parameters

public static void add(int a, int b) {
    System.out.println(a + b);
}

Method with Return Type

public static int multiply(int x, int y) {
    return x * y;
}

Explanation

  • add() accepts two integers and prints their sum.
  • multiply() accepts two integers and returns their product.

Types of Return Values

  • Primitive valuesint, double, boolean
  • Reference valuesString, arrays, objects
  • void – No value returned

3. Method Overloading

Description

Method overloading allows multiple methods with the same name but different parameter lists within the same class. It improves readability and flexibility.

Rules for Method Overloading

  • Method name must be the same
  • Parameters must differ in number, type, or order
  • Return type alone cannot differentiate methods

Example

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

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

public static int sum(int a, int b, int c) {
    return a + b + c;
}

Explanation

The sum() method behaves differently based on the number and type of parameters passed.


4. Variable Arguments (Varargs)

Description

Varargs allow a method to accept zero or more arguments of the same type. This is useful when the number of arguments is not fixed.

Syntax

returnType methodName(dataType... variableName)

Key Points

  • Internally treated as an array
  • Only one varargs parameter allowed
  • Must be the last parameter

Example

public static int addNumbers(int... numbers) {
    int sum = 0;
    for (int num : numbers) {
        sum += num;
    }
    return sum;
}

Method Call

System.out.println(addNumbers(10, 20));
System.out.println(addNumbers(1, 2, 3, 4, 5));

5. Recursion

Description

Recursion is a programming technique in which a method calls itself to solve a problem. It is commonly used to solve problems that can be broken down into smaller sub-problems.

Key Components of Recursion

  • Base Condition – Stops recursive calls
  • Recursive Call – Method calls itself

Example: Factorial Calculation

public static int factorial(int n) {
    if (n == 0) {
        return 1;
    }
    return n * factorial(n - 1);
}

Explanation

The method keeps calling itself until the base condition (n == 0) is met.


6. Applications of Recursion

Common Use Cases

  • Factorial calculation
  • Fibonacci series
  • Tree and graph traversal
  • Searching and sorting algorithms
  • Divide and conquer algorithms

Example: Fibonacci Series

public static int fibonacci(int n) {
    if (n <= 1) {
        return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

7. Recursion vs Iteration

FeatureRecursionIteration
Code LengthShortLonger
Memory UsageHigh (stack)Low
PerformanceSlowerFaster
ComplexityEasy to understandSometimes complex

Example:

java

public class MethodsDemo {
    // Simple method
    public static void greet(String name) {
        System.out.println("Hello, " + name);
    }
    
    // Method with return type
    public static int add(int a, int b) {
        return a + b;
    }
    
    // Method overloading
    public static int multiply(int a, int b) {
        return a * b;
    }
    
    public static double multiply(double a, double b) {
        return a * b;
    }
    
    // Varargs
    public static int sum(int... numbers) {
        int total = 0;
        for (int num : numbers) {
            total += num;
        }
        return total;
    }
    
    // Recursion - Factorial
    public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        }
        return n * factorial(n - 1);
    }
    
    public static void main(String[] args) {
        greet("Alice");
        System.out.println("Sum: " + add(5, 3));
        System.out.println("Product: " + multiply(4, 5));
        System.out.println("Sum of multiple: " + sum(1, 2, 3, 4, 5));
        System.out.println("Factorial of 5: " + factorial(5));
    }
}

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥