Methods in Java — theory with Laura’s final grade, the call stack and overloading (and the static I deleted because I didn’t know what it did)
The first time I wrote a method in Java I copied the header from the lecture notes as it was: public static double finalGrade(double theory, double practice). It worked. But one word bothered me, static, because nobody had told me what it did. So I did what anyone in a hurry would do: I deleted it, “to see what happens”. Something happened:
public class Hook {
// I removed the static "because I didn't know what it did". Error: main is static
// and from there you can't call a method that isn't.
public double finalGrade(double theory, double practice) {
return theory * 0.6 + practice * 0.4;
}
public static void main(String[] args) {
System.out.println(finalGrade(7.5, 6.0));
}
}
When compiling:
Hook.java:10: error: non-static method finalGrade(double,double) cannot be referenced from a static context
System.out.println(finalGrade(7.5, 6.0));
^
1 error
Half an hour staring at that line. The method was well written, the calculation was right, and the error talked about a “static context” I had never asked for. The problem was exactly the word I had removed: main is static, and from a static place you can only call other static methods directly. With the word back in place, everything works again:
public class HookFixed {
// With static, main can call it without creating any object
public static double finalGrade(double theory, double practice) {
return theory * 0.6 + practice * 0.4;
}
public static void main(String[] args) {
System.out.printf("FP2 final grade: %.2f%n", finalGrade(7.5, 6.0));
}
}
FP2 final grade: 6.90
Today we’re going to take that header apart piece by piece, so that none of them scares you and you don’t delete any “to see what happens”. We come from the Java loops exercises, where the guessing game had a block that was repeated and the prime check lived inside two loops with a flag. By the end of this article, both will be methods with a name. The running example is still Laura, the FP2 student from the previous topics: her final grade, her enrolment fee and her grades per subject. When you finish, you have the methods in Java practice with three complete programs.
In a nutshell: A method in Java is a named block of code that does a task and that you can call as many times as you want, passing it parameters and getting a result back with return (or nothing, if it’s void). Java passes parameters by value and allows overloading: several methods with the same name and different parameters.
Table of Contents
Before you start. For this topic you only need to declare variables with their type (int, double, boolean, String), write an if/else and a loop as in the previous topics and, if you come from FP1, to have written some function with def and return in Python. Nothing else. The topic has four big ideas, in this order: what a method is and how to read its header, piece by piece (public, static, the return type, the name and the parameters); how you call a method and what happens with what it returns; what goes on in memory on every call (parameters are copies and each call has its own frame on the stack); and overloading, which lets you use the same name with different parameters. If you get lost at any point, go back to Laura’s final grade: finalGrade(7.5, 6.0) gives 6.9, and the whole topic can be told with that line.
From function to method: what is a method in Java?
A method is a named block of code that does a task, can receive data (the parameters) and can return a result. If you come from Python, it’s what you called a function there:
def final_grade(theory, practice):
return theory * 0.6 + practice * 0.4
print(final_grade(7.5, 6.0))
Java has no loose functions. Everything lives inside a class, and a function that lives inside a class is called a method. For now, while we haven’t seen classes, you’ll write your methods inside the same class as main, at the same level:
public class LauraGrades {
// The calculation lives in ONE place: if the theory weight changes, it is changed here and nowhere else
public static double finalGrade(double theory, double practice) {
return theory * 0.6 + practice * 0.4; // 60 % theory, 40 % practice
}
public static void main(String[] args) {
// Two calls, two subjects: each one passes its own data
System.out.printf("FP2: %.2f%n", finalGrade(7.5, 6.0));
System.out.printf("IC2: %.2f%n", finalGrade(5.0, 8.5));
}
}
FP2: 6.90 IC2: 6.40
Notice three things. First: finalGrade is outside main but inside the class. A method never goes inside another method; if you try, javac gets lost with brace errors that have nothing to do with it. Second: the calculation is written once and used twice, each time with different data. For FP2, 7.5 × 0.6 + 6 × 0.4 = 4.5 + 2.4 = 6.9; for IC2, 5 × 0.6 + 8.5 × 0.4 = 3 + 3.4 = 6.4. Third: if tomorrow the theory weighs 70 %, you change a number in one place, not in every subject.
These programs were run once on a computer set to Spanish, where printf writes the decimal comma (6,90). In this article the outputs of the theory programs are shown with the decimal point you would see on an English-language computer. You’ll see below that when a double is joined to a text with +, Java always writes a point, whatever the language of the computer.
The header, built from Python
Before giving each piece its name, let’s build the header of finalGrade in our heads, starting from the Python function you already know. The idea is this: Java wants to know in advance things that Python works out as it goes. Each new word in the header is the answer to one of those questions.
| Step | What it looks like | Why |
|---|---|---|
| 1. What you already had | final_grade(theory, practice) | The name and the parameters are the same idea in both languages: a name for the task and some slots for the data. |
| 2. Name in camelCase | finalGrade(theory, practice) | In Java, methods are written in camelCase, starting with a lowercase letter. It’s a convention, but everyone follows it. |
| 3. Type of each parameter | finalGrade(double theory, double practice) | Java sets aside room for each parameter before running anything, so it needs to know what fits in it. Grades have decimals: double. |
| 4. Type of what comes out | double finalGrade(double theory, double practice) | Whoever calls it has to know what they’ll get back. 7.5 × 0.6 + 6 × 0.4 has decimals: double. In Python you wrote nothing here. |
5. static | static double finalGrade(…) | main is static and you’re going to call finalGrade from there, without creating any object. The full reason, in its own section. |
6. public | public static double finalGrade(…) | It says who can call it. For now, anyone. |
| 7. The body | { return theory * 0.6 + practice * 0.4; } | The braces replace Python’s colon and indentation, and the statement ends with a semicolon. |
Now you have the whole line, the same one I copied from my notes without understanding it. No word is there for decoration: three say what goes in and what comes out (the two parameter types and the return type) and two say who can call the method and how (public and static). What comes next is giving each piece its official name.
Anatomy of a method
Let’s go with the line that made me delete the static. Each word has a specific job:
| Piece | What it is | In finalGrade |
|---|---|---|
| Visibility | Who can call the method | public |
static | The method belongs to the class, not to an object (we’ll see it shortly) | static |
| Return type | The type of what it returns, or void if it returns nothing | double |
| Name | In camelCase, starts with a lower-case letter and is usually a verb or what it calculates | finalGrade |
| Parameters | In brackets, each with its type and name, separated by commas | (double theory, double practice) |
| Body | Between braces: what it does when called | { return …; } |
Everything before the brace is called the method header or signature (strictly speaking, the signature is only the name plus the parameter types; you’ll see why with overloading). The drawing also shows the call: the arguments 7.5 and 6.0 are copied, in order, into the parameters theory and practice. A parameter is the variable in the header; an argument is the actual value you pass when calling. That distinction comes up in quizzes.
Passing the arguments in a different order. finalGrade(6.0, 7.5) compiles without a warning and gives 6.6 instead of 6.9: Java copies the first argument into the first parameter and the second into the second, without looking at what you meant. So theory is 6.0 and practice is 7.5, and the maths is 6 × 0.6 + 7.5 × 0.4 = 3.6 + 3 = 6.6. When two parameters have the same type, the compiler can’t warn you: check the header before calling.
The access modifier: public and private
In Python everything is accessible from anywhere; at most, an underscore in front of the name is a convention for “this is internal, don’t touch it”. Java does prevent it, with access modifiers:
public: the method can be called from any class of your program.private: it can only be called from inside the same class. If another class tries, it doesn’t compile.- Nothing: visible to the classes in the same package (package-private). You’ll see it calmly with classes and inheritance, together with
protected.
When do I use each one? public for what others will use (the “face” of your class) and private for the intermediate steps that only make sense inside. In the practice you’ll see a password validator with four private checks and a single public isValid.
If in doubt, start with private and open it up to public when another class really needs it. It’s easier to open a door than to close it once there’s code using it.
The return type: what Python never made you state
In Python, a function can return a number on one path and a text on another, and nobody complains until something blows up. In Java, the return type is a promise that the compiler checks before running anything. Three ways to break it, all three with their real error.
First: a path without return. For you it’s clear that a grade is either a pass or not; for javac, the “not” path reaches the end of the method without returning anything:
public class NoReturn {
// For us it is clear: if the grade is >= 5, true. But what if it isn't?
// That path reaches the end of the method without any return.
public static boolean passed(double grade) {
if (grade >= 5) {
return true;
}
}
public static void main(String[] args) {
System.out.println(passed(6.9));
}
}
NoReturn.java:9: error: missing return statement
}
^
1 error
The little arrow points at the closing brace: that’s where the method would be left without a return. The compiler doesn’t reason with numbers: it doesn’t know that if grade >= 5 is false “there’s nothing else left”. It only checks whether every path ends in a return. You fix it with a return false; at the end or with an else.
Second: void with a value. void promises that the method returns nothing; a return with a value breaks the promise:
public class VoidWithValue {
// void promises to return NOTHING: a return with a value breaks the promise
public static void showGrade(double grade) {
System.out.println("Grade: " + grade);
return grade;
}
public static void main(String[] args) {
showGrade(6.9);
}
}
VoidWithValue.java:6: error: incompatible types: unexpected return value
return grade;
^
1 error
In a void method you can write a bare return; to leave early, but never return something;.
Third: the wrong type. You promise an int and return a double:
public class WrongType {
// It promises an int but returns a double: it would lose the decimals and Java won't do that without permission
public static int roundedGrade(double grade) {
return grade;
}
public static void main(String[] args) {
System.out.println(roundedGrade(6.9));
}
}
WrongType.java:5: error: incompatible types: possible lossy conversion from double to int
return grade;
^
1 error
It’s the same rule you saw in Java variables: going from double to int loses the decimals, and Java won’t do it unless you ask with a cast, (int) grade, or better (int) Math.round(grade) if you want to round rather than truncate.
An if / else if that “covers every case” and still gives missing return statement. It’s not a Java bug: the last else if might not hold and the compiler doesn’t do the maths. Always finish with a return outside the ifs or with an else without a condition.
To see why the compiler complains, go through the paths of passed one by one, as javac does:
| If the grade is… | What happens | Does it end in return? |
|---|---|---|
| 6.9 | It enters the if and runs return true; | Yes |
| 3.0 | It doesn’t enter the if, keeps going down and reaches the closing brace | No |
One path without return is enough for it not to compile. javac doesn’t try values: it looks at the shape of the code and asks whether there’s any way of reaching the closing brace without returning anything. Test yourself with this one, which has a catch:
public static boolean passed(double grade) {
if (grade >= 5) {
return true;
} else if (grade < 5) {
return false;
}
}
Check you’ve got it: does this method compile?
No. You get missing return statement, pointing at the closing brace. You know a grade is always >= 5 or < 5, but javac doesn’t evaluate the conditions: it only sees an else if that might not hold and, after it, no return. You fix it by changing else if (grade < 5) to a plain else, or by putting return false; after the if.
Parameters also need a type
Each parameter carries its type in front, one by one, even if it repeats. (double theory, practice) doesn’t compile: it has to be (double theory, double practice). Inside the method, each parameter is just another local variable, born with the value of the argument and gone when the method ends.
A method can receive parameters of different types. Laura’s enrolment fee depends on an integer, a decimal number and a yes/no:
public class Enrolment {
// Three parameters, each with its type: int, double and boolean
public static double enrolmentFee(int credits, double creditPrice, boolean largeFamily) {
double total = credits * creditPrice;
if (largeFamily) {
total = total * 0.5; // 50 % discount (made-up figure for the example)
}
return total;
}
// Overloading: the same operation with one parameter fewer. It acts as a "default value":
// if you say nothing, there is no discount. It doesn't repeat the calculation: it calls the full version.
public static double enrolmentFee(int credits, double creditPrice) {
return enrolmentFee(credits, creditPrice, false);
}
public static void main(String[] args) {
System.out.printf("Laura, 60 credits: %.2f €%n", enrolmentFee(60, 15.20));
System.out.printf("With large-family discount: %.2f €%n", enrolmentFee(60, 15.20, true));
System.out.printf("FP2 only (6 credits): %.2f €%n", enrolmentFee(6, 15.20));
}
}
Laura, 60 credits: 912.00 € With large-family discount: 456.00 € FP2 only (6 credits): 91.20 €
The maths: 60 × 15.20 = 912; with the 50 % discount, 456; and 6 × 15.20 = 91.20 for a single subject. The prices and the discount are made up for the example: they’re not the ULPGC’s.
Look at the second enrolmentFee. Python has parameters with default values (def fee(credits, credit_price, large_family=False)); Java doesn’t. What you do is write another version with fewer parameters that calls the full one with the “default” value. That’s called overloading, and it has its own section further down.
static: for now, “that’s just how it’s done”
Back to the error at the start. static means the method belongs to the class and not to a particular object created with new. You haven’t created your own objects yet (that comes with classes and objects in Java), so the practical rule for this topic is simple:
mainisstatic: Java calls it without creating any object.- From a
staticmethod you can only call the class’s otherstaticmethods directly. - So, while everything is in one class with
main, all your methods arestatic.
If you remove static, the method becomes an instance method: it needs an object to be called (new Hook().finalGrade(7.5, 6.0)). From main there’s no object, hence the message at the start: non-static method finalGrade(double,double) cannot be referenced from a static context. In plain words: “this method needs an object, and here, in a static context, there isn’t one”.
The rule isn’t only for main: it applies to any static method. These are the situations you’ll come across in this topic:
| From… | You call… | Does it compile? | Why |
|---|---|---|---|
main (static) | finalGrade, static, in the same class | Yes, with finalGrade(7.5, 6.0) | Both belong to the class: no object needed. |
main (static) | classify, static, in another class | Yes, with Grades.classify(6.9) | It also belongs to a class; you just have to say which one. |
nextPrime (static) | isPrime (static) | Yes | The “static context” isn’t only main: it’s the body of any static method. |
main (static) | A method without static | No | That method needs an object, and in main you haven’t created one. |
Check you’ve got it: if you remove the static from classify (in the Grades class) and main still calls Grades.classify(6.9), what happens?
It doesn’t compile, with the same error as at the start: non-static method classify(double) cannot be referenced from a static context. It doesn’t matter that the call has the class name in front: Grades.classify(…) only works if classify belongs to the class (static). Without static, the method belongs to each Grades object, and main hasn’t created any.
Removing static from a method and, when the error shows up, putting it on everything “so it compiles”, including class attributes. In this topic it’s right for everything to be static; when classes arrive, static will be the exception, not the rule, and marking a piece of data static by accident makes all the objects share it.
Calling a method in Java
Calling a method means writing its name with the arguments in brackets, as you’ve done with System.out.println(…) since day one. The interesting part is what you do with what it returns:
// A second class in the same file (no public): its static methods are called with its name in front
class Grades {
public static String classify(double grade) {
if (grade >= 9) {
return "Distinction";
} else if (grade >= 7) {
return "Merit";
} else if (grade >= 5) {
return "Pass";
}
return "Fail"; // final path: if it didn't enter any if, it gets here
}
}
public class Calling {
// RETURNS a text: the caller decides what to do with it
public static String greeting(String name) {
return "Hello, " + name;
}
// Returns NOTHING (void): it does its job (printing) and that is it
public static void printGreeting(String name) {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
double fp2 = 6.9;
// 1. Store what it returns in a variable
String result = Grades.classify(fp2);
System.out.println("FP2: " + result);
// 2. Use it directly inside another expression
System.out.println("IC2: " + Grades.classify(6.4));
// 3. Use it as a condition (a method that returns boolean also works here)
if (Grades.classify(9.5).equals("Distinction")) {
System.out.println("Distinction with honours in sight");
}
// String versus void: the first can be stored or printed, the second is just called
String s = greeting("Laura");
System.out.println(s + " (printed by main)");
printGreeting("Laura");
}
}
FP2: Pass IC2: Pass Distinction with honours in sight Hello, Laura (printed by main) Hello, Laura
There are four ways of calling in that program:
- Store the result in a variable:
String result = Grades.classify(fp2);. Useful if you’re going to use it several times. - Use it inside another expression:
"IC2: " + Grades.classify(6.4). Java runs the method first and then concatenates what it returns. - Use it as a condition:
if (Grades.classify(9.5).equals("Distinction")). Any method that returns aboolean(or something you can compare, as here) can go inside anifor awhile. - Just call it, like
printGreeting("Laura");. That’s normal withvoidmethods.
And Grades.classify? classify lives in another class, Grades, so it’s called with the class name in front and a dot. It’s the same as Math.max(a, b) or Integer.parseInt("7"): static methods of other classes. If the method is in the same class as the caller, the class name can be left out. A .java file can contain several classes, but only one public one, named like the file.
The maths in the output: 6.9 is between 5 and 7, so FP2 is a “Pass”; 6.4 too. With 9.5 the if condition is true and the sentence is printed.
What happens, step by step, when you call a method
The four ways have something in common: Java first runs the method and then puts what the method returns in the place of the call. Follow the first one, String result = Grades.classify(fp2);, the way Java would:
| Step | What happens | Why |
|---|---|---|
| 1 | The argument is evaluated: fp2 is 6.9 | Java needs the value before going into the method. |
| 2 | classify starts with grade = 6.9 | The 6.9 is copied into the parameter. |
| 3 | grade >= 9, false; grade >= 7, false; grade >= 5, true | The conditions are checked in order and the first one that holds wins. |
| 4 | return "Pass"; and the method ends right there | return doesn’t just hand over the value: it leaves the method. The return "Fail"; at the end is never run. |
| 5 | In main, Grades.classify(fp2) is replaced by "Pass" | It’s as if you had written that text on the line. |
| 6 | result stores "Pass" and FP2: Pass is printed | The assignment collects what came back from the method. |
Step 4 is the one people forget most: return is an exit, not just a value. That’s why the return "Fail"; at the end doesn’t need an else in front of it: if the method reaches that line, it’s because none of the ifs returned anything before.
To read a line with calls, solve it from the inside out: first the method, then what surrounds it. "IC2: " + Grades.classify(6.4) becomes "IC2: " + "Pass", and that becomes "IC2: Pass". With Grades.classify(7) you’d get "Merit" (7 >= 7 is true), and with Grades.classify(4.99), "Fail".
public String name() versus public void name()
It’s a question that reaches Google word for word, and it has a short answer: one returns a text and the other returns nothing. greeting("Laura") works out "Hello, Laura" and hands it back to the caller, who decides whether to store it, print it or compare it. printGreeting("Laura") prints it itself and returns nothing, so there’s nothing to store. If you try to use a void method as if it returned something:
public class VoidInPrintln {
public static void printGreeting(String name) {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
// println needs a value to print, and a void method doesn't give one
System.out.println(printGreeting("Laura"));
}
}
VoidInPrintln.java:9: error: 'void' type not allowed here
System.out.println(printGreeting("Laura"));
^
1 error
'void' type not allowed here: println needs a value to print, and printGreeting doesn’t give one.
public String greeting(…) | public void printGreeting(…) | |
|---|---|---|
| Does it return something? | Yes, a String | No |
Does it have return value;? | Yes, on every path | No (at most return;) |
| Can it be stored? | String s = greeting("Laura"); | No |
| Who prints? | The caller, if it wants to | The method itself |
| When do I use it? | To work out something others reuse | For an action with an effect: printing, changing something |
When in doubt, let the method return and let the caller print. A method that returns can be used to print, compare, store or pass to another method; one that prints can only print.
Pass by value and the call stack
This is the hardest part, and the one that causes the most silent mistakes. Look at this program and try to guess the three lines before seeing the output:
public class PassByValue {
// grade is a COPY of the value passed in: changing it here doesn't touch main's variable
public static void raiseGrade(double grade) {
grade = grade + 1;
System.out.println("Inside raiseGrade: " + grade);
}
// The right way: return the new value and let the caller collect it
public static double raisedGrade(double grade) {
return grade + 1;
}
public static void main(String[] args) {
double grade = 6.5;
raiseGrade(grade);
System.out.println("In main, afterwards: " + grade);
grade = raisedGrade(grade); // now it works: the returned value is stored in grade
System.out.println("In main, collecting the return: " + grade);
}
}
Inside raiseGrade: 7.5 In main, afterwards: 6.5 In main, collecting the return: 7.5
Why doesn’t raiseGrade raise anything? Because Java passes arguments by value: the grade parameter of raiseGrade is a copy of main‘s 6.5, a different variable even though it has the same name. Adding 1 changes the copy; main‘s doesn’t notice.
To see it you need the call stack. Every time you call a method, Java opens a frame (a space of its own) on top of the caller’s frame, with the method’s parameters and local variables. When the method ends, its whole frame disappears, with all its variables. The only thing that survives is what return hands back:
In step 1 there are two different grade variables, one in each frame. In step 2 the raiseGrade frame no longer exists and main‘s is still 6.5. In step 3, raisedGrade returns 7.5 and this time main collects it with grade = raisedGrade(grade);.
The PassByValue trace, line by line
The drawing sums up three moments. This is the full run, without skipping a single line. The column that matters is the second one: main‘s grade.
| Line being run | grade in main | Frame on top | Printed | Why |
|---|---|---|---|---|
double grade = 6.5; | 6.5 | None | main creates its variable. | |
raiseGrade(grade); | 6.5 | raiseGrade: grade = 6.5 | A new frame opens and the 6.5 is copied into the parameter. | |
grade = grade + 1; | 6.5 | raiseGrade: grade = 7.5 | It changes the grade in the frame on top, the only one that method can see. | |
println in raiseGrade | 6.5 | raiseGrade: grade = 7.5 | Inside raiseGrade: 7.5 | It prints the copy. |
End of raiseGrade | 6.5 | Disappears | It’s void: it returns nothing and the 7.5 is lost with the frame. | |
println in main | 6.5 | None | In main, afterwards: 6.5 | main reads its own grade, which nobody has touched. |
grade = raisedGrade(grade); | 7.5 | raisedGrade: grade = 6.5; returns 7.5 and disappears | The return takes the 7.5 out of the frame and main‘s assignment stores it. | |
Last println | 7.5 | None | In main, collecting the return: 7.5 | Now main‘s has changed. |
Compare the fifth row with the seventh: that’s the whole section in two lines. In both, the frame disappears; the difference is that in the seventh something comes out through the return and main collects it.
Check you’ve got it: if in main you write raiseGrade(grade); twice in a row, what gets printed and what is grade in main at the end?
Inside raiseGrade: 7.5 is printed twice, and grade is still 6.5 in main. Each call opens a new frame and gets a fresh copy of main‘s 6.5; the 7.5 from the first call died with its frame, so the second one doesn’t start from it.
The outputs here have a point (7.5) even on the Spanish computer: the double is joined to a text with +, which uses Double.toString and always writes a point, regardless of the computer’s language. printf does look at it. If an exam asks for a particular format, use printf.
The same happens with local variables: they live in their frame and nobody outside sees them. If you try to use, from main, a variable declared inside another method:
public class Scope {
public static double finalGrade(double theory, double practice) {
double result = theory * 0.6 + practice * 0.4; // result only exists in here
return result;
}
public static void main(String[] args) {
finalGrade(7.5, 6.0);
System.out.println(result); // main doesn't know the local variables of another method
}
}
Scope.java:10: error: cannot find symbol
System.out.println(result); // main doesn't know the local variables of another method
^
symbol: variable result
location: class Scope
1 error
cannot find symbol: for main, result doesn’t exist. The way to get data out of a method is to return it and collect it, never “read its variable”.
Calling a method that returns something and not collecting the result: doubleIt(n); instead of n = doubleIt(n);. It compiles without a single warning and the calculated value is lost. You’ll see it as a “What’s wrong here?” snippet in the exercises.
With arrays and objects a copy is also made, but what gets copied is a reference (an arrow to the same data), so a method can change the contents of an array it receives. You’ll see it in the next topic, arrays in Java, and calmly in classes and objects.
Method overloading
In Java you can have several methods with the same name in the same class, as long as they differ in their parameters: a different number or different types. It’s called overloading. You’ve already seen it in enrolmentFee, and you use it without knowing every time you write System.out.println, which has a version for int, another for double, another for String…
How does Java decide which one to call? It’s best to see it. Each version of average prints its signature before returning the result:
public class Overloading {
// Three methods with the same name. Each one prints its signature so you can see which one Java picks.
public static double average(int a, int b) {
System.out.print("[int, int] ");
return (a + b) / 2.0; // 2.0 and not 2: otherwise, (7 + 8) / 2 would be integer division (7)
}
public static double average(double a, double b) {
System.out.print("[double, double] ");
return (a + b) / 2;
}
public static double average(int a, int b, int c) {
System.out.print("[int, int, int] ");
return (a + b + c) / 3.0;
}
public static void main(String[] args) {
System.out.println(average(7, 8)); // two ints: the exact version
System.out.println(average(7, 8.5)); // int and double: the 7 becomes 7.0
System.out.println(average(7, 8, 9)); // three arguments: the three-parameter one
System.out.println(average(7.5, 6.0)); // two doubles
}
}
[int, int] 7.5 [double, double] 7.75 [int, int, int] 8.0 [double, double] 6.75
Java follows two steps. First it counts the arguments: with three, only average(int, int, int) fits. Then it looks for the version that fits with the fewest conversions: average(7, 8) fits (int, int) as it is; average(7, 8.5) doesn’t fit (int, int) because 8.5 isn’t an int, but it does fit (double, double) by turning 7 into 7.0, a conversion Java makes on its own because nothing is lost. The maths: (7 + 8) / 2.0 = 7.5; (7 + 8.5) / 2 = 7.75; (7 + 8 + 9) / 3.0 = 8; (7.5 + 6) / 2 = 6.75.
The program’s four calls, one by one:
| Call | Arguments | Versions it fits | Picks | Why |
|---|---|---|---|---|
average(7, 8) | 2 | (int, int) as it is; (double, double) converting both | (int, int) | The one that needs no conversion wins. |
average(7, 8.5) | 2 | Only (double, double) | (double, double) | 8.5 doesn’t fit in an int; the 7 does become 7.0 without losing anything. |
average(7, 8, 9) | 3 | Only (int, int, int) | (int, int, int) | It’s the only one with three parameters. |
average(7.5, 6.0) | 2 | Only (double, double) | (double, double) | A double doesn’t go into an int without a cast. |
Check you’ve got it: which version does average(7.0, 8) pick and what does it print? And average(7, 8, 9.0)?
average(7.0, 8) picks (double, double): 7.0 doesn’t fit in an int, and the 8 does become 8.0. It prints [double, double] 7.5, because (7 + 8) / 2 = 7.5.
average(7, 8, 9.0) doesn’t compile. With three arguments, the only candidate is average(int, int, int), and 9.0 can’t become an int without losing decimals: possible lossy conversion from double to int. Java doesn’t go looking for another version with a different number of parameters; it counts first, and if the one left doesn’t fit, error.
Why / 2.0 in the int version? Because (7 + 8) / 2 between two int values is integer division and would give 7, not 7.5. The usual trap, now hidden inside a method.
There are two cases that don’t compile and that come up in quizzes. The first is ambiguity: if there are average(int, double) and average(double, int), the call average(7, 8) fits both by converting one int, and Java won’t choose:
public class Ambiguous {
public static double average(int a, double b) {
return (a + b) / 2;
}
public static double average(double a, int b) {
return (a + b) / 2;
}
public static void main(String[] args) {
// With (7, 8) both fit by turning one int into a double: Java can't choose
System.out.println(average(7, 8));
}
}
Ambiguous.java:13: error: reference to average is ambiguous
System.out.println(average(7, 8));
^
both method average(int,double) in Ambiguous and method average(double,int) in Ambiguous match
1 error
The second: changing only the return type is not overloading. Two methods with the same name and the same parameters are the same method written twice, whatever they return:
public class OnlyReturn {
public static double average(int a, int b) {
return (a + b) / 2.0;
}
// Same name and same parameters: changing only the return type is NOT overloading
public static int average(int a, int b) {
return (a + b) / 2;
}
public static void main(String[] args) {
System.out.println(average(7, 8));
}
}
OnlyReturn.java:8: error: method average(int,int) is already defined in class OnlyReturn
public static int average(int a, int b) {
^
1 error
It makes sense: in a call like average(7, 8); without storing the result, Java would have no clue to choose. That’s why a method’s signature is its name plus its parameter types, without the return type.
This is also what lies behind a very common exercise on the web: write three calculateAverage methods, with two, three and four double parameters. Each one is an overload, and Java picks it by counting the arguments.
A very handy use of overloading is the one you saw in the enrolment fee: the short version calls the long one with a fixed value. That way the calculation lives in one method and the short version repeats nothing. You’ll use it in the exercises with a readInt that has a version with a range and one without.
Types of methods in Java
Another popular search: “types of methods in Java”. There’s no official list, but they’re classified by three questions, and each method answers all three at once:
| Question | Options | Example from this topic |
|---|---|---|
| Does it return something? | With a return type (int, double, String, boolean…) or void | finalGrade returns double; printGreeting is void |
| Whose is it? | The class’s (static) or an instance’s (no static, needs an object) | All the ones in this topic are static; instance ones come with classes |
| Who can see it? | public, private, protected or no modifier | isValid public; its checks private |
There are also two “types” with names of their own that you’ll see soon: constructors (named like the class and with no return type, not even void) and getters and setters (getGrade(), setGrade(…)), which are ordinary instance methods with a naming habit. Both come in classes and objects. And one you already know: main, which is public static void because Java has to find it and call it without creating anything.
Seeing methods in action
Time to keep the promise from the loops topic. In the loops exercises, to know whether a number was prime there was an outer for with the candidates, an inner for with the divisors, an isPrime flag that had to be reset for every candidate, and a break. With a method, all that becomes a question with a name:
public class Primes {
// The block from Loops in Java, with a name of its own. return false in the middle of the loop
// leaves the whole METHOD: no flag or break needed any more.
public static boolean isPrime(int n) {
if (n < 2) {
return false; // neither 0 nor 1 is prime
}
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
return false; // it has a divisor: it isn't prime, end of story
}
}
return true; // the loop ended without finding divisors
}
// A method that uses another: it looks for the first prime that comes AFTER n
public static int nextPrime(int n) {
int candidate = n + 1;
while (!isPrime(candidate)) {
candidate++;
}
return candidate;
}
public static void main(String[] args) {
System.out.print("Primes up to 50:");
for (int i = 1; i <= 50; i++) {
if (isPrime(i)) { // it reads like a sentence: "if i is prime"
System.out.print(" " + i);
}
}
System.out.println();
System.out.println("Is 31 prime? " + isPrime(31));
System.out.println("The next prime after 31: " + nextPrime(31));
}
}
Primes up to 50: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 Is 31 prime? true The next prime after 31: 37
Look at how the way of thinking changes:
return falsein the middle of the loop leaves the whole method. No flag and nobreakneeded any more: as soon as a divisor shows up, the answer is clear and the method leaves with it.return trueafter the loop is only reached if theforended without finding divisors. It’s the “I look for something; if I find it, I leave; if I reach the end, it wasn’t there” pattern.d * d <= nis the same trick as in the loops exercises: trying divisors up to the square root is enough.nextPrimeusesisPrime: one method calls another. With 31, it tries 32 (divisible by 2), 33 (by 3), 34, 35 (by 5), 36 and reaches 37, which is prime.- The
mainreads almost like a sentence: “for each i from 1 to 50, if i is prime, write it”.
isPrime(31) and isPrime(35), round by round
To see how return cuts the loop short, follow the for in isPrime with two numbers. First 31:
d | d * d <= 31? | 31 % d | What the method does | Why |
|---|---|---|---|---|
| 2 | 4, yes | 1 | Carries on | 2 doesn’t divide 31. |
| 3 | 9, yes | 1 | Carries on | Nor does 3. |
| 4 | 16, yes | 3 | Carries on | Nor 4. |
| 5 | 25, yes | 1 | Carries on | Nor 5. |
| 6 | 36, no | Leaves the for and runs return true; | If 31 had a divisor greater than 5, its partner would be smaller than 6 and we would already have tried it. |
Now 35:
d | d * d <= 35? | 35 % d | What the method does | Why |
|---|---|---|---|---|
| 2 | 4, yes | 1 | Carries on | 2 doesn’t divide 35. |
| 3 | 9, yes | 2 | Carries on | Nor does 3. |
| 4 | 16, yes | 3 | Carries on | Nor 4. |
| 5 | 25, yes | 0 | return false; and the method ends right there | 5 divides 35: we already know the answer, and d = 6 is never tried. |
Look at the last row of each table. With 31, the answer comes out after the loop; with 35, from inside it. In neither case do you need a flag to remember what happened: the return takes the answer away the very moment it’s known.
The other promise, the guessing-game block that was repeated three times, becomes a playRound method in the methods exercises.
When is it worth creating a method? Three clues: the code repeats, you need a comment to explain what a piece does (the method name can be that comment), or main no longer fits on one screen. If a method doesn’t fit on your screen, it’s probably two.
Common mistakes with methods
- Removing
static(or not writing it) and calling frommain:non-static method … cannot be referenced from a static context. - A path without
return:missing return statement, even if “every case is covered”. - Not collecting the result:
doubleIt(n);compiles and changes nothing. - Using a
voidas a value:'void' type not allowed here. - Integer division inside a method:
(a + b) / 2withintgives 7 instead of 7.5. - Thinking that changing only the return type is overloading:
method … is already defined. - A method inside another: meaningless brace errors. Methods go one after the other, inside the class.
Watch it step by step in Python Tutor
Python Tutor runs the code line by line and draws the variables and the call stack. Choose Java in the drop-down, paste this program and step through with Next:
public class Demo {
public static double weigh(double grade, double weight) {
double part = grade * weight;
return part;
}
public static double finalGrade(double theory, double practice) {
double t = weigh(theory, 0.6);
double p = weigh(practice, 0.4);
return t + p;
}
public static void main(String[] args) {
double fp2 = finalGrade(7.5, 6.0);
System.out.println(fp2);
}
}
Output:
6.9
What to look at:
- When entering
finalGrade(7.5, 6.0)a new frame appears on top ofmain‘s, withtheory = 7.5andpractice = 6.0. They are copies of the arguments. - Inside, the call to
weigh(theory, 0.6)opens a third frame, with its owngradeand its ownweight. Three stacked frames: the call stack you saw in the drawing. - When
return part;is reached, theweighframe disappears and the 4.5 lands in the variabletoffinalGrade. Same with the second call, which leaves 2.4 inp. - When
finalGradereturnst + p, its frame disappears withtandpinside, and onlyfp2 = 6.9is left inmain.
Summary
| Concept | In Java | If you come from Python |
|---|---|---|
| Function | Method, always inside a class | Loose def |
| Return type | Compulsory (double, String… or void) and checked | Not declared |
| Parameters | Each with its type | No type |
| Default values | Don’t exist: simulated with overloading | def f(x, y=10) |
| Calling another class | Class.method(…) | module.function(…) |
| Passing arguments | By value: the method gets copies | References to objects |
static | Belongs to the class; needed to call it from main without an object | Nothing similar for loose functions |
Three ideas to take away:
- A method is a promise with a type: whatever the header says (what it receives and returns), the compiler demands on every path.
- Parameters are copies and each call has its frame: the only thing that leaves a method is its
return, so collect it. - While everything is in
main‘s class, everything isstatic. Overloading lets you reuse a name if the parameters change, never only the return type.
Now it’s time to use it: in the methods in Java practice Laura builds a calculator, the validator for her campus password and her grade report, each with small methods and a short main. And then comes arrays in Java, where that report can have as many subjects as you like and methods start receiving arrays.
Did this article help you? Here is how you can support SergioLearns →



