8.1 Designing Methods, Return Types & Pass-by-Value Semantics
Key Takeaways
Optional method specifiers such as
static,final,abstract,synchronized, andstrictfpmay appear in any order before the return type—even before the access modifier—while the return type, method name, and parameter parentheses are mandatory.A non-void method with a block body cannot reach its closing brace normally. It may return an assignment-compatible value, throw, or have control flow that never completes.
A varargs parameter must be last. A variable-arity call supplies an array of the trailing arguments, which can be empty. A fixed-arity call can pass an array or a null array reference directly.
Java passes each argument value into its own parameter variable. An object argument supplies a reference value, which leaves caller and callee able to refer to the same object.
Through a copied reference alias, a method can mutate a
StringBuilderor array in place, but reassigning the parameter variable itself never changes the caller's reference.
Designing Methods, Return Types & Pass-by-Value Semantics
Methods encapsulate reusable behavior inside classes and interfaces. On the Java SE 8 Programmer I (1Z0-808) exam, method questions rarely test trivial syntax alone—instead, they target subtle modifier ordering, unreachable or missing return paths, varargs edge cases, and the distinction between mutating a shared heap object and reassigning a local parameter variable under pass-by-value.
Anatomy of a Java Method Declaration
Use this outline for an ordinary non-generic class method. Modifiers go first. The declaration then supplies the result type, name, parameters, optional throws clause, and body or semicolon:
[modifiers] returnType methodName([parameterList]) [throws ExceptionList] { body }
| Component | Required? | Rules & Exam Traps |
|---|---|---|
| Access modifier | Optional (package-private if omitted) | public, protected, none (package-private), or private |
| Optional specifiers | Optional | static, final, abstract, synchronized, strictfp, native in any order before return type |
| Return type | Required | Any primitive, reference type, or void; omitting it is legal only on constructors |
| Method name | Required | A valid Java identifier, subject to the Java SE 8 identifier rules |
| Parameter list | Required parentheses | Empty () or comma-separated Type name pairs; Java has no default parameter values |
throws clause | Optional | Comma-separated exception types after ) and before { or ; |
| Method body | Required (unless abstract/native) | { ... }; abstract and native methods end with ; instead of braces |
A classic exam surprise is that optional specifiers can appear before the access modifier! Both declarations below compile cleanly:
public static final void logStatus(int code) {
System.out.println("Status: " + code);
}
static final public void logAlt(int code) { // Legal: specifier before access modifier
System.out.println("Alt: " + code);
}
However, placing any specifier after the return type (such as public void static bad() {}) or combining contradictory modifiers (abstract + final, abstract + static, or abstract + private) fails compilation immediately.
Warning
Never confuse a void method with a constructor. Writing public void Account() {} inside class Account declares an ordinary method named Account with return type void—not a constructor.
void vs. Non-void Return Paths & Type Compatibility
In a void method, control can reach the closing brace normally or exit early with a bare return; statement. Attempting to return a value (return 0; or return null;) inside a void method triggers a compile-time error.
A non-void method with a block body must be unable to complete normally under Java’s reachability rules. A value return or an uncaught throw exits abruptly, and a demonstrably non-completing loop also satisfies the rule. Here the compiler still sees a path to the end:
public String classifyScore(int score) {
if (score >= 65) {
return "PASS";
} else if (score < 65) {
return "RETRY";
}
// COMPILE ERROR: missing return statement!
}
Even though score >= 65 and score < 65 cover all mathematical integers, the compiler does not evaluate runtime variable conditions in if/else if chains; without a final else or trailing return, compilation fails. Conversely, placing code directly after an unconditional return or throw triggers an unreachable statement compile error.
The expression returned must be assignment-compatible with the declared return type:
public double getRate() {
int basisPoints = 25;
return basisPoints; // Legal: int implicitly widens to double (25.0)
}
public byte getSmallConstant() {
return 100; // Legal: compile-time constant 100 fits in byte (-128..127)
}
public byte getVariableByte(int n) {
// return n; // COMPILE ERROR: possible lossy conversion from int to byte
return (byte) n; // Legal with explicit cast
}
public CharSequence getLabel() {
return "Java 8"; // Legal: String implements CharSequence
}
Returning null is valid for any reference return type (including boxed wrappers like Integer), though unboxing a null wrapper or returning null where a primitive is expected fails (NullPointerException on unbox, compile error on literal null for int).
Varargs (Type... name) Rules & Edge Cases
Variable-arity parameters (varargs) allow a method to accept zero or more values of a given type without forcing the caller to allocate an array manually:
public static int sumAll(int... values) {
int total = 0;
for (int v : values) { // values is treated as int[] inside the method
total += v;
}
return total;
}
Two structural rules govern every varargs declaration:
- At most one varargs parameter may appear in a method's parameter list.
- The varargs parameter must be last in the parameter list.
Declarations such as void bad(int... a, int b) or void worse(int... a, String... b) fail to compile. Also, notice the ellipsis belongs on the type (int... nums or int ...nums), never after the identifier (int nums... fails compilation).
Calls to sumAll(...) can pass a synthesized array, an existing array, or a null reference:
| Call Expression | Value Received by values | values.length / Outcome |
|---|---|---|
sumAll() | Empty array new int[0] | 0 (returns 0) |
sumAll(10, 20) | new int[]{10, 20} | 2 (returns 30) |
sumAll(new int[]{5}) | Existing array {5} | 1 (returns 5) |
sumAll(null) | null reference itself! | Attempting enhanced-for iteration over the null array throws NullPointerException |
Caution
If the selected declaration is log(String... words), log(null) passes a null array reference in a fixed-arity invocation—not a one-element array containing null. If you cast it (log((String) null)), Java builds a 1-element String[] holding null.
Strict Pass-by-Value Semantics in Java
Java is 100% pass-by-value. After the applicable method invocation conversions, the argument values initialize the method’s own parameter variables:
- Primitives: The parameter receives a copy of the numeric or boolean value. Reassigning the parameter changes only the local copy.
- References to immutable objects: The parameter receives the same reference value. A call such as
s.concat("!")leaves that string unchanged. Assigning the result to the parameter changes only that local variable. - Mutable references (
StringBuilder, arrays, custom objects): The parameter receives a copy of the reference pointing to the same heap object. Mutating the object through that alias (sb.append(...),arr[0] = ...) is visible to the caller, while reassigning the parameter (sb = new StringBuilder(...)) breaks the alias locally and leaves the caller untouched.
Trace this complete example line by line:
public class PassByValueTrace {
public static void modify(int num, String text, StringBuilder buf, int[] arr) {
num = 99; // Changes local primitive copy only
text = text + "-updated"; // Local String ref points to new object
buf.append("-appended"); // Mutates shared StringBuilder on heap
buf = new StringBuilder("reassigned"); // Rebinds local ref only; caller unaffected
arr[0] = 777; // Mutates element 0 of shared array
arr = new int[]{1, 2}; // Rebinds local ref only; caller unaffected
}
public static void main(String[] args) {
int n = 10;
String s = "orig";
StringBuilder sb = new StringBuilder("base");
int[] data = {5, 6};
modify(n, s, sb, data);
System.out.println(n); // 10
System.out.println(s); // orig
System.out.println(sb); // base-appended
System.out.println(data[0]); // 777
}
}
Notice the exact distinction: buf.append("-appended") ran before buf = new StringBuilder("reassigned"), so the caller's sb still points to the mutated "base-appended" object. Similarly, data[0] became 777 via the shared array reference, while arr = new int[]{1, 2} changed only the local parameter arr. The caller still refers to the original array.
Which class method declaration compiles when placed in a suitable enclosing class under Java SE 8?
public void final process(int... items, String tag) {}
final static public synchronized int compute(String tag, int... items) { return items.length; }
public abstract static void execute();
public byte adjust(int x) { return x; }
What is the output of compiling and running the following code?
public class VarargsTrap {
static int count(String... words) {
return words.length;
}
public static void main(String[] args) {
System.out.print(count() + ":");
System.out.print(count((String) null) + ":");
System.out.print(count(null));
}
}
0:0:0
0:1:1
Compilation fails on count(null)
Prints 0:1: and then throws NullPointerException
What does the following program print?
public class AliasTest {
static void twist(String a, StringBuilder b, int[] c) {
a.concat("!");
b = new StringBuilder("Fresh");
b.append("!");
c[1] = c[0] + 10;
}
public static void main(String[] args) {
String s = "Hi";
StringBuilder sb = new StringBuilder("Old");
int[] nums = {5, 1};
twist(s, sb, nums);
System.out.println(s + "|" + sb + "|" + nums[1]);
}
}
Hi|Old|15
Hi!|Fresh!|15
Hi|Fresh!|15
Hi|Old|1
Sections you finish are checked off in the contents.