Definition:
A Method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.
1. Method Syntax Breakdown
A method must be declared within a class. It looks like this:
public class Main {
// 1. Declaration
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
// 2. Execution (Calling the method)
myMethod();
myMethod(); // Can be called multiple times
}
}
// Output:
I just got executed!
I just got executed!
2. Parameters and Arguments
Information can be passed to methods as a parameter. Parameters act as variables inside the method.
The void keyword indicates that the method should not return a value. If you want the method to return a value, you can use a primitive type (like int or double) instead of void.
static int addNumbers(int x, int y) {
return x + y; // Sends the result back
}
public static void main(String[] args) {
int result = addNumbers(5, 3);
System.out.println("The sum is: " + result);
}
// Output:
The sum is: 8
4. Why use Methods?
Code Reusability: Define the code once, and use it many times.
Better Organization: Break complex problems into smaller, manageable "tasks."
Easy Maintenance: If a bug exists in a calculation, you only have to fix it in one method rather than everywhere in your program.
Common Mistake: Forgetting the static keyword. In these early tutorials, we use static so we can call the method without creating an object of the class first.