Java Methods - Complete Guide
Master Java methods with detailed explanations of parameters, return types, overloading, recursion, and best practices for modular, reusable code.
1. Introduction to Java Methods
Methods group reusable logic inside classes. They accept parameters, may return a value, and improve readability and testing.
Method vs Function — what is the difference?
In everyday speech, many people say function for any named block of code. In Java, the correct term is method because every callable unit (except special cases like lambdas) lives inside a class.
| Term | Typical meaning | In Java |
|---|---|---|
| Function | Standalone routine (C, Python, JavaScript) | Not a separate language feature — no top-level function foo() outside a class |
| Method | Function tied to a class or object | Official name: accessModifier returnType name(params) { } inside a class |
- C / Python:
int add(int a, int b) { ... }at file scope — called a function - Java: same idea, but must sit inside a class — called a method
main: is a method (public static void main(String[] args)), not a free function- Static methods (e.g.
Math.max) are still methods — sometimes described informally as “utility functions” - Instance methods belong to an object:
account.withdraw(100)
Remember
If it is defined inside a class in Java, call it a method. Saying “function” in conversation is fine, but exam papers and the Java Language Specification use method.
- Defined inside a class
- Called with dot notation:
obj.method()orClassName.staticMethod() mainis the program entry method- Methods can call other methods in the same class
public class MethodIntro {
static void greet() {
System.out.println("Hello!");
}
public static void main(String[] args) {
greet();
}
}
2. Method Anatomy
A method signature includes modifiers, return type, name, and parameter list. The body contains statements in curly braces.
- access modifier + static + returnType + name(params)
- void means no return value
- return exits method with a value
- Parameters are local variables
public class Anatomy {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(2, 3));
}
}
3. Types of Methods
Methods vary by return type, parameters, and whether they are static (class-level) or instance (object-level).
- Static — called on class, no object needed
- Instance — called on object, access fields
- void — perform action, return nothing
- Parameterized — accept input values
public class MethodTypes {
int value = 10;
static int staticValue = 5;
void show() { System.out.println(value); }
static void showStatic() { System.out.println(staticValue); }
}
4. Method Parameters
Parameters let methods receive data. Java passes arguments by value: for objects, the reference value is copied.
- Formal parameters in method declaration
- Arguments passed at call site
- Varargs: int... nums for variable args
- Primitive copies value; object copies reference
public class Params {
static double average(int... nums) {
int sum = 0;
for (int n : nums) sum += n;
return (double) sum / nums.length;
}
public static void main(String[] args) {
System.out.println(average(10, 20, 30));
}
}
5. Method Overloading
Overloading defines multiple methods with the same name but different parameter lists. The compiler picks the best match at compile time.
- Same name, different parameters
- Return type alone is not enough
- Constructors can be overloaded too
- Compile-time polymorphism
public class OverloadDemo {
static int max(int a, int b) { return a > b ? a : b; }
static double max(double a, double b) { return a > b ? a : b; }
public static void main(String[] args) {
System.out.println(max(3, 7));
System.out.println(max(3.5, 2.1));
}
}
6. Recursion in Methods
A recursive method calls itself with a smaller or simpler input until a base case stops the recursion.
- Must have base case
- Each call gets its own stack frame
- Useful for tree and divide-and-conquer problems
- Can often be rewritten as iteration
public class Factorial {
static int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
public static void main(String[] args) {
System.out.println(fact(5));
}
}
7. Method Design Principles
Well-designed methods do one thing, have clear names, and keep parameter lists short. This makes code easier to test and reuse.
- Single responsibility per method
- Use descriptive verb names (calculateTotal)
- Avoid side effects when possible
- Keep methods short and focused
- Document public API with Javadoc
public class DesignDemo {
static boolean isValidEmail(String email) {
return email != null && email.contains("@");
}
public static void main(String[] args) {
System.out.println(isValidEmail("user@mail.com"));
}
}
8. Tricky Points
Common method-related pitfalls in Java interviews and real projects.
Method vs function wording
void helper() { } outside any class is a compile error — wrap it in a class (often with static).
Return type and void
void method must return a value on every path. if (x > 0) return x; without an else return causes “missing return statement”.
void and return value: return 5; inside a void method is illegal. Use bare return; to exit early.
Parameters and pass-by-value
void setZero(int n) { n = 0; } does not affect the argument variable outside.
list.add(1)) but reassigning the parameter (list = new ArrayList<>()) does not change the caller’s reference.
Static vs instance
greet(); only works if greet is static or you are inside another instance method on the same object. Otherwise use obj.greet().
this: Static methods cannot use this or access non-static fields directly — no object context exists.
Overloading
int max(int a, int b) and double max(int a, int b) is not valid overloading — same parameter list, different return only.
void print(int x) vs void print(Integer x) — calling print(5) picks int; mixed overloads with null can confuse the compiler.
Recursion
StackOverflowError, not a normal loop forever.
main calling itself: public static void main(String[] args) { main(args); } recurses until stack overflow — main is just another method.
Rule of thumb
Use method in Java; keep one job per method; match return type on all paths; remember pass-by-value; use static only when you do not need object state; overload by parameter list, not return type alone.
9. Pass by Value vs Pass by Reference in Java
Many languages teach both pass by value and pass by reference. Java uses only pass by value — always. What confuses beginners is that for objects, the value being copied is a reference (memory address), not the object itself.
| Concept | What gets copied? | Does Java use it? |
|---|---|---|
| Pass by value | A copy of the argument’s value | Yes — always (primitives and object references) |
| Pass by reference | The variable itself (alias); reassignment inside the method changes the caller’s variable | No (not for parameters — C++ & style) |
Pass by value with primitives
The method receives a copy of the number. Changing the parameter inside the method does not change the original variable.
public class PassByValuePrimitive {
static void tryToChange(int x) {
x = 100; // changes only the local copy
System.out.println("Inside method: x = " + x);
}
public static void main(String[] args) {
int num = 10;
tryToChange(num);
System.out.println("After method: num = " + num); // still 10
}
}
Output: Inside method: x = 100 → After method: num = 10
“Pass by reference” confusion with objects
With objects, Java still passes by value — but the value is a reference (like a remote control pointing to the object). Two outcomes:
- Mutate the object (change what it points to) — caller sees the change
- Reassign the parameter to a new object — caller’s variable is unchanged (only the copy of the reference was reassigned)
public class PassByValueObject {
static void changeContent(int[] arr) {
arr[0] = 999; // mutates the same array object — caller sees this
}
static void reassignReference(int[] arr) {
arr = new int[]{7, 8, 9}; // local copy points elsewhere — caller unchanged
}
public static void main(String[] args) {
int[] data = {1, 2, 3};
changeContent(data);
System.out.println("After changeContent: " + data[0]); // 999
reassignReference(data);
System.out.println("After reassign: " + data[0]); // still 999 (same array)
System.out.println("Length: " + data.length); // still 3, not new array
}
}
Same idea with a String (immutable object)
String cannot be mutated. Any “change” creates a new string, so reassignment inside the method never affects the caller.
public class PassByValueString {
static void tryToChange(String s) {
s = s.toUpperCase(); // new String object; parameter now points to it
}
public static void main(String[] args) {
String name = "java";
tryToChange(name);
System.out.println(name); // still "java"
}
}
Visual summary
| Argument type | What is copied into the method? | Change inside method affects caller? |
|---|---|---|
int, double, etc. |
The actual number | No — if you assign to the parameter |
| Array / object reference | Copy of the reference (same object on heap) | Yes — if you mutate the object; no — if you reassign the parameter |
Interview answer
Java is always pass by value. For objects, the value is the reference. There is no true pass by reference for method parameters in Java. To return a new reference to the caller, use return or wrap values in a holder object/array.