Methods (Functions)
Overview
Methods (commonly called Functions in other languages) are reusable blocks of code designed to perform a single, specific task. Instead of writing the same 50 lines of code multiple times across your app, you write it once inside a method, and 'call' that method whenever you need it. This promotes the DRY (Don't Repeat Yourself) principle.
A method definition consists of an Access Modifier (like public), a Return Type (like int or void if it returns nothing), a Method Name, and a parameter list. When a method finishes executing, it can optionally pass data back to the caller using the return keyword.
Syntax
The multiply method acts as a black box. You feed it inputs (parameters), it processes them, and it spits an output (return) back out to the main method.
public class Calculator {
// 1. A method that RETURNS data (int) and takes Parameters
public int multiply(int a, int b) {
int result = a * b;
return result; // Passes the data back!
}
// 2. A method that returns NOTHING (void)
public void printGreeting(String name) {
System.out.println("Hello, " + name + "!");
// No return statement needed for void
}
public static void main(String[] args) {
Calculator calc = new Calculator();
// Calling the methods
calc.printGreeting("Alice");
// Storing the returned data into a variable
int product = calc.multiply(5, 4);
System.out.println("Result: " + product);
}
}Common Pitfalls
- Forgetting the
returnstatement. If you declare a method with a return type ofString, the compiler will throw an error if every single logical path doesn't end with areturnstatement. - Returning values from a
voidmethod. A method marked asvoidis explicitly stating it gives nothing back. Trying toreturn 5;inside a void method is illegal.
Interview Questions
Method Overloading allows a class to have multiple methods with the exact same name, as long as their parameter lists (signatures) are different. For example, having add(int a, int b) and add(double a, double b). The compiler figures out which one to call based on the arguments provided.
Java is strictly Pass-by-Value. For primitive types, a copy of the actual value is passed. For objects, a copy of the memory reference is passed. This means you can alter the internal state of an object passed into a method, but you cannot reassign the object to a brand new reference.
Real-World Example
In a secure application, password hashing logic is complex and requires multiple encryption steps. By extracting this into a hashPassword(String raw) method, developers across the team can safely hash passwords without needing to understand the underlying cryptography.
public String createUser(String username, String rawPassword) {
// Reusable, abstracted logic
String secureHash = cryptoService.hashPassword(rawPassword);
return db.saveUser(username, secureHash);
}Check Your Knowledge
Test your understanding of Methods (Functions) with these quick questions.