Methods
What's a Method?
A method is like a recipe card. Instead of explaining how to bake cookies every single time, you write the recipe once and just say "follow the cookie recipe." In Java, methods let you bundle up a chunk of code, give it a name, and call it whenever you need it.
When you call a method, Java pushes it onto the call stack; when it returns, it pops off. Every Java method has a few parts:
- Return type — what does the method hand back? (
int,String,voidfor nothing) - Name — what you call it (
calculateTax,greet) - Parameters — what ingredients it needs (the inputs)
- Body — the actual instructions inside
{ }
We use static methods for now so they can be called directly from main(). You'll learn about non-static methods when we get to classes.
Your First Methods
Method Overloading — Same Name, Different Ingredients
Java lets you have multiple methods with the same name as long as they take different parameters. This is called overloading. It's like having a "make coffee" recipe — one version makes black coffee (no parameters), another makes a latte (milk parameter), and another makes a mocha (milk + chocolate).
Java figures out which version to call based on what arguments you pass in. It looks at the number and types of arguments.