Sub topic 10
Methods: Parameters and Return Values
What This Chapter Covers
So far, your programs have mostly been one long list of statements inside main. That works for tiny programs, but real software needs a way to break work into named, reusable pieces. In Java, those pieces are called methods. A method is a named block of code that does one job, can be given input, and can hand back a result.
This chapter assumes you already know how to write and run a simple Java program, declare variables with types, and use if statements and loops. We will build directly on those skills.
By the end, you will be able to:
- Define methods with parameters (the inputs a method accepts) and return values (the output a method produces)
- Call methods and use their results
- Choose between returning a value and returning nothing (
void) - Avoid common mistakes like forgetting a return value or misusing the
statickeyword
Why Methods Matter
Imagine you need to compute a sales tax amount in ten places in a program. Without methods, you copy the same formula ten times. If the tax rate changes, you must find and fix every copy. With a method, the formula lives in exactly one place, has a name you can recognize, and can be reused everywhere.
Methods give you three benefits:
- Reuse: write once, call many times.
- Naming:
calculateTax(price)describes intent better than a bare formula. - Testing and debugging: a small method is easy to check in isolation.
The Shape of a Method
Every method declaration has the same parts:
// access static? returnType name(parameters) { body }
public static int add(int a, int b) {
return a + b;
}| Part | Meaning | Example |
|---|---|---|
| Access modifier | Who is allowed to call it | `public` |
| `static` (optional) | Belongs to the class itself, not to an object | `static` |
| Return type | The type of value the method gives back | `int` |
| Name | What it is called; use camelCase | `add` |
| Parameters | Named inputs with types | `int a, int b` |
| Body | The statements that run when called | `return a + b;` |
| `return` | Sends a value back and exits the method | `return a + b;` |
A method with no return value uses the special type void. It still performs work, such as printing, but it hands back nothing.
A Complete First Example
Here is a full runnable program. Type it into a file named MethodDemo.java, compile it with javac MethodDemo.java, and run it with java MethodDemo.
public class MethodDemo {
// A method with two parameters and an int return value
public static int add(int a, int b) {
return a + b;
}
// A method that returns nothing: it just prints
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
int sum = add(3, 4); // call add, store the result
System.out.println("Sum: " + sum);
greet("Ada"); // call greet, ignore "result" (there is none)
}
}Output:
Sum: 7
Hello, Ada!Walk through what happens when add(3, 4) runs:
- The program reaches the expression
add(3, 4). - Java creates the method's parameters
aandband copies3intoa,4intob. These copied values are called arguments. - The body runs:
return a + b;computes7. - The method exits, and the whole expression
add(3, 4)becomes the value7. - That value is stored in
sum.
The words matter: parameters are the names in the method declaration (a, b); arguments are the actual values you pass when calling (3, 4).
Return Values in Detail
The return type is a promise. If you declare int, every possible path through the method must produce an int to return. Java checks this at compile time.
public class ReturnDemo {
// Every branch returns an int, so this compiles
public static String verdict(int score) {
if (score >= 60) {
return "pass";
} else {
return "fail";
}
}
public static void main(String[] args) {
System.out.println(verdict(82)); // pass
System.out.println(verdict(40)); // fail
}
}Two important rules:
returnexits the method immediately. Nothing after it in that path runs.- A method like
verdictmust return on every path. If one path can reach the closing brace without areturn, the compiler reports a missing return statement error.
A void method may still use a bare return; to exit early:
public static void printIfPositive(int n) {
if (n <= 0) {
return; // exit early, return nothing
}
System.out.println(n);
}Parameters in Detail
Parameters are typed, and Java checks argument types at compile time. You cannot call add("3", 4); the compiler rejects it.
Rules worth knowing:
- Order and count must match.
add(4, 3)andadd(3, 4)are both fine here, but if the parameters meant(price, quantity), swapping them changes the meaning even though it compiles. - Arguments are copied. For
int,double,boolean, and other primitive types, the method gets a copy. Changing a parameter inside the method does not affect the caller's variable. - You can have zero or many parameters, separated by commas.
public class CopyDemo {
public static void tryToChange(int n) {
n = n * 100; // changes only the local copy
}
public static void main(String[] args) {
int value = 5;
tryToChange(value);
System.out.println(value); // still 5
}
}A Method That Builds on Loops and Arrays
Methods combine well with what you already know. Here is a method that takes an array (a fixed-size list of values) and returns the largest element:
public class MaxDemo {
public static int max(int[] numbers) {
int best = numbers[0]; // start with the first element
for (int n : numbers) { // enhanced for loop over the array
if (n > best) {
best = n;
}
}
return best;
}
public static void main(String[] args) {
int[] scores = {42, 91, 7, 63};
System.out.println("Highest score: " + max(scores));
}
}Notice the flow: data goes in through the parameter, computation happens in the body, and a single result comes out through return. That input-process-output shape is the standard pattern for a good method.
Here is the flow of a call in sequence form:
The `static` Keyword: Why It Appears
You may have noticed static on every method so far. static means the method belongs to the class itself, not to an object created from the class. This matters right now for one big reason: main is static, and while your programs only use plain methods, those methods must also be static so main can call them directly.
If you omit static on a helper method and call it from main, you get the error non-static method cannot be referenced from a static context. For the programs in this tutorial, add static to your helper methods and the problem disappears. In the chapters on classes and objects, you will learn the non-static style, where methods belong to objects.
Common Errors and How to Fix Them
| Error message | Cause | Fix |
|---|---|---|
| missing return statement | Some path through a non-void method has no `return` | Add a `return` on every path, often with a final `return` after an `if` |
| incompatible types | Returned value's type does not match the declared return type | Match the types, or change the declared return type |
| non-static method cannot be referenced from a static context | Calling a non-`static` method from `main` | Mark the helper `static` for now |
| method not found / cannot find symbol | Misspelled name, wrong argument count, or wrong types | Check name, parameter order, and types at the call site |
A subtle mistake beginners make: calling a method but ignoring its result.
add(2, 2); // computes 4, throws it away
int sum = add(2, 2); // correct: capture the resultCalling a value-returning method without using the result is legal Java, but almost always a bug.
Design Tips for Good Methods
- One job per method. If you need "and" to describe it, split it.
- Name it with a verb.
calculateTotal,isValid,printReport. - Keep parameter lists short. More than three or four inputs is a warning sign.
- Prefer returning a value over printing. A method that returns
totalcan be printed, tested, or reused; one that only prints cannot.
Exercises
Exercise
What is the difference between a parameter and an argument?
Show answer
A parameter is the named variable in the method declaration (for example, int a in add(int a, int b)). An argument is the actual value you pass when calling the method (for example, 3 in add(3, 4)). Parameters are declared; arguments are supplied.
Exercise
What is wrong with this method, and how do you fix it? public static int sign(int n) { if (n > 0) { return 1; } else if (n < 0) { return -1; } }
Show answer
When n is 0, no return statement runs, so the compiler reports a missing return statement. Add a final path, for example else { return 0; } or a trailing return 0; after the if/else chain.
Exercise
Write a method double average(int[] values) that returns the average of the array elements. You can compute the sum with a loop and divide by values.length.
Show answer
For example:
public static double average(int[] values) {
int total = 0;
for (int v : values) {
total += v;
}
return (double) total / values.length;
}
The cast (double) forces decimal division instead of integer division.
Exercise
This program prints what? public static void main(String[] args) { int x = 10; bump(x); System.out.println(x); } public static void bump(int n) { n = n + 1; }
Show answer
It prints 10. Primitive arguments are copied, so bump changes only its local copy n, not x in main.