Magic Boxes, Methods
Until now, we’ve put all our code inside void main(). But what happens when the code gets longer? We can take groups of frequently used commands and give them a name, like a magic box, so we can reuse them whenever we want.
In Java, these magic boxes are called Methods. While they are called “Functions” in many other programming languages, “Method” is the official term in Java.
Creating a Method
static void sayHello() {
System.out.println("Hello!");
}
void main() {
sayHello(); // Use it!
}
Translation:
Define a magic box named sayHello {
Print "Hello!" and move to the next line;
}
Program starting point {
Open (use) the sayHello box!
}
Once you create the box, simply writing sayHello() will execute all the commands inside it.
For now, just remember that the
statickeyword at the beginning is necessary if you want to use the method directly frommain.
Methods with Ingredients (Parameters)
Just like putting a coin into a vending machine to get a drink, you can pass “ingredients” to a method.
static void greet(String name) {
System.out.println("Nice to meet you, " + name + "!");
}
void main() {
greet("John");
greet("Java");
}
Translation:
Define a magic box named greet (Ingredient is text type, let's call it name) {
Combine "Nice to meet you, ", the content of name, and "!" then print it;
}
Program starting point {
Use the greet box (Ingredient is "John");
Use the greet box (Ingredient is "Java");
}
Result:
Nice to meet you, John!
Nice to meet you, Java!
Methods that Return Results (return)
A magic box can also perform a task and return a result back to us. In this case, we use return and specify the type of result instead of void.
static int add(int a, int b) {
return a + b;
}
void main() {
int result = add(10, 20);
System.out.println("The result is: " + result);
}
Translation:
Define a magic box named add (Ingredients are numbers a and b): The result will be a number (int) {
Send the value of a + b back to the outside (return);
}
Program starting point {
Put 10 and 20 into the add box and remember the result as 'result';
Print "The result is: " and the value of result;
}
What does void mean?
Remember the void we saw in void main()? void means “there is nothing to return.”
void sayHello()→ Just says hello and ends (nothing to return)int add(int a, int b)→ Returns a number
Why use Methods?
- Reduces repetition: You don’t have to write the same code over and over again.
- Cleaner code: It’s easier to read when long blocks of code are organized into boxes with labels (method names).
- Easier maintenance: If you change the contents of the box, every place that uses that box is updated at once.
You are now a creator of your very own magic boxes!