A method in Java is a named block of code you run with arguments and, usually, hand a result back to. Defining one takes a return type, a name and a parameter list, and calling one is the name followed by arguments in brackets. Splitting a program into methods is the first step towards code you can test one piece at a time.
What are the parts of a method declaration?
Every method declaration has the same skeleton: an access modifier, a return type, a name, and a parameter list in brackets. The return type says what kind of value comes back, and void is the special value that means nothing comes back at all.
public class MethodBasics {
static void printBanner(String title) {
System.out.println("== " + title + " ==");
}
static int addMinutes(int a, int b) {
return a + b;
}
public static void main(String[] args) {
printBanner("Study plan");
int total = addMinutes(30, 45);
System.out.println("Total study time: " + total + " minutes");
System.out.println("In whole hours: " + addMinutes(30, 45) / 60);
}
}Read static void printBanner(String title) piece by piece: static means it is called without an object, void means it produces no result, printBanner is the name you will call, and String title is the single parameter it expects. The second method, addMinutes, declares an int return type, so its return statement hands an int back to whoever called it.
The program prints three lines:
== Study plan ==
Total study time: 75 minutes
In whole hours: 1Two habits are worth copying. First, you can call a method directly inside the argument list of another call, as the last line does, which keeps intermediate results out of variables you never use. Second, the method name says what the method does and the parameters say what it works on, so the call site reads almost like the sentence you would say out loud.
How do void methods and value-returning methods differ?
A void method does its work and ends. A method with a return type produces a value, and the return statement names it. That difference decides how each one is used: a void method is called for its effect, while a returned value is normally assigned to a variable or passed straight into another call.
public class VoidVsReturn {
static void shout(String word) {
System.out.println(word.toUpperCase() + "!");
}
static String quiet(String word) {
return word.toLowerCase() + "...";
}
public static void main(String[] args) {
shout("focus");
System.out.println(quiet("FOCUS"));
System.out.println(quiet("FOCUS").length());
}
}The output is:
FOCUS!
focus...
8The last line is the giveaway that a returned value is a first-class result: you can ask it for its length, store it, or pass it on. A void method gives you nothing to do that with. If you find yourself wanting to use the result of a void method, that is a signal the method should return the value instead of printing it.
Why split a program into small methods?
A method with one job can be named, understood and tested on its own. When the work is inlined in main, every change risks breaking the whole program; when it sits in a named method, you change that method and the rest of the code keeps working as it did.
public class OneJobEach {
static String describeSubject(String subject, int minutes) {
return subject + " (" + minutes + " min)";
}
static int totalMinutes(int[] sessions) {
int sum = 0;
for (int s : sessions) {
sum += s;
}
return sum;
}
public static void main(String[] args) {
int[] sessions = {25, 40, 15};
String[] subjects = {"Arrays", "Loops", "Methods"};
for (int i = 0; i < sessions.length; i++) {
System.out.println(describeSubject(subjects[i], sessions[i]));
}
System.out.println("Total: " + totalMinutes(sessions) + " minutes");
}
}The output reads like a report rather than like code:
Arrays (25 min)
Loops (40 min)
Methods (15 min)
Total: 80 minutesNotice that describeSubject knows nothing about arrays and totalMinutes knows nothing about printing. Neither needs to know about the other, and both can be reused in a completely different program. That independence is the whole point of cutting a program into methods.
What order do methods actually run in?
Java runs a method body from the first statement to the last, and a method that calls another method runs that inner method to completion before it carries on. The order is always the order of the calls, never the order of the definitions in the file.
public class MethodCallOrder {
static void step(String name) {
System.out.println("step: " + name);
}
static void prepare() {
step("prepare");
step("review");
}
static void finish() {
step("finish");
}
public static void main(String[] args) {
step("start");
prepare();
finish();
}
}The output is:
step: start
step: prepare
step: review
step: finishprepare was defined before finish in the file but called before it, so it ran first. There is no such thing as a method running in the background: a call is a pause in the current method until the called method returns. That is also why a method that never returns, whether by accident or by design, freezes everything that is waiting on it.
Where do methods live in a Java program?
Every method lives inside a class, because Java has no free-floating functions. That is why even a program with a single method is written as a class with a main entry point. A single source file may also hold more than one class, as long as only one of them is public and its name matches the file name.
public class InstanceMethod {
public static void main(String[] args) {
Counter tally = new Counter();
tally.increase();
tally.increase();
System.out.println("count = " + tally.getCount());
}
}
class Counter {
private int count;
void increase() {
count++;
}
int getCount() {
return count;
}
}The output is count = 2. The methods here are different from the ones earlier in the lesson: they have no static keyword, so they belong to an individual object and can use the data that object holds. That is the difference between a utility method and a method on a thing, and you will meet it in detail when classes get their own module.
Recap
- A declaration is an access modifier, a return type, a name and a parameter list.
voidmeans the method produces no value; any other return type means it hands one back.- Give every method one job and one name that says what the job is.
- Calling a method runs it to completion before the caller continues, and the call order decides the output order.
- Methods always live inside a class, and a file may contain several classes as long as one is public and matches the file name.
- A void method is called for its effect; if you want to use the result, return it instead of printing it.
Try it yourself: write a class with three methods for a small order system: one that formats a line item as a string, one that adds up the prices you pass it, and one that prints a receipt header. Call them in a different order from the one you defined them in and check that the output order follows the calls. Then change the receipt header method so it returns the header text instead of printing it, and use that returned value inside the receipt printing.