5.2 Method Declarations and Calls
Prerequisites: Understand that methods are used to encapsulate behavior Estimated time: 25 minutes You are ready to continue when: You can declare and call static methods in a Java 17 class and manage scope
A complete, runnable class
public class MethodsDemo {
static void showBanner() {
System.out.println("=== Methods Demo ===");
}
static int add(int left, int right) {
return left + right;
}
public static void main(String[] args) {
showBanner();
int result = add(3, 5);
System.out.println(result);
}
}mkdir -p out
javac -d out MethodsDemo.java
java -cp out MethodsDemoExpected output:
=== Methods Demo ===
8Methods can be written before or after main; the Java compiler processes the entire type declaration and does not require that definitions appear before their usage in text order.
static and Instance Methods
static int add(int left, int right) {
return left + right;
}Static methods belong to a class and can be written MethodsDemo.add(3, 5). Within the same class's static context, the class name is typically omitted.
Instance methods require a receiver object:
class Counter {
private int value;
int increment() {
value++;
return value;
}
}
Counter counter = new Counter();
System.out.println(counter.increment());Start by practicing static method calls first. Instances, fields, and this will be explored in the object-oriented chapter. Do not interpret static as meaning "the method is created when the program starts"; it describes the relationship between members and the class.
Method Name and Parameter List Form the Invocation Entry Point
static int add(int left, int right) { ... }In the Java Language Specification, a method signature is fundamentally defined by the method name and the formal parameter types (with additional formal definitions involving type parameter adaptation, etc.). It does not include the return type or parameter variable names. Therefore, the following two methods cannot coexist merely by changing the return type or parameter names:
// static int convert(int value) { ... }
// static long convert(int number) { ... } // Duplicate signatureParameter names serve the method body and the reader; invocation matching depends on type and order.
Parameter and Local Variable Scope
static int addFee(int price, int fee) {
int total = price + fee;
return total;
}Scope is a region of source code: price and fee are visible in the method body, and total from its declaration to the end of its block. Each call has separate parameters and locals; ending a call does not change lexical scope. Objects referenced elsewhere may remain alive, so distinguish scope, the duration of a call, and object lifetime.
A code block cannot declare the same local variable name more than once:
int total = 1;
// int total = 2;Arguments Are Evaluated Left to Right
static int mark(String name, int value) {
System.out.println(name);
return value;
}
int sum = add(mark("left", 3), mark("right", 5));First print left, then print right. Even if the rules are clear, avoid using parameters with complex side effects to create reading puzzles.
Return Paths and Unreachable Statements
Any method that returns a value must ensure that every normal execution path provides a return value:
static String sign(int value) {
if (value > 0) {
return "positive";
}
if (value < 0) {
return "negative";
}
return "zero";
}Statements following an unconditional return are unreachable and will cause a compilation error:
static int answer() {
return 42;
// System.out.println("never");
}Paths that throw an exception abruptly terminate and do not need to return a normal value.
Method Naming and Granularity
Use verbs or verb phrases to express behavior: calculateTotal, isEligible, loadConfig. Boolean methods often use is, has, can, but domain meaning should take precedence.
There is no universal line count limit for method length. A more reliable indicator is whether the method has several independent reasons to change, requires extensive context to be named, is difficult to test independently, or has deeply nested control flow.
Professional Quick Reference
| Condition to Evaluate | Rule |
|---|---|
| Static method invocation | Type.method(...) |
| Instance method invocation | receiver.method(...) |
| Can a method be defined later? | Yes, the compiler processes the entire type |
| Does the signature include a return type? | No |
| Does parameter name affect overloading? | No |
| Scope of local variables | The containing block; not equivalent to object lifetime |
Before Proceeding
Use MethodsDemo and Counter to identify the class for a static call and the receiver for an instance call. Explain why return type and parameter names cannot distinguish overloaded methods. Then verify that every normal path returns a compatible value, and separate local-variable scope from object lifetime.
→ Next: Parameters, Return Values, and Value Passing
Specification reference: JLS §8.4: Method Declarations.