Java Methods
A method is a block of code that only runs when you call it. You give it a name once, then reuse it as many times as you like. Methods let you break a big program into small, named pieces that are easier to read, test, and fix.
Why methods matter
Imagine you need to print a welcome banner in five different places in your program. Without methods, you would copy the same lines five times. With a method, you write the banner once and call its name whenever you need it. This is often called the DRY principle: Don't Repeat Yourself.
- Reuse: write the logic once, call it anywhere.
- Readability: a good method name explains what the code does.
- Maintenance: fix a bug in one place instead of many.
- Organization: split a large task into small, focused steps.
Creating a method
In Java, methods are defined inside a class. A method has a return type, a name, a pair of parentheses for parameters, and a body enclosed in curly braces. The keyword static means the method belongs to the class itself, so you can call it without first creating an object. The word void means the method does not send any value back.
Defining and calling a method
public class Main {
// Define a method named greet
static void greet() {
System.out.println("Welcome to Java!");
}
public static void main(String[] args) {
greet(); // Call the method
greet(); // Call it again
}
}
// Output:
// Welcome to Java!
// Welcome to Java!Notice that main is itself a method. It is the special method Java runs first when your program starts. When you call greet(), the program jumps into the greet method, runs its body, and then returns to the exact spot where it was called.
Calling a method many times
One method, reused
public class Main {
static void drawLine() {
System.out.println("------------------------");
}
public static void main(String[] args) {
drawLine();
System.out.println("Monthly Report");
drawLine();
}
}
// Output:
// ------------------------
// Monthly Report
// ------------------------Exercise: Java Methods
What must a method whose return type is not void include?