Java Method Declarations: Access Modifiers, Specifiers, Return Types and Parameters (OCP 21)
Every part of a Java method declaration as tested on the OCP Java 21 exam: access modifiers, optional specifiers and their order, return types and return statements, legal method names, parameter lists, the method signature, the throws clause and the body.
kvi5hnuCode Sprout team member10 min readOn this page
So far, almost all our code has lived inside main. Chapter 5 is about writing your own methods: how to declare them, what variables they can use, who can call them, how data is passed in and out, and how Java picks between methods with the same name. This article starts with syntax. Many exam questions show a list of method declarations and ask which ones compile. To answer them quickly, you need to know each part of a declaration and the order the parts must appear in.
The parts of a declaration
public static String grade(int climb) throws IOException {
// body
}

| Part | In the example | Required? |
|---|---|---|
| Access modifier | public | No |
| Optional specifiers | static | No (zero or more) |
| Return type | String | Yes (void if nothing is returned) |
| Method name | grade | Yes |
| Parameter list | (int climb) | Yes, but it can be empty: () |
| Exception list | throws IOException | No |
| Body | { … } | Yes, except for abstract and native methods, which end with ; |
The method signature is the method name plus the parameter types, in order. Here, it's grade(int). The return type, the parameter names, the modifiers and the throws clause are not part of the signature. To call the method, you use the name and pass matching arguments: grade(450).
Access modifiers
There are four levels of access. Only three of them have a keyword:
| Modifier | Who can call the method |
|---|---|
private | code in the same class only |
| (none): package access | classes in the same package |
protected | the same package, plus subclasses in other packages |
public | any class |
Package access is also called package-private or default access, but there's no keyword for it. You just leave the modifier out. Article 27 covers what each level allows in detail. For now, focus on syntax:
public class Trail {
public void open() {}
void inspect() {} // package access
default void close() {} // DOES NOT COMPILE
void public reopen() {} // DOES NOT COMPILE
public private void lock() {} // DOES NOT COMPILE
}
defaultis a real keyword, but only forswitchlabels and interface default methods. It's never an access modifier.- Modifiers must come before the return type.
- A method has at most one access level, so
public privateis an "illegal combination of modifiers".
Optional specifiers
| Specifier | Meaning | Covered in |
|---|---|---|
static | belongs to the class, not to an object | Article 28 |
abstract | no body; a subclass must provide one | Chapter 6 |
final | can't be overridden in a subclass | Chapter 6 |
default | interface method with a body | Chapter 7 |
synchronized | only one thread at a time may run it on the same lock | Chapter 13 |
native | implemented in platform code (for example, C) | not on the exam |
strictfp | strict floating-point arithmetic | obsolete (see below) |
You can use zero or more specifiers, in any order among themselves and with the access modifier, as long as they all come before the return type. Some combinations are illegal: abstract can't be combined with final, static or private, and the same modifier can't be repeated.
public class Exercise {
public final void stretch() {}
public static final void warmUp() {}
public final static void coolDown() {} // order of specifiers doesn't matter
final public void rest() {} // compiles: specifier before access modifier
public void final sprint() {} // DOES NOT COMPILE: after the return type
public quick void draw() {} // DOES NOT COMPILE: not a modifier
final final void walk() {} // DOES NOT COMPILE: repeated modifier
transient void swim() {} // DOES NOT COMPILE: transient is for fields
}
By convention, the access modifier comes first, but final public void rest() is legal. Field-only modifiers such as transient and volatile aren't allowed on methods.
Return type
The return type comes right after the modifiers and right before the name. It's always required. A method that returns nothing uses void. Constructors are the only members without a return type, and they're covered in Chapter 6.
The body has to match the return type:
- A non-
voidmethod must end every possible path withreturn value;, or with athrowstatement. - A
voidmethod may use a barereturn;to leave early, or noreturnat all. It can't return a value.
public class Hike {
void a() {}
void b() { return; }
String c() { return ""; }
String d() {} // DOES NOT COMPILE: missing return statement
e() {} // DOES NOT COMPILE: no return type
String int f() { return ""; } // DOES NOT COMPILE: two return types
void g() { return null; } // DOES NOT COMPILE: void can't return a value
int h() { return; } // DOES NOT COMPILE: missing return value
String i(int x) { // DOES NOT COMPILE
if (1 < 2) return "short";
}
String j(boolean b) { // compiles: both branches return
if (b) return "yes"; else return "no";
}
String k() { while (true) { } } // compiles: the end is unreachable
}
Method i is the classic trap. The compiler doesn't evaluate the if condition, even though 1 < 2 is constant, so it assumes the condition might be false and the method might reach the end without returning. Adding return "long"; after the if fixes it, and javac doesn't complain even though that line can never run (IDEs often flag it as dead code). An if is the one statement where the compiler deliberately ignores a constant condition. A while (true) loop with no break is different: the compiler knows the end of the method can't be reached, so no return is needed.
The returned value must be assignable
The value after return follows the same rules as an assignment to a variable of the return type:
long a() { int n = 9; return n; } // int widens to long
double b() { return 1; } // int widens to double
Integer c() { return 1; } // int boxes to Integer
Object d() { return 1; } // boxes to Integer, which is an Object
int e() { long n = 9; return n; } // DOES NOT COMPILE: possible lossy conversion
Long f() { return 1; } // DOES NOT COMPILE: int can't box to Long
Method f is a good one to remember: Java can box an int only to an Integer. It won't widen it to long and box it to Long in one step. Also, var can't be used as a return type or as a parameter type.
Method name
Method names follow the identifier rules from Chapter 1:
- They can contain letters, digits,
$and_. - They can't start with a digit.
- They can't be a reserved word.
- A single underscore
_is not allowed (it has been a keyword since Java 9).
void draw() {}
void Draw_$() {} // legal, though unconventional
void $() {} // legal
void 2draw() {} // DOES NOT COMPILE: starts with a digit
void _() {} // DOES NOT COMPILE
public draw void() {} // DOES NOT COMPILE: name before return type
public void() {} // DOES NOT COMPILE: no name
By convention, method names are verbs in camelCase, but the compiler doesn't enforce that.
Parameter list
The parentheses are always required, even when the method has no parameters. Parameters are separated by commas, and each one needs its own type:
void send1() {}
void send2 {} // DOES NOT COMPILE: no parentheses
void send3(int a, int b) {}
void send4(int a; int b) {} // DOES NOT COMPILE: semicolon
void send5(int a, b) {} // DOES NOT COMPILE: b has no type
void send6(int a, int a) {} // DOES NOT COMPILE: duplicate name
void send7(final int a) {} // final is the only modifier allowed on a parameter
Parameters may be final, and a varargs parameter (int... values) can be the last one. Varargs are covered in the next article.
What counts as the same signature
The parameter names aren't part of the signature, and neither is the return type. A class can't contain two methods with the same name and the same parameter types in the same order:
public class Trip {
void visit(String place, int hours) {}
void visit(String town, int minutes) {} // DOES NOT COMPILE: same signature
int visit(String s, int i) { return 0; } // DOES NOT COMPILE: return type doesn't count
void visit(int hours, String place) {} // compiles: different order of types
}
Methods with the same name and different parameter types are overloads. The rules for choosing between them come in article 30.
Exception list
After the parameter list, a method may declare the exceptions it can throw, with throws and a comma-separated list:
void none() {}
void one() throws IllegalArgumentException {}
void two() throws IllegalArgumentException, InterruptedException {}
The list is optional in the syntax. Whether the compiler requires it depends on whether the body can throw checked exceptions, which is covered in Chapter 11. For now, remember where it goes: after the ) and before the {. The keyword is throws in a declaration and throw in a statement.
Method body
The body is a block in braces containing zero or more statements:
void paint1() {}
void paint2() // DOES NOT COMPILE: missing body
void paint3(int a) { int b = a; }
Only abstract and native methods end with a semicolon instead of a body. Declaring a method abstract in a regular class makes the class itself fail to compile, unless the class is also abstract (Chapter 6).
What's current
strictfphas done nothing since Java 17 (JEP 306).- Java 25 allows instance
mainmethods (JEP 512), and Java 22 allows unnamed_locals and lambda parameters (JEP 456). Neither is on 1Z0-830.
Exam traps from this article
A complete example
The program declares methods with different combinations of modifiers, return types, parameters and throws clauses, calls each one, and then uses reflection to print how the compiler recorded the declarations. Reflection always prints the modifiers in the standard order, even for the oddly ordered final static public grade.
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
public class Solution {
// Access modifier, then optional specifiers in any order, then the return type.
public static final double kmToMiles(double km) {
return km * 0.621371;
}
// Specifiers may even come first; javac accepts it, but nobody writes it this way.
final static public String grade(int climbMeters) {
if (climbMeters < 200) {
return "easy";
} else if (climbMeters < 800) {
return "moderate";
}
return "hard"; // every path ends in a return
}
// void: return is optional, but a bare return can leave early.
static void log(String message) {
if (message == null || message.isBlank()) {
return;
}
System.out.println("[log] " + message);
}
// The return value only has to be assignable to the declared type.
static long widened() {
int steps = 12_000;
return steps; // int widens to long
}
static Object boxed() {
return 42; // int boxes to Integer, which is an Object
}
// Same name, different parameter types: a different signature.
static String describe(String trail, int km) {
return trail + " (" + km + " km)";
}
static String describe(int km, String trail) {
return km + " km of " + trail;
}
// The exception list goes after the parameters and before the body.
static void pause(long millis) throws InterruptedException, IllegalArgumentException {
if (millis < 0) {
throw new IllegalArgumentException("negative pause: " + millis);
}
Thread.sleep(millis);
}
public static void main(String[] args) throws InterruptedException {
System.out.printf("12 km = %.2f miles%n", kmToMiles(12));
for (int climb : new int[] {150, 650, 1200}) {
System.out.println(climb + " m climb -> " + grade(climb));
}
log(""); // returns early, prints nothing
log("trail plan ready");
System.out.println(widened() + " " + boxed() + " " + boxed().getClass().getSimpleName());
System.out.println(describe("Ridge Loop", 9) + " | " + describe(9, "Ridge Loop"));
pause(1);
try {
pause(-5);
} catch (IllegalArgumentException e) {
System.out.println("caught: " + e.getMessage());
}
System.out.println("\n== Declarations as the compiler recorded them");
Method[] methods = Solution.class.getDeclaredMethods();
Arrays.sort(methods, Comparator.comparing(Method::toGenericString));
for (Method m : methods) {
if (!m.isSynthetic()) {
System.out.println(m.toGenericString().replace("Solution.", ""));
}
}
}
}
Output:
12 km = 7.46 miles
150 m climb -> easy
650 m climb -> moderate
1200 m climb -> hard
[log] trail plan ready
12000 42 Integer
Ridge Loop (9 km) | 9 km of Ridge Loop
caught: negative pause: -5
== Declarations as the compiler recorded them
public static final double kmToMiles(double)
public static final java.lang.String grade(int)
public static void main(java.lang.String[]) throws java.lang.InterruptedException
static java.lang.Object boxed()
static java.lang.String describe(int,java.lang.String)
static java.lang.String describe(java.lang.String,int)
static long widened()
static void log(java.lang.String)
static void pause(long) throws java.lang.InterruptedException,java.lang.IllegalArgumentException
Points to notice:
gradereturns on every path: two inside theif/else if, and one at the end.logleaves early with a barereturn;when there's nothing to print.widenedreturns anintfrom a method declaredlong, andboxedreturns anintfrom a method declaredObject. Both are legal assignment conversions.- The two
describemethods have the same name and parameter types in a different order, so their signatures differ. - The reflection output omits parameter names. Only the types are part of the signature.
Common questions
Is the return type part of the signature? Not in Java source code. Two methods that differ only in return type clash. (At the bytecode level, the JVM includes the return type in its method descriptor, but that never matters when compiling Java source.)
Can a method be both public and static final synchronized?
Yes. One access modifier plus any compatible specifiers is fine: public static final synchronized void m() compiles.
Is throws required if the method throws an unchecked exception?
No. RuntimeException and its subclasses may be listed, but they don't have to be. Checked exceptions are different, as Chapter 11 explains.
Why does Java allow final public void m()?
The language grammar allows modifiers in any order. Style guides, including the order used by the JDK's own Modifier.toString, put the access modifier first.
Summary
- A method declaration consists of an optional access modifier and specifiers (in any order), a required return type, a name, a parameter list in parentheses, an optional
throwslist, and a body. - The signature is the name plus the parameter types in order. Parameter names, the return type and modifiers don't count.
- There are four access levels:
private, package (no keyword),protectedandpublic.defaultisn't one of them. - Non-
voidmethods must return a compatible value on every path.voidmethods may only use a barereturn;. - Method names follow the identifier rules, so
_and a leading digit aren't allowed.
Practice quiz
Test yourself with the method declarations quiz: 10 exam-style questions with explanations.
Previous: Java Period, Duration, Instant and Daylight Saving Time (OCP 21)
Next: Java Local and Instance Variables, Effectively Final and Varargs (OCP 21)
Related reading
- Java Period, Duration, Instant and Daylight Saving Time (OCP 21)
- Java Date and Time: LocalDate, LocalTime, LocalDateTime and ZonedDateTime (OCP 21)
- Java Math API, BigInteger and BigDecimal (OCP 21)
- Java Arrays: equals, compare, mismatch, Varargs and Multidimensional Arrays (OCP 21)
- Java Arrays: Creating, Sorting and Searching (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.