Lesson 7 of 23

In progress

Course progress

Java

Methods: naming behaviour

Extract repeated code into a method, choose a signature that says what it does, and keep methods short enough to check.

A method gives a name to a piece of work. The name is the point: it lets a reader understand a call without reading the body, and it gives you one place to fix a bug.

What you will learn

  • Declare methods with parameters and return values.
  • Keep methods focused and free of hidden state.
  • Use overloading without making calls ambiguous.

The declaration

public class Prices {
static long withTax(long paise) {
return Math.round(paise * 1.18);
}
public static void main(String[] args) {
System.out.println(withTax(45_000L));
System.out.println(withTax(129_900L));
}
}

static means the method belongs to the class, not to an object, so it can be called as Prices.withTax(...) without creating anything. long before the name is the return type; long paise is the parameter.

A method signature is its name plus the parameter types. The return type is not part of the signature, which is why two methods cannot differ only by return type.

Return early, return once

static String describe(int score) {
if (score < 0 || score > 100) {
return "invalid";
}
if (score >= 90) {
return "excellent";
}
if (score >= 70) {
return "good";
}
return "needs work";
}

Each guard handles one case and returns. The alternative — a local variable assigned in every branch and returned at the end — is longer and easier to get wrong, because one path can forget the assignment.

For a method that does real work after validation, the shape is: validate and return early, then compute and return the result. That keeps the happy path unindented.

void methods and side effects

static void printTable(int[] values) {
for (int value : values) {
System.out.println(value);
}
}

A void method exists for its effect: printing, saving, mutating an argument. That is legitimate and it makes the method harder to test than one that returns a value.

The useful rule: a method should either return a value or change state, and preferably not both. A method named calculateTotal that also writes to a database is a method whose name lies.

Parameters

static long total(long[] prices, int count) {
long sum = 0;
for (int i = 0; i < count; i++) {
sum += prices[i];
}
return sum;
}

Java passes everything by value. For primitives, the method gets a copy, so changes are local. For objects and arrays, the value is the reference, so the method can change the object’s contents but cannot make the caller’s variable point elsewhere.

That distinction drives a design choice: if a method must not modify its argument, do not pass a mutable object, or copy it at the boundary. Documenting "does not modify" is weaker than making it impossible.

Too many parameters is a smell. Three or four is comfortable; six means the call site reads as a list of unexplained values. Group related parameters into a small class or record:

record Money(long paise, String currency) {}
static String format(Money money) {
return money.currency() + " " + money.paise() / 100.0;
}

Overloading

static String greet(String name) {
return "Hello, " + name;
}
static String greet(String name, String greeting) {
return greeting + ", " + name;
}

Two methods with the same name and different parameter lists. The compiler picks by the argument types, so greet("Ana") and greet("Ana", "Hi") resolve to different bodies.

Overloading works when the variants do the same thing with different inputs. It becomes confusing when the behaviour differs by type, because the call site does not show which one runs. Prefer distinct names when the meaning differs.

Method length

A method that fits on one screen can be checked by reading it. Beyond that, the reader needs to hold too much in mind.

The usual fix is extraction: find a block with a coherent purpose, name it, and call it. That often reveals repeated code, which is the real reason to extract.

static boolean isValidEmail(String email) {
return email != null && email.contains("@") && !email.startsWith("@");
}

A one-line method is worth writing when the name explains a rule that is otherwise a cryptic expression.

Static versus instance

static is right for a pure function that needs no object state: a calculation, a parser, a formatter. Instance methods are right when the behaviour depends on fields.

A class with only static methods is a namespace, which Java allows and often uses for utilities. A class with a mix needs care: a static method cannot read instance fields, and calling one from the other is a sign the design is unclear.

Documenting

A short comment above a non-obvious method explaining why it exists is worth more than a restatement of the code. Javadoc on public API methods is the convention for libraries:

/**
* Returns the price including tax, rounded to the nearest paise.
*/
public static long withTax(long paise) {

Do not write "returns the price with tax" for a method called withTax; say the part a reader could not guess, such as the rounding rule.

A method that both prints and returns a value, so callers cannot use it in a calculation without producing output. Split it: one method returns the string, another prints it.

Write a method slug(String title) that lowercases, trims, replaces runs of spaces with a hyphen and removes punctuation. Add a second method that returns the slug with a numeric suffix when it is empty. Test both.

Show solution
public class Slugs { static String slug(String title) { String cleaned = title.strip().toLowerCase() .replaceAll("[^a-z0-9\s-]", "") .replaceAll("\s+", "-"); return cleaned; } static String uniqueSlug(String title, int fallback) { String base = slug(title); return base.isEmpty() ? "post-" + fallback : base; } public static void main(String[] args) { System.out.println(slug(" Java: The Basics! ")); System.out.println(uniqueSlug("!!!", 7)); } }

The first method does one transformation and returns it; the second adds the fallback rule. Splitting them means the fallback can change without touching the cleaning logic, and each can be tested with one call.

Recap

  • A method’s name lets callers avoid reading its body; keep the name honest about effects.
  • Validate and return early, and keep the happy path unindented.
  • Prefer a small record to a long parameter list, and extract blocks with a clear purpose.

Next, parameters and return values in more depth, including when to return an empty value.

Should methods be static?
When they need no object state. Utility calculations usually are; behaviour tied to data is not.
Can a method return more than one value?
Not directly. Return a record, an array, or a small class with named fields.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.