Methods
This content is for Java. Switch to the latest version for up-to-date documentation.
Methods are blocks of code that perform specific tasks. They help organize code, enable reuse, and provide abstraction.
Method Declaration
Section titled “Method Declaration”public int calculateSum(int a, int b) { return a + b;}A method declaration includes:
- Access modifier (
public) - Return type (
int) - Method name (
calculateSum) - Parameters (
int a, int b) - Method body (code between curly braces)
Method Invocation
Section titled “Method Invocation”int result = calculateSum(5, 3); // result = 8Static vs. Instance Methods
Section titled “Static vs. Instance Methods”Static Methods
Section titled “Static Methods”- Belong to the class rather than objects
- Called using the class name
- Cannot access instance variables directly
public class MathHelper { public static int add(int a, int b) { return a + b; }}
// Calling a static methodint sum = MathHelper.add(5, 3);Instance Methods
Section titled “Instance Methods”- Belong to objects of the class
- Require an instance to be called
- Can access instance variables
public class Calculator { private int memory;
public void store(int value) { memory = value; }
public int recall() { return memory; }}
// Using instance methodsCalculator calc = new Calculator();calc.store(10);int value = calc.recall(); // value = 10Method Parameters
Section titled “Method Parameters”Parameter Passing
Section titled “Parameter Passing”- Primitive types are passed by value (a copy is passed)
- Objects are passed by reference value (a copy of the reference is passed)
public void modifyValues(int number, StringBuilder text) { number = 100; // Only modifies the local copy text.append(" World"); // Modifies the actual object}
int n = 5;StringBuilder sb = new StringBuilder("Hello");modifyValues(n, sb);
System.out.println(n); // Still 5System.out.println(sb); // "Hello World"Method Recursion
Section titled “Method Recursion”A method that calls itself:
public int factorial(int n) { if (n <= 1) { return 1; // Base case } return n * factorial(n - 1); // Recursive case}Best Practices
Section titled “Best Practices”- Single Responsibility: A method should do one thing well
- Descriptive Names: Method names should clearly describe what they do