Methods
A method is a named piece of a class that takes parameters and gives a result. It is the unit of work in Java: the type of every parameter and every result is written down, the compiler checks every call against it, and a method may be called before it is declared because the compiler reads the whole class first.
A method declaration
The declaration has a modifier, a return type, a name, a parameter list and a body. Inside the class the order of the methods does not matter, and the program below calls three of its own methods from main.
The file Methods.java:
public class Methods {
public static void main(String[] args) {
greet("Ada");
int result = square(7);
System.out.println("square: " + result);
System.out.println("max: " + max(3, 9));
}
static void greet(String name) {
System.out.println("Hello, " + name);
}
static int square(int n) {
return n * n;
}
static int max(int a, int b) {
return a > b ? a : b;
}
}
javac -Xlint:all Methods.java
java Methods
Hello, Ada
square: 49
max: 9
The name and the parameter types together are the signature: square(int) is a different method from square(double). The parameter names are for the reader and for the body; a caller never writes them, which is why max(3, 9) says nothing about a and b.
return and void
A method with a return type must return a value of that type on every path that leaves it, and the compiler checks the paths. A void method returns nothing, and a bare return; leaves it early. Returning a value from a void method is an error, and it is reported at the value.
public class VoidReturn {
public static void main(String[] args) {
say();
}
static void say() {
return 1;
}
}
javac -Xlint:all VoidReturn.java
VoidReturn.java:7: error: incompatible types: unexpected return value
return 1;
^
1 error
A non-void method with a branch that returns nothing is an error too, with missing return statement at the closing brace. The fix is either a return on that path or a throw, which also leaves the method.
Overloading
Two methods with the same name but different parameter lists are overloads. The compiler chooses one at the call from the number and types of the arguments, before the program runs, and the return type is not part of the choice.
public class Overload {
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2.5, 3.5));
System.out.println(add("a", "b"));
System.out.println(add(1, 2, 3));
}
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
static String add(String a, String b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
}
javac -Xlint:all Overload.java
java Overload
5
6.0
ab
6
The second call picks the double version because two fractional literals are double values, and the result prints with a decimal point. Two methods that differ only in their return type are not overloads but a duplicate, and the compiler refuses the second declaration.
Instance methods and this
A method without static belongs to an object and runs with that object as this. It may read and write the fields of the object, call its other instance methods, and the same code behaves differently for two objects with different field values.
public class Counter {
private int value;
Counter(int start) {
this.value = start;
}
void increment() {
value++;
}
int value() {
return value;
}
static Counter zero() {
return new Counter(0);
}
public static void main(String[] args) {
Counter counter = Counter.zero();
counter.increment();
counter.increment();
System.out.println("value: " + counter.value());
Counter other = new Counter(10);
other.increment();
System.out.println("other: " + other.value());
}
}
javac -Xlint:all Counter.java
java Counter
value: 2
other: 11
this.value = start says the field, not the parameter, because the parameter has the same name. Two counters, two value fields: the method increment reads the one that belongs to the object it was called on. That object is what this names inside the method.
static methods
A static method belongs to the class, not to an object, and it has no this. It cannot read an instance field, because there is no object to read it from, and the compiler says so at the field:
public class StaticErr {
int value = 1;
static int get() {
return value;
}
public static void main(String[] args) {
System.out.println(get());
}
}
javac -Xlint:all StaticErr.java
StaticErr.java:5: error: non-static variable value cannot be referenced from a static context
return value;
^
1 error
main is static for the same reason: the JVM calls it before any object of the class exists. A static method that needs the state of an object takes that object as a parameter, or is an instance method instead.
Exercises
- Add a method static boolean isEven(int n) to Methods.java and use it in main.
- Add an overload add(long, long) to Overload.java. Which version does add(1, 2) call now?
- Make increment in Counter.java return this. What can a caller do with that?
- Move value in StaticErr.java into the get method as a local variable. Does the class compile?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the signature of a method?
Answer
Its name and its parameter types
A method is identified by name and parameter types; the return type does not take part in overloading.
-
What must a non-void method do on every path that leaves it?
Answer
Return a value of its return type or throw
The compiler checks that every path returns or throws, and reports missing return statement otherwise.
-
Which method can read an instance field?
Answer
An instance method
An instance field belongs to an object, so a method needs an object, which is what an instance method has.
-
What does this program print?
public class Q1 { public static void main(String[] args) { System.out.println(square(6)); } static int square(int n) { return n * n; } }Answer
36
square returns 6 times 6, and println writes the value.
-
What does this program print?
public class Q2 { public static void main(String[] args) { System.out.println(add(1, 2, 3)); } static int add(int a, int b) { return a + b; } static int add(int a, int b, int c) { return a + b + c; } }Answer
6
The call has three arguments, so the three-parameter overload is chosen.
-
What is the first line of the compiler output for this program?
public class Q3 { int value = 1; static int get() { return value; } public static void main(String[] args) { System.out.println(get()); } }Answer
error: non-static variable value cannot be referenced from a static context
A static method has no object, so the instance field value is not available to it.
-
What does this program print?
public class Q4 { private int value; Q4(int value) { this.value = value; } int doubled() { return value * 2; } public static void main(String[] args) { Q4 one = new Q4(4); System.out.println(one.doubled()); } }Answer
8
The constructor stores 4 in the field and doubled returns twice that.
-
What does this program print?
public class Q5 { public static void main(String[] args) { System.out.println(greet("Ada")); } static String greet(String name) { return "Hello, " + name; } }Answer
Hello, Ada
greet returns a string and println writes it.
-
What is the first line of the compiler output for this program?
public class Q6 { public static void main(String[] args) { say(); } static void say() { return 1; } }Answer
error: incompatible types: unexpected return value
A void method cannot return a value, and the compiler reports the value itself.
-
What is a call such as
max(3, 9)passing to the method?Answer
Arguments, which the parameters receive in order
The caller supplies arguments; the declaration names parameters, and the values are matched by position.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev