Chapter 7: Methods in Java

Introduction to Methods

Sometimes our program grows in size and we want to separate the logic of main method to other methods.

For instance - If we are calculating average of a number pair 5 times, we can use methods to avoid repeating the logic.

DRY = Don't Repeat Yourself!

🔄 Code Reusability

Write once, use multiple times

📝 Better Organization

Separate logic into manageable chunks

🐛 Easier Debugging

Isolate and fix issues quickly

Syntax of a Method

A method is a function written inside a class.

Since Java is an Object Oriented language, we need to write the method inside some class.

Method Structure:

Method Syntax
returnType methodName(parameters) {
    // Method body
    return value; // if return type is not void
}

Example: Sum of Two Numbers

Calculator.java
public class Calculator {
    // Method that returns sum of two numbers
    int mySum(int a, int b) {
        int c = a + b;
        return c;
    }
    
    // Method with void return type
    void printMessage() {
        System.out.println("Hello from method!");
    }
    
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        
        int result = calc.mySum(5, 3);
        System.out.println("Sum: " + result);
        
        calc.printMessage();
    }
}

Calling a Method

A method can be called by creating an object of the class in which the method exists followed by the method call.

đŸ—ī¸
Object Creation
Calc obj = new Calc();
📞
Method Call
obj.mySum(a, b);
📋
Value Copy
Parameters are copied
â†Šī¸
Return Value
Result is returned

Important: The values from the method call (a and b) are copied to the parameters of the function. Thus even if we modify the values inside the method, the values in the main method will not change.

Exception: In case of Arrays, the reference is passed. Same is the case for Object passing to methods.

Static Keyword

static keyword is used to associate a method of a given class with the class rather than the object.

Static method in a class is shared by all the objects.

StaticExample.java
public class StaticExample {
    // Static method - belongs to class
    static int add(int a, int b) {
        return a + b;
    }
    
    // Non-static method - belongs to object
    int multiply(int a, int b) {
        return a * b;
    }
    
    public static void main(String[] args) {
        // Calling static method - no object needed
        int sum = StaticExample.add(5, 3);
        System.out.println("Sum: " + sum);
        
        // Calling non-static method - object needed
        StaticExample obj = new StaticExample();
        int product = obj.multiply(5, 3);
        System.out.println("Product: " + product);
    }
}

Method Overloading

Two or more methods can have same name but different parameters. Such methods are called Overloaded methods.

Note: Method overloading cannot be performed by changing the return type of methods.

MethodOverloading.java
public class MethodOverloading {
    // Overloaded methods with same name but different parameters
    
    void foo() {
        System.out.println("Method with no parameters");
    }
    
    void foo(int a) {
        System.out.println("Method with one parameter: " + a);
    }
    
    int foo(int a, int b) {
        System.out.println("Method with two parameters");
        return a + b;
    }
    
    void foo(String name) {
        System.out.println("Method with String parameter: " + name);
    }
    
    public static void main(String[] args) {
        MethodOverloading obj = new MethodOverloading();
        
        obj.foo();              // Calls first method
        obj.foo(10);            // Calls second method
        int result = obj.foo(5, 3);  // Calls third method
        obj.foo("Java");        // Calls fourth method
        
        System.out.println("Result: " + result);
    }
}

Variable Arguments (Varargs)

A function with varargs can be created in Java using the following syntax:

public static void foo(int... arr)

arr is available here as int[] arr

VarargsExample.java
public class VarargsExample {
    // Method with varargs
    public static void foo(int... arr) {
        System.out.println("Number of arguments: " + arr.length);
        for (int element : arr) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
    
    // Method with at least one parameter required
    public static void bar(int a, int... arr) {
        System.out.println("First parameter: " + a);
        System.out.println("Remaining parameters:");
        for (int element : arr) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        // foo can be called with zero or more arguments
        foo();
        foo(7);
        foo(7, 8, 9);
        foo(1, 2, 7, 8, 9);
        
        System.out.println("---");
        
        // bar requires at least one argument
        bar(1);
        bar(1, 2);
        bar(1, 7, 9, 11);
    }
}

Recursion

A function in Java can call itself. Such calling of function by itself is called recursion.

Example: factorial(n) = n × factorial(n-1)

RecursionExample.java
public class RecursionExample {
    // Recursive method to calculate factorial
    static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1;  // Base case
        } else {
            return n * factorial(n - 1);  // Recursive call
        }
    }
    
    // Recursive method to calculate Fibonacci
    static int fibonacci(int n) {
        if (n <= 1) {
            return n;  // Base case
        } else {
            return fibonacci(n - 1) + fibonacci(n - 2);  // Recursive call
        }
    }
    
    public static void main(String[] args) {
        int num = 5;
        System.out.println("Factorial of " + num + " = " + factorial(num));
        
        System.out.println("Fibonacci series:");
        for (int i = 0; i < 10; i++) {
            System.out.print(fibonacci(i) + " ");
        }
    }
}

Quick Quiz: Write a program to calculate factorial of a number using recursion in Java

Answer: The factorial method shown above demonstrates recursion. The method calls itself with (n-1) until it reaches the base case (n=0 or n=1).

Practice Set

Chapter 7 - Practice Set

1. Multiplication Table

Write a Java method to print multiplication table of a number n.

2. Star Pattern

Write a program using functions to print the following pattern:
*
**
***
****

3. Sum of Natural Numbers

Write a recursive function to calculate sum of first n natural numbers.

4. Reverse Star Pattern

Write a function to print the following pattern:
****
***
**
*

5. Fibonacci Series

Write a function to print nth term of fibonacci series using recursion.

6. Average Calculator

Write a function to find average of a set of numbers passed as arguments.

7. Temperature Converter

Write a function to convert Celsius temperature into Fahrenheit.

8. Iterative Approach

Repeat problem 3 using iterative approach.

Sample Solution: Multiplication Table

← Previous: Arrays Next: OOPs →