Methods
A method is a named, reusable block of code that performs a task. Instead of copy-pasting the
same logic everywhere, you define it once as a method and call it whenever you need it. You've already
been calling one this whole time: System.out.println(...).
Defining a Method
Every method has a return type, a name, a parameter list (which can be empty), and a body wrapped in braces.
public class MethodDemo {
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greet("Sonu"); // calling the method
}
}
Breaking it down:
static void— the return type.voidmeans this method doesn't return a value.greet— the method name, used to call it later.(String name)— the parameter list: the inputs this method expects.greet("Sonu");— calling the method, passing"Sonu"as an argument.
Parameters vs Arguments
These two terms are often used interchangeably, but they mean slightly different things:
| Term | What it means |
|---|---|
| Parameter | The variable listed in the method's definition (e.g. name in greet(String name)) |
| Argument | The actual value passed in when you call the method (e.g. "Sonu" in greet("Sonu")) |
void vs Returning a Value
A void method just performs an action and returns nothing. A method with a real return type must use the return keyword to send a value back to the caller.
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
int result = square(5);
System.out.println(result); // 25
}
static int square(int n) must return an int on every possible path.Method Overloading
Java lets you define multiple methods with the same name, as long as their parameter lists are different (different number or types of parameters). This is called overloading, and the compiler picks the right version based on the arguments you pass.
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b, double c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println(add(2, 3)); // 5 - uses the int version
System.out.println(add(1.5, 2.5, 3.0)); // 7.0 - uses the double version
}
The static Keyword on Methods
A static method belongs to the class itself, not to any particular object, so it can be called
without creating an object first — ClassName.methodName(). That's exactly why main is
always static: the JVM calls it before any object of your class exists.
MathHelper.square(4); // call directly on the class, no object needed
static keyword — covering static fields, static blocks, and when (and when not) to reach for it.