Skip to content

5.1. Method Declaration & Invocation

A method in Java is a collection of statements that perform a specific task. Methods allow code reuse and make programs more organized and manageable.

Method Declaration Syntax

java
accessModifier returnType methodName(parameterList) {
    // method body - statements
    return value; // if returnType is not void
}

Components of Method Declaration

Access Modifiers

  • public - Accessible from any other class
  • private - Accessible only within its own class
  • protected - Accessible within package and subclasses
  • (default) - Accessible only within the same package

Return Types

  • void - Method doesn't return any value
  • Primitive types - int, double, boolean, etc.
  • Reference types - String, Object, custom classes, etc.

Method Declaration Examples

Basic Method Declaration

java
public class MethodExamples {

    // Method with no parameters and no return value
    public void greet() {
        System.out.println("Hello, World!");
    }

    // Method with parameters and return value
    public int add(int a, int b) {
        return a + b;
    }

    // Method with String return type
    public String getFullName(String firstName, String lastName) {
        return firstName + " " + lastName;
    }

    // Static method - can be called without creating object
    public static void printMessage() {
        System.out.println("This is a static method");
    }
}

Method with Different Access Modifiers

java
public class AccessModifierDemo {

    // Public method - accessible from anywhere
    public void publicMethod() {
        System.out.println("Public method called");
    }

    // Private method - accessible only within this class
    private void privateMethod() {
        System.out.println("Private method called");
    }

    // Protected method - accessible within package and subclasses
    protected void protectedMethod() {
        System.out.println("Protected method called");
    }

    // Package-private (default) method - accessible within package
    void packagePrivateMethod() {
        System.out.println("Package-private method called");
    }

    // Public method that uses private method internally
    public void publicWrapper() {
        System.out.println("Calling private method from public method:");
        privateMethod();
    }
}

Method Invocation

Instance Method Invocation

java
public class Calculator {

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

    public double divide(double a, double b) {
        if (b == 0) {
            throw new IllegalArgumentException("Cannot divide by zero");
        }
        return a / b;
    }

    public void displayResult(String operation, double result) {
        System.out.println(operation + " result: " + result);
    }
}

// Using the Calculator class
public class CalculatorTest {
    public static void main(String[] args) {
        // Create an instance of Calculator
        Calculator calc = new Calculator();

        // Invoke instance methods
        int product = calc.multiply(5, 3);
        calc.displayResult("Multiplication", product);

        double quotient = calc.divide(10.0, 2.0);
        calc.displayResult("Division", quotient);
    }
}

Static Method Invocation

java
public class MathUtils {

    // Static method - belongs to class, not instance
    public static double calculateCircleArea(double radius) {
        return Math.PI * radius * radius;
    }

    public static boolean isEven(int number) {
        return number % 2 == 0;
    }

    public static String reverseString(String input) {
        return new StringBuilder(input).reverse().toString();
    }
}

// Using static methods
public class MathUtilsTest {
    public static void main(String[] args) {
        // Call static methods using class name
        double area = MathUtils.calculateCircleArea(5.0);
        System.out.println("Circle area: " + area);

        boolean even = MathUtils.isEven(10);
        System.out.println("Is 10 even? " + even);

        String reversed = MathUtils.reverseString("Hello");
        System.out.println("Reversed: " + reversed);
    }
}

Method Chaining

java
public class StringProcessor {
    private String value;

    public StringProcessor(String value) {
        this.value = value;
    }

    public StringProcessor toUpperCase() {
        this.value = this.value.toUpperCase();
        return this; // Return this for method chaining
    }

    public StringProcessor append(String text) {
        this.value += text;
        return this;
    }

    public StringProcessor reverse() {
        this.value = new StringBuilder(this.value).reverse().toString();
        return this;
    }

    public String getValue() {
        return value;
    }
}

// Using method chaining
public class MethodChainingDemo {
    public static void main(String[] args) {
        StringProcessor processor = new StringProcessor("hello");

        // Method chaining
        String result = processor.toUpperCase()
                               .append(" WORLD")
                               .reverse()
                               .getValue();

        System.out.println("Result: " + result); // Output: DLROW OLLEH
    }
}

Complete Example: Bank Account

java
public class BankAccount {
    private String accountNumber;
    private double balance;
    private String accountHolder;

    // Constructor
    public BankAccount(String accountNumber, String accountHolder, double initialBalance) {
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
        this.balance = initialBalance;
    }

    // Instance methods
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: $" + amount);
        } else {
            System.out.println("Deposit amount must be positive");
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: $" + amount);
        } else {
            System.out.println("Invalid withdrawal amount");
        }
    }

    public void transfer(BankAccount recipient, double amount) {
        if (amount > 0 && amount <= balance) {
            this.withdraw(amount);
            recipient.deposit(amount);
            System.out.println("Transferred: $" + amount + " to " + recipient.getAccountHolder());
        } else {
            System.out.println("Transfer failed: Insufficient funds or invalid amount");
        }
    }

    // Getter methods
    public double getBalance() {
        return balance;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public String getAccountHolder() {
        return accountHolder;
    }

    // Static method
    public static void displayBankInfo() {
        System.out.println("Welcome to Java Bank");
        System.out.println("Established: 2024");
    }
}

// Using the BankAccount class
public class BankDemo {
    public static void main(String[] args) {
        // Call static method
        BankAccount.displayBankInfo();

        // Create account instances
        BankAccount aliceAccount = new BankAccount("12345", "Alice", 1000.0);
        BankAccount bobAccount = new BankAccount("67890", "Bob", 500.0);

        // Invoke instance methods
        aliceAccount.deposit(200.0);
        aliceAccount.withdraw(150.0);
        aliceAccount.transfer(bobAccount, 100.0);

        System.out.println("Alice balance: $" + aliceAccount.getBalance());
        System.out.println("Bob balance: $" + bobAccount.getBalance());
    }
}

Best Practices

  1. Meaningful names: Use verbs that describe what the method does
  2. Single responsibility: Each method should do one thing well
  3. Proper access modifiers: Use the most restrictive access that works
  4. Document with comments: Use Javadoc for public methods
java
/**
 * Calculates the factorial of a non-negative integer
 * @param n the number to calculate factorial for
 * @return the factorial of n
 * @throws IllegalArgumentException if n is negative
 */
public static long factorial(int n) {
    if (n < 0) {
        throw new IllegalArgumentException("n must be non-negative");
    }
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}