A method is a named block of code that takes some inputs, does one job, and gives something back. You write it once and then call it from anywhere in your program, which is the whole point: instead of the same twelve lines appearing in six places, you have one definition and six calls. The signature is the part worth learning carefully, because it is what the compiler uses to check every call. It runs access modifier, return type, name, parameters. The return type comes before the name, which trips up almost everyone coming from a language that writes it the other way round, so read public static void main as public, returns nothing, called main, takes no parameters. Java methods divide into two families. A static method belongs to the class and is called as ClassName.method(). An instance method belongs to an object and is called on a reference. Static methods cannot touch instance fields; instance methods can. Knowing which kind you are writing tells you where the data comes from, and that question answers most design debates before they start. The habit that matters most is keeping methods short and single-purpose. The return statement works with you here, because a method that does one thing usually has one obvious place to exit. A method doing five things, by contrast, needs flags, multiple returns scattered through nesting, and a comment explaining what the local variables are for. Short methods are not a style preference, they are what makes the rest of the language work.
Detailed Explanation & Mechanics
1) Anatomy of a Method
Every method has a signature and a body. The signature is the contract; the body is the implementation.
public static int calculateArea(int width, int height) {
// ^ ^ ^ ^ ^ ^
// | | | | | +-- parameter list
// | | | | +---------- method name
// | | | +----------------------- parameter type
// | | +----------------------------- return type
// | +------------------------------------- static or instance
// +---------------------------------------------- access modifier
return width * height;
}
The signature is the contract. The compiler checks every call against it before the program runs.
Two rules are worth memorising. First, the return type comes before the name, which is the opposite of how most languages read. Second, the parameter list declares both the type and the name of each value, so int width, int height is two parameters, not one.
2) The Two Families, Static and Instance
Every method is one or the other, and the distinction is about where the data lives.
public class Counter {
private static final int STEP = 1;
private static final int FIRST = 2;
private static final int SECOND = 3;
private int count = 0;
// instance field, one per object
public void increment() {
// INSTANCE method
count = count + STEP;
// can touch instance data
} public static int add(int a, int b) {
// STATIC method
return a + b;
// no instance data available
}
}Counter c = new Counter();
c.increment();
// called on an object
System.out.println(Counter.add(FIRST, SECOND));
// called on the class
Question
Static
Instance
Belongs to
The class
Each object
How it is called
ClassName.method()
object.method()
Can read instance fields
No
Yes
Can use this
No
Yes
Best for
Pure functions, utilities, factories, main
Anything operating on object state
Overriding in a subclass
Hidden, not truly overridden
Yes, real dynamic dispatch
A useful rule: if the method would work if you deleted every this from it, make it static. If it genuinely needs the object it was called on, keep it an instance method. This is why utilities like Math.max and Integer.parseInt are static, while list.add is not.
The classic error is calling an instance method statically, or trying to use this inside a static method. The compiler catches both, which is reassuring.
3) Calling Methods
Calls come in two forms, and matching the arguments to the parameter types is the compiler’s job.
final int WIDTH = 10;
final int HEIGHT = 20;
// Calling with arguments, in the declared order
int area = calculateArea(WIDTH, HEIGHT);
// Parameters are positional, so the order matters
calculateArea(WIDTH, HEIGHT);
// width first, height second
// Assigning the result to a variable
int result = calculateArea(WIDTH, HEIGHT);
// Ignoring the result is legal only for a void method
logMessage("done");
// Methods can call methods, which is how code stays readable
public static int describeRoom(int width, int height) {
int area = calculateArea(width, height);
return area * WALL_THICKNESS;
}
Arguments go in, a result comes back. Nothing runs until the line is reached.
Java is strictly pass by value, so a method receives a copy of each argument. Changing a parameter inside the method does not change the caller’s variable, which is a common source of confusion and a reason many methods return a result rather than mutating an argument.
4) Method Overloading
Several methods can share one name as long as their parameter lists differ. The compiler picks the right one from the argument types at the call site.
final double TWO_POINT_FIVE = 2.5;
final double THREE_POINT_FIVE = 3.5;
public static int add(int a, int b) {
return a + b;
}public static double add(double a, double b) {
return a + b;
}public static int add(int a, int b, int c) {
return a + b + c;
}final int ONE = 2;
final int TWO = 3;
final int THREE = 4;
add(ONE, TWO);
// picks the int version, result 5
add(TWO_POINT_FIVE, THREE_POINT_FIVE);
// picks the double version
add(ONE, TWO, THREE);
// picks the three argument version
Rule
Allowed?
Same name, different parameter types
Yes, this is the point
Same name, different number of parameters
Yes
Same name, same parameters, different return type
No, compile error
Constructor with a different parameter list
Yes, this is the normal pattern
Note the third row. Because the compiler must choose from the arguments alone, the return type cannot break a tie. Two methods differing only in what they return would be indistinguishable at the call site.
5) void, Value Returning, and Constructors
Not every method hands something back, and a method that runs in main without returning anything is a perfectly good method.
// VOID: does the work, sends nothing back
public static void logMessage(String message) {
System.out.println("[log] " + message);
}// VALUE RETURNING: produces a result
public static int findMax(int a, int b) {
return a > b ? a : b;
}// CONSTRUCTOR: same name as the class, no return type at all
public Counter() {
this.count = 0;
}public Counter(int start) {
this.count = start;
}
A constructor is the one method where you must not write a return type, not even void. The class name is the method name. Writing public void Counter() is a compile error, and it is a mistake almost everyone makes once.
6) Passing Arrays and Objects
For an array or an object, the value copied is the reference. So the method can modify the contents, and the caller sees the change. Reassigning the parameter itself is still invisible.
public static void doubleAll(int[] values) {
for (int i = 0;
i < values.length;
i++) {
values[i] = values[i] * 2;
// caller sees this
} values = new int[10];
// caller does NOT see this
}int[] numbers = {
1, 2, 3
};
doubleAll(numbers);
System.out.println(numbers[0]);
// 2, the array is shared
This is worth being precise about, because “pass by value” and “changes are visible” sound contradictory. Both are true: the reference is copied, and both copies point at the same array.
7) Methods Versus Fields
A field stores a value. A method computes or acts. Reaching for the right one is part of writing clear code.
// A stored total can go stale the moment the items change
private int total;
// Better: compute it when asked, so it is always correct
public int getTotal() {
int sum = 0;
for (int item : items) {
sum = sum + item.getPrice();
} return sum;
}
Storing a derived value is a bug waiting to happen, because you now have to update it everywhere the underlying data changes. Making it a method trades a tiny amount of repeated work for a value that cannot be wrong.
8) Good Methods, in Practice
Three habits cover most of what makes a method readable.
Name it as a verb phrase.calculateTotal() says what it does; total or doStuff() says nothing. A good name often lets you delete the comment above the method.
Keep it short. A method you cannot summarise in one line is usually doing more than one thing. The smell is nesting: four levels of if inside a for inside an if is really three or four methods waiting to be extracted.
final int MIN_QTY = 1;
// Before: one method doing four things
public static void processOrder(Order order) {
if (order != null) {
for (Item item : order.getItems()) {
if (item.getQuantity() > MIN_QTY) {
if (!item.isExpired()) {
reserve(item);
}
}
} charge(order);
notifyCustomer(order);
}
}// After: each step is named and can be tested on its own
public static void processOrder(Order order) {
if (order == null) {
return;
// guard clause
} List<Item> sellable = filterSellable(order.getItems());
reserve(sellable);
charge(order);
notifyCustomer(order);
}private static List<Item> filterSellable(List<Item> items) {
List<Item> result = new ArrayList<>();
for (Item item : items) {
if (item.getQuantity() > 0 && !item.isExpired()) {
result.add(item);
}
} return result;
}
Keep the parameters few and related. A method taking six parameters, several of which must be passed together in a particular order, is usually hiding a small object. Grouping them into a type makes the contract self-documenting and removes the chance of swapping two int arguments.
Splitting one long method into named steps. The behaviour is identical, the reading is not.
9) Common Mistakes
Mistake
Symptom
Fix
Return type before the name
Compile error, or you wrote int getName String
Type first, then the name.
Return type on a constructor
Compile error
Remove the type entirely.
Using this in a static method
Compile error
Make the method an instance method.
Overloading on return type only
Compile error
Vary the parameter list instead.
Expecting a changed parameter to persist
Caller sees the original value
Return the new value, or mutate the object.
A method that does several things
Deep nesting and scattered returns
Extract named helper methods.
Naming a method like a noun
Reads as a field, hides the action
Use a verb phrase.
Storing a value that can be derived
The stored copy goes stale
Compute it in a method.
Eight method mistakes. The compiler catches the first four, which leaves the last four for review to find.
Frequently Asked Questions
What is a method in Java?
A named block of code that takes zero or more parameters, performs one task, and optionally returns a result. You define it once and call it as many times as you like, which is the main reason methods exist.
What is the difference between a static and an instance method?
A static method belongs to the class and is called as ClassName.method(). An instance method belongs to each object and is called on a reference. A static method cannot read instance fields or use this, because no particular object is in view.
What is method overloading?
Defining several methods with the same name but different parameter lists, such as add(int, int) and add(double, double). The compiler selects the correct one from the types of the arguments at the call site.
Can two methods differ only in return type?
No. Because the compiler must choose from the arguments alone, a differing return type would make the call ambiguous. It is a compile error, so you must vary the parameter list instead.
What is the difference between a method and a constructor?
A constructor has the same name as the class, has no return type at all, and runs when an object is created. An ordinary method has a name you choose, always declares a return type, and is called explicitly.
Why can a method not change the value of its parameter?
Because Java passes by value, so the method receives a copy of the argument. Reassigning the parameter changes only that copy. Objects and arrays are different, since the copy is of the reference and both sides still point at the same data.
How long should a method be?
There is no fixed rule, but if you cannot describe what it does in a single sentence it is probably doing more than one thing. A practical guide is under about thirty lines, and more importantly low nesting.
When should a method be static?
When it does not need the object it was called on. A good test is to delete every this from the method: if it still makes sense, make it static. Pure calculations, utilities, and factory methods are the usual candidates.
// Demonstrates how Java methods are declared, overloaded, and called.
public class MethodDemo {
private static final int WALL_THICKNESS = 2;
private static final int MIN_QTY = 1;
private static final double TAX_RATE = 0.2;
// 1) SIGNATURE ANATOMY
// public static int calculateArea(int width, int height)
// ^ ^ ^ ^ ^
// access | return name parameters
// modifier | type
// belongs to the class, not an object
public static int calculateArea(int width, int height) {
return width * height;
} // 2) ONE METHOD CALLING ANOTHER
public static int describeRoom(int width, int height) {
int area = calculateArea(width, height);
return area * WALL_THICKNESS;
} // 3) A VOID METHOD RETURNS NOTHING
public static void logMessage(String message) {
System.out.println("[log] " + message);
} // 4) OVERLOADING, SAME NAME DIFFERENT PARAMETERS
public static int add(int a, int b) {
return a + b;
} public static double add(double a, double b) {
return a + b;
} public static int add(int a, int b, int c) {
return a + b + c;
} // 5) A BUILDER METHOD, WHICH IS JUST A METHOD WITH A LOOP
public static String repeat(String text, int times) {
StringBuilder builder = new StringBuilder();
for (int i = 0;
i < times;
i++) {
builder.append(text);
} return builder.toString();
} // 6) PASSING AN ARRAY, THE CALLER SEES CHANGES TO THE CONTENTS
public static void doubleAll(int[] values) {
for (int i = 0;
i < values.length;
i++) {
values[i] = values[i] * 2;
// the array is shared
} values = new int[values.length];
// reassigning is NOT seen by the caller
} // 7) A COMPUTED VALUE BEATS A STORED ONE, BECAUSE IT CANNOT GO STALE
public static int totalOf(int[] prices) {
int sum = 0;
for (int price : prices) {
sum = sum + price;
} return sum;
} public static double withTax(int amount) {
return amount +(amount * TAX_RATE);
} public static void main(String[] args) {
final int WIDTH = 10;
final int HEIGHT = 20;
final int TIMES = 3;
// THE PARAMETERS ARE POSITIONAL, SO THE ORDER MATTERS
logMessage("calling methods");
System.out.println("area(10, 20) = " + calculateArea(WIDTH, HEIGHT));
System.out.println("describeRoom = " + describeRoom(WIDTH, HEIGHT));
// OVERLOAD RESOLUTION HAPPENS AT COMPILE TIME
System.out.println("add(2, 3) = " + add(2, 3));
System.out.println("add(2.5, 3.5) = " + add(2.5, 3.5));
System.out.println("add(2, 3, 4) = " + add(2, 3, 4));
System.out.println("repeat(\"ab\", 3) = " + repeat("ab", TIMES));
int[] numbers = {
1, 2, 3
};
doubleAll(numbers);
System.out.println("after doubleAll = " + numbers[0] + numbers[1] + numbers[2]);
int subtotal = totalOf(numbers);
System.out.println("total = " + subtotal);
System.out.println("with 20% tax = " + withTax(subtotal));
}
}/*
ACTUAL OUTPUT:
[log] calling methods
area(10, 20) = 200
describeRoom = 400
add(2, 3) = 5
add(2.5, 3.5) = 6.0
add(2, 3, 4) = 9
repeat("ab", 3) = ababab
after doubleAll = 246
total = 12
with 20% tax = 14.4
THE SEVEN THINGS TO REMEMBER
1) THE SIGNATURE IS access modifier, return type, name, parameters.
The return type comes BEFORE the name, which is the opposite of
how most other languages read, so read it right to left.
2) static belongs to the class, instance belongs to an object. A
static method cannot use instance fields or this.
3) ARGUMENTS ARE POSITIONAL. calculateArea(10, 20) and
calculateArea(20, 10) are different calls.
4) OVERLOADING IS DECIDED BY THE PARAMETERS, never by the return
type, because the compiler chooses from the arguments alone.
5) A CONSTRUCTOR HAS NO RETURN TYPE. Not void, nothing. Its name is
the class name and it runs when the object is created.
6) PARAMETERS ARE COPIED, so reassigning one is invisible to the
caller. Arrays and objects are the exception in practice,
because the copy is of the reference and the data is shared.
7) PREFER A COMPUTED METHOD OVER A STORED FIELD, since a stored
copy can go stale the moment the underlying data changes.
*/
Common Java Technical Interview Questions & Answers
Interview Prep
Q1: What is a method in Java?\nA1: A named block of code that takes zero or more parameters, performs one task, and optionally returns a result. It is defined once and can be called from anywhere, which is the main reason methods exist.\nQ2: What is the difference between a static and an instance method?\nA2: A static method belongs to the class and is called as ClassName.method(). An instance method belongs to an object and is called on a reference. A static method cannot read instance fields or use this, because no particular object is in view.\nQ3: What is method overloading in Java?\nA3: Defining several methods with the same name but different parameter lists, such as add(int, int) and add(double, double). The compiler selects the correct one based on the types of the arguments at the call site.\nQ4: Can two methods differ only in their return type?\nA4: No. Because the compiler must choose from the arguments alone, a differing return type would make the call ambiguous. It is a compile error, so the parameter list has to differ instead.\nQ5: What is the difference between a method and a constructor?\nA5: A constructor has the same name as the class, declares no return type at all, and runs when an object is created. An ordinary method has a name you choose, always declares a return type, and is called explicitly by your code.\nQ6: Why can a method not change the value of its parameter?\nA6: Because Java passes by value, so the method receives a copy of the argument and reassigning it affects only that copy. Objects and arrays behave differently in practice, since the copy is of the reference and both sides still point at the same data.\nQ7: How long should a method ideally be?\nA7: There is no hard limit, but if you cannot describe what it does in one sentence it is probably doing more than one thing. Under roughly thirty lines with low nesting is a practical target, and the nesting level matters more than the line count.\nQ8: When should a method be declared static?\nA8: When it does not need the object it was called on. A good test is to remove every this from the method: if it still makes sense, declare it static. Pure calculations, utility helpers, and factory methods are the usual candidates.
Key Takeaways, Best Practices & Clean Code Rules
Java Best Practice & Production Rules
Name methods as verb phrases such as calculateTotal() or sendNotification(), since a good name often tells you the comment above the method is unnecessary.\nKeep methods short and single-purpose, and treat deep nesting as the real warning sign that a method should be split into named helpers.\nPrefer a computed method over a stored field for any derived value, because a stored copy silently goes stale the moment the underlying data changes.\nDeclare a method static when it never needs the object it was called on, and apply the test of removing every this from the body.\nUse guard clauses at the top of a method body to handle invalid input, which keeps the main logic flat instead of wrapped in a large if block.\nKeep the parameter count small and group related parameters into a type, so the compiler can catch two accidentally swapped arguments.\nDo not rely on mutating a parameter to communicate a result back to the caller, since only the local copy changes; return the value instead.\nRead a method signature right to left, as return type, name, parameters, and remember the return type comes before the name in Java.\nGive a void method a verb name that describes the action, since a caller gets nothing back and the name is the only description available.\nExtract repeated blocks into a method even when the block is only a few lines, because the second occurrence proves it is worth naming.\nAvoid methods that differ only in return type, as the compiler cannot resolve the call and will reject it.\nUse Javadoc on methods whose contract is not obvious from the name, particularly anything with unusual parameters or a non-obvious return value.
Share with friends, students, or your developer network
We value your privacy & transparency
OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.
Stay Updated
Enable Notifications?
Get real-time updates, instant tool alerts & daily news directly on your device.