A method in Java is a named block of code that you run with arguments and that usually hands a result back to you. 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 that you can test one piece at a time.
This is the first lesson in the Methods and Scope module, and the next lesson in this module is about "How Do Parameters and Return Values Flow Through Methods?".
What are the parts of a method declaration?
Every method declaration has the same skeleton. There is an access modifier, there is a return type, there is a name, and there is a parameter list in brackets. The return type says what kind of value comes back, and void is the special value that means that 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 the line static void printBanner(String title) piece by piece. The word static means that the method is called without an object. The word void means that it produces no result. The name printBanner is the name that you will call. And String title is the single parameter that 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 here. First, you can call a method directly inside the argument list of another call, as the last line does, and that keeps the intermediate results out of variables that 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 that you would say out loud.
How do void methods and value-returning methods differ?
A void method does its work and then it ends. A method with a return type produces a value, and the return statement names that value. 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, you can store it, and you can pass it on. A void method gives you nothing to do any of that with. If you find yourself wanting to use the result of a void method, then that is a signal that 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, then every change risks breaking the whole program. When the work sits in a named method, then 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 one of them needs to know about the other one, and both of them 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, and it is 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: finishThe method prepare was defined before finish in the file, but it was 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 in this example are different from the ones earlier in the lesson. They have no static keyword, so they belong to an individual object and they can use the data that the object holds. That is the difference between a utility method and a method on a thing, and you will meet it in detail when the classes get their own module.
Recap
- A declaration is an access modifier, a return type, a name and a parameter list.
- void means the method produces no value, and 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, so if you want to use the result then you return it instead of printing it.
Try it yourself: write a class with three methods for a small order system. One of them formats a line item as a string, one of them adds up the prices that you pass it, and one of them prints a receipt header. Call them in a different order from the one in which you defined them, 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.