Methods in Java – Syntax, Types and Examples
A method is a named block of code that performs a task. You write it once and call it whenever you need that task done, which keeps programs short, readable and easy to change. In Java, every method belongs to a class or an interface, and the program itself starts from a method: main.
This tutorial covers how to declare and call methods, parameters and return values, how Java passes arguments, overloading, variable-length arguments, static and instance methods, and recursion.
1. What Is a Method?
Think of a method as a recipe: it has a name ("make tea"), takes ingredients (parameters), follows steps (the body), and may produce a result (the return value). Once written, anyone can follow the recipe by calling its name.
Benefits of methods:
- Reuse: write logic once, call it from many places.
- Readability: a well-named method explains what the code does.
- Maintainability: fix a bug in one place.
- Testing: small methods are easy to test on their own.
2. Method Syntax
accessModifier [static] returnType methodName(parameterList) [throws Exceptions] {
// method body
return value; // if returnType is not void
}
public static int square(int number) {
return number * number;
}
| Part | Meaning |
|---|---|
| Access modifier | Who can call it: public, protected, package-private or private. |
static (optional) | Belongs to the class rather than an object. |
| Return type | Type of the value returned, or void for none. |
| Name | A verb in camelCase, such as calculateTotal. |
| Parameter list | Inputs with their types, in parentheses; may be empty. |
| Body | The statements that do the work. |
The method's signature is its name plus its parameter types, for example square(int). The return type is not part of the signature.
3. Defining and Calling Methods
public class MethodBasics {
// A method that takes two parameters and returns a value
static double area(double length, double width) {
return length * width;
}
// A method that returns nothing (void)
static void printReceipt(String item, double amount) {
System.out.println(item + ": Rs. " + amount);
}
// A method with no parameters
static String greeting() {
return "Thank you for shopping!";
}
public static void main(String[] args) {
double room = area(4.5, 3.0); // call and store the result
printReceipt("Floor tiles for " + room + " sq m", room * 650);
System.out.println(greeting());
}
}
Floor tiles for 13.5 sq m: Rs. 8775.0 Thank you for shopping!
When you call a method, Java evaluates the arguments, copies them into the parameters, runs the body, and returns to the caller, together with a value if the method has one. return also ends the method immediately.
4. How Arguments Are Passed: Always by Value
Java always passes a copy of each argument. For primitives, that is a copy of the value. For objects, it is a copy of the reference, so the method can change the object, but it cannot make the caller's variable point to a different object.
public class PassByValue {
static class Wallet { int balance; Wallet(int b) { balance = b; } }
static void tryToChange(int amount) {
amount = 999; // changes only the local copy
}
static void spend(Wallet w) {
w.balance -= 100; // changes the object the reference points to
}
static void replace(Wallet w) {
w = new Wallet(5000); // changes only the local copy of the reference
}
public static void main(String[] args) {
int amount = 10;
tryToChange(amount);
System.out.println("amount after tryToChange: " + amount);
Wallet wallet = new Wallet(500);
spend(wallet);
System.out.println("balance after spend: " + wallet.balance);
replace(wallet);
System.out.println("balance after replace: " + wallet.balance);
}
}
amount after tryToChange: 10 balance after spend: 400 balance after replace: 400
5. Method Overloading
Several methods in a class can share a name if their parameter lists differ (in number, type or order). Java picks the right one at compile time from the arguments you pass.
public class Overloading {
// Same name, different parameter lists
static int add(int a, int b) { return a + b; }
static int add(int a, int b, int c) { return a + b + c; }
static double add(double a, double b) { return a + b; }
static String add(String a, String b) { return a + b; }
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2, 3, 4));
System.out.println(add(2.5, 1.25));
System.out.println(add("Java", "21"));
}
}
5 9 3.75 Java21
Changing only the return type is not enough to overload a method. See Method Overloading in Java.
6. Variable-Length Arguments (Varargs)
Adding ... after a parameter type lets callers pass any number of arguments, which the method receives as an array:
public class VarargsDemo {
// Accepts any number of int arguments (received as an array)
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
static String join(String separator, String... parts) { // varargs must come last
return String.join(separator, parts);
}
public static void main(String[] args) {
System.out.println(sum());
System.out.println(sum(5));
System.out.println(sum(1, 2, 3, 4, 5));
System.out.println(join(" | ", "red", "green", "blue"));
}
}
0 5 15 red | green | blue
A method can have only one varargs parameter, and it must be the last one. More in Varargs in Java.
7. Static Methods vs Instance Methods
public class InstanceMethods {
private int count; // state of each object
void increment() { count++; } // instance method: uses the object's state
int getCount() { return count; }
static int max(int a, int b) { // static method: no object needed
return a > b ? a : b;
}
public static void main(String[] args) {
InstanceMethods clicksA = new InstanceMethods();
InstanceMethods clicksB = new InstanceMethods();
clicksA.increment();
clicksA.increment();
clicksB.increment();
System.out.println("A=" + clicksA.getCount() + ", B=" + clicksB.getCount());
System.out.println("max = " + InstanceMethods.max(clicksA.getCount(), clicksB.getCount()));
}
}
A=2, B=1 max = 2
| Instance method | Static method |
|---|---|
Called on an object: clicksA.increment() | Called on the class: Math.max(a, b) |
Can use instance fields and this | Cannot use instance fields or this directly |
| Can be overridden | Cannot be overridden (only hidden) |
| Use for behaviour that depends on an object's state | Use for utilities and factory methods |
8. Recursive Methods
A method that calls itself is recursive. Every recursive method needs a base case that stops the recursion; otherwise it keeps calling itself until the stack runs out and a StackOverflowError is thrown.
public class RecursionDemo {
// A method that calls itself: n! = n * (n - 1)!
static long factorial(int n) {
if (n <= 1) return 1; // base case stops the recursion
return n * factorial(n - 1);
}
static int sumDigits(int n) {
return n < 10 ? n : n % 10 + sumDigits(n / 10);
}
public static void main(String[] args) {
System.out.println("5! = " + factorial(5));
System.out.println("20! = " + factorial(20));
System.out.println("sum of digits of 98765 = " + sumDigits(98765));
}
}
5! = 120 20! = 2432902008176640000 sum of digits of 98765 = 35
Recursion is elegant for problems that are naturally self-similar (trees, file systems, divide-and-conquer algorithms). For simple counting, a loop is usually faster and uses less memory.
9. Kinds of Methods
- Predefined methods from the Java library:
System.out.println(),Math.sqrt(),String.length(). - User-defined methods that you write yourself.
- Getters and setters that read and update private fields.
- Abstract methods without a body, implemented by subclasses.
- Default and static methods in interfaces (Java 8+), and private interface methods (Java 9+).
main, the entry point of an application.
10. The main Method
public static void main(String[] args) {
// args holds command-line arguments: java App one two -> args = ["one", "two"]
}
In this classic form, which works in every Java version, main is public so the launcher can call it, static so no object is needed, and void because it returns nothing. Since Java 25, the launcher also accepts simpler main methods that are not static and have no parameters; see Java Version Improvements and Java 25 Updates.
11. Java Version Improvements and Java 25 Updates
Methods themselves have changed little, but several releases added new places to declare them and, in Java 25, a simpler way to start a program:
| Feature | Java version | Status in Java 25 | What it adds |
|---|---|---|---|
| Varargs | Java 5 | Standard | Methods that accept any number of arguments. |
| Default and static interface methods | Java 8 | Standard | Interfaces can contain method bodies. |
| Private interface methods | Java 9 | Standard | Helper methods shared by default methods. |
Instance main methods and compact source files | Java 25 | Standard | main can be an instance method with no parameters, and small programs can omit the class declaration. |
Instance main Methods (Java 25)
In Java 25, main no longer has to be public static void main(String[] args). Because main below is an instance method, it can call the instance method tip() and read the field tipRate directly, without creating an object first:
class TipCalculator {
double tipRate = 0.15;
void main() { // Java 25: instance main method, no String[] needed
IO.println("Bill 1200.0 -> tip " + tip(1200.0));
IO.println("Bill 860.0 -> tip " + tip(860.0));
}
double tip(double bill) { // an ordinary instance method; no static required
return Math.round(bill * tipRate * 100) / 100.0;
}
}
java TipCalculator.java
Bill 1200.0 -> tip 180.0 Bill 860.0 -> tip 129.0
The launcher follows these rules when it starts a class:
mainmay bepublic,protectedor package-private, but notprivate.- If the class has a
main(String[] args)method, the launcher uses it; otherwise it uses amain()method with no parameters. - If the chosen
mainis an instance method, the launcher first creates an object, so the class needs a non-private constructor with no parameters. IO.println()is a Java 25 convenience method fromjava.lang.IO;System.out.println()still works everywhere.
The classic public static void main(String[] args) remains valid and is still the right choice for code that must run on Java 21 or earlier.
12. Best Practices
- Give each method one clear job, and keep it short.
- Name methods with verbs:
calculateTax(),sendEmail(),isValid(). - Keep parameter lists short; group related values into an object if there are many.
- Validate parameters and fail early with clear exceptions.
- Avoid changing objects passed as arguments unless that is the method's obvious purpose.
- Return empty collections instead of
null.
13. Summary
- A method has a modifier, return type, name, parameters and body; its signature is name plus parameter types.
- Java passes all arguments by value, including copies of object references.
- Overloading lets methods share a name with different parameter lists.
- Varargs accept any number of arguments of one type.
- Static methods belong to the class; instance methods work with an object's state.
- Recursive methods call themselves and must have a base case.
Related Tutorials
14. Official Java Documentation References
- Java Language Specification (Java SE 25) §8.4: Method Declarations
- JLS §8.4.2: Method Signature
- JLS §15.12: Method Invocation Expressions
- JLS §12.1.4: Invoke a main Method
- The java Command (Java SE 25)
- java.lang.IO (Java SE 25 API)
- JEP 512: Compact Source Files and Instance Main Methods
- dev.java: Defining Methods