Step 1 of 5 · Reading · ~4 min
Learn
Methods and Classes
Methods
A method gives a computation a name so you can run it many times, test it on its own, and read code as intent ("is this valid?") instead of mechanics. By the end of this lesson you can write methods that take parameters and return values, split a task into small helpers, and explain how Java passes arguments.
Anatomy of a signature
public class Main {
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
System.out.println(isEven(10)); // true
System.out.println(isEven(7)); // false
}
}
static boolean isEven(int n) reads as a contract:
boolean(before the name) is the return type: what comes back. The compiler holds you to it.isEvenis the name, camelCase. Methods that answer yes/no are conventionally namedisXorhasX.(int n)is the parameter list: each input with its type and a local name.staticmeans the method belongs to the class itself rather than to an object. For now every helper thatmaincalls must bestatic.
return does two things at once: it ends the method immediately and hands the value back. A method that returns void returns nothing and is called as a statement.
Every path must return
If a method has a non-void return type, the compiler checks that every route through it ends in a return:
static String sign(int n) {
if (n < 0) {
return "negative";
} else if (n > 0) {
return "positive";
}
// error: missing return statement -- what about n == 0?
}
Add a final return "zero";. Because return exits at once, you can also use early returns to dispose of the special cases first, and let the rest of the method assume they are out of the way:
static int firstDigit(int n) {
if (n < 0) {
n = -n; // fix up the odd case
}
while (n >= 10) {
n /= 10;
}
return n;
}
Parameters are copies
Java passes arguments by value: the parameter is a fresh copy of what the caller supplied. Reassigning it inside the method never touches the caller's variable:
static void bump(int x) {
x = x + 1;
}
int a = 5;
bump(a);
System.out.println(a); // still 5
To get a result out, return it. (When the argument is an object, the copy is a copy of the reference, so changing the object's contents is visible to the caller. That arrives with classes.)
Locals stay local
A variable declared inside a method exists only there. Two methods can both have a variable called i without clashing, and a loop variable declared in a for is gone after the loop.
Overloading
Several methods may share a name if their parameter lists differ:
static int bigger(int a, int b) { return a > b ? a : b; }
static double bigger(double a, double b) { return a > b ? a : b; }
The compiler picks the version from the argument types at compile time: bigger(3, 9) runs the int one, bigger(3.0, 9.5) the double one.
Small methods, big payoff
A method that does one job is easy to test with a handful of values, including the awkward ones (zero, one, negatives, the exact boundary). Prefer a helper isEven(n) called from a loop over a loop with the test inlined: the loop then reads like the problem statement.
Common mistakes
- Calling an instance method from
static mainwithoutstaticon the helper:non-static method cannot be referenced from a static context. - A path with no
return, which is a compile error, or a stubreturn false;left in by accident, which compiles and quietly fails. - Printing inside a method that was supposed to return a value, or the reverse.
- Expecting a parameter reassignment to be visible to the caller.
Your exercise
Write a yes/no method that decides a property of a whole number, and let the provided main call it once per input. The method has to be right for the unusual values (the smallest cases and negatives) as well as the ordinary ones, so think about which inputs need an early return.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…