Methods Basics in Java
Introduction
In Java, a method is a block of code grouped together to perform a specific operation. Methods allow you to break down complex logic into small, manageable, and reusable pieces. They form the behavior of objects and classes in Java's object-oriented paradigm.
Writing good methods is the foundation of the DRY (Don't Repeat Yourself) principle, ensuring your code is modular, readable, and easy to test.
Method Anatomy
A standard Java method declaration consists of several components:
public static int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
- Access Modifier (
public): Dictates who can call the method (e.g.,public,private,protected, or default). - Non-Access Modifier (
static): Optional.staticmeans the method belongs to the class itself, rather than an instance of the class. - Return Type (
int): The data type the method gives back. Usevoidif it returns nothing. - Method Name (
addNumbers): Should be a verb, written incamelCase. - Parameter List (
int a, int b): Variables passed into the method. Can be empty. - Method Body (
{ ... }): The actual code executed when the method is called. - Return Statement (
return sum;): Ends method execution and passes the value back to the caller (mandatory if return type is notvoid).
Static vs. Instance Methods
Instance Methods
Instance methods belong to an object (an instance of a class). You must create an object using the new keyword to call them. They can access both instance variables and static variables.
public class Car {
public void startEngine() {
System.out.println("Engine started.");
}
}
// Usage:
// Car myCar = new Car();
// myCar.startEngine();
Static Methods
Static methods belong to the class itself. You don't need to instantiate an object to call them. They cannot access instance variables directly, only static variables.
public class MathUtils {
public static int square(int num) {
return num * num;
}
}
// Usage:
// int result = MathUtils.square(5);
Parameters: Pass-by-Value
One of the most critical concepts in Java is how it passes arguments to methods. Java is strictly pass-by-value.
1. Passing Primitives
When you pass a primitive type (like int, double), Java passes a copy of the value. Changing the value inside the method does not affect the original variable.
public void modifyNumber(int num) {
num = 100; // Only modifies the local copy
}
2. Passing Objects (References)
When you pass an object, Java passes a copy of the reference to that object.
- Modifying the object's internal state (e.g., changing an attribute) will affect the original object.
- Reassigning the reference to a completely new object will not affect the original reference.
public void modifyArray(int[] arr) {
arr[0] = 99; // THIS AFFECTS THE ORIGINAL ARRAY!
arr = new int[]{1, 2, 3}; // This reassignment does NOT affect the original array
}
Variable Arguments (Varargs)
Introduced in Java 5, varargs allow a method to accept zero or multiple arguments of the same type. It is treated as an array inside the method body.
public void printNames(String... names) {
for (String name : names) {
System.out.println(name);
}
}
// Usage:
// printNames("Alice");
// printNames("Bob", "Charlie", "Dave");
Rule: Varargs must be the last parameter in the method signature, and you can only have one varargs parameter per method.
Summary
- Methods encapsulate behavior and promote code reuse.
- Understand the difference between instance and static methods based on state requirements.
- Java is strictly pass-by-value; passing objects passes a copy of the reference pointing to the heap.
- Use meaningful names, keep methods small (single responsibility), and document inputs/outputs clearly.