methods
What is a Method?
A method is a named, reusable block of code that performs a specific task. You've already used one: main, and System.out.println() is also a method. Instead of repeating the same logic everywhere, you write it once inside a method and call it whenever you need it.
Method Syntax
returnType methodName(parameterType parameterName) {
// method body
return value; // only needed if returnType is not void
}A Simple Example
public class Calculator {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println(result); // 8
}
}Void Methods
If a method doesn't need to return anything, its return type is void.
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// calling it:
greet("Alice"); // prints: Hello, Alice!Parameters vs Arguments
These terms are often used interchangeably, but technically:
- Parameters are the variables listed in the method's definition:
(int a, int b) - Arguments are the actual values passed in when calling the method:
add(5, 3)
Method Overloading
Java allows multiple methods with the same name as long as their parameter lists are different (different number or types of parameters). This is called overloading.
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}Java figures out which version to call based on the arguments you provide.
Returning Values
static boolean isEven(int number) {
return number % 2 == 0;
}
static String describe(int number) {
if (isEven(number)) {
return number + " is even";
} else {
return number + " is odd";
}
}Static vs Instance Methods
A static method belongs to the class itself and can be called without creating an object. An instance method belongs to individual objects and requires you to create an object first (covered in the next topic on classes).
// Static method — called directly on the class
Math.max(5, 10);
// Instance method — called on an object
String text = "hello";
text.toUpperCase(); // instance method on a String objectWhy Use Methods?
| Benefit | Explanation |
|---|---|
| Reusability | Write the logic once, use it everywhere |
| Readability | Well-named methods make code self-documenting |
| Maintainability | Fix a bug in one place instead of many |
| Organization | Break complex problems into smaller, manageable pieces |
Coming up next: We'll take the biggest step yet — Object-Oriented Programming with classes and objects.