Skip to content

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.

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)
int result = calculateSum(5, 3); // result = 8
  • 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 method
int sum = MathHelper.add(5, 3);
  • 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 methods
Calculator calc = new Calculator();
calc.store(10);
int value = calc.recall(); // value = 10
  • 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 5
System.out.println(sb); // "Hello World"

A method that calls itself:

public int factorial(int n) {
if (n <= 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive case
}
  1. Single Responsibility: A method should do one thing well
  2. Descriptive Names: Method names should clearly describe what they do
Built with passion by Ngineer Lab