[!NOTE] As your programs grow, putting all your code inside the
mainblock becomes impossible to read and maintain. Methods (often called functions in other languages) allow you to break your code into small, testable, reusable blocks.
What is a Method?
A method is a block of code which only runs when it is explicitly called. You can pass data into a method (parameters), and it can return data back out (return values).
public class Main {
// Method Definition
static void printWelcomeMessage(String name) {
System.out.println("Welcome to the system, " + name + "!");
}
public static void main(String[] args) {
// Method Executions
printWelcomeMessage("Alice"); // Outputs: Welcome to the system, Alice!
printWelcomeMessage("Bob"); // Outputs: Welcome to the system, Bob!
}
}
Let's dissect the method signature: static void printWelcomeMessage(String name)
- static: Means this method belongs to the class itself, allowing us to call it directly without
new Main(). - void: This is the "Return Type".
voidmeans this method simply executes actions and returns absolutely nothing back to the caller. - String name: This is the parameter. It acts as a local variable inside the method.
Return Values
Methods become incredibly powerful when they calculate data and hand it back to the caller. To do this, change void to the data type you intend to return, and use the return keyword inside the block.
public class MathTools {
// We declare that this method MUST return an 'int'
static int addNumbers(int x, int y) {
int sum = x + y;
return sum; // Hand the data back!
}
public static void main(String[] args) {
// The method executes, evaluates to '15', and assigns it to 'result'
int result = addNumbers(5, 10);
System.out.println("The answer is: " + result);
}
}
[!IMPORTANT] The Return Exit: The moment a method hits a
returnstatement, the method instantly terminates. Any code written beneath thereturninside that method block will never be executed.
Pass by Value
In Java, method arguments are Passed by Value. This means Java creates a copy of your primitive variable and passes the copy into the method. If the method alters the parameter, your original variable remains totally unaffected!
static void tryToChange(int number) {
number = 99; // Only changes the local copy!
}
public static void main(String[] args) {
int myNum = 5;
tryToChange(myNum);
System.out.println(myNum); // Still outputs 5!
}