Declaring and calling a method
A method is a named block of code that does one job. Every Java method lives inside a class. Its signature has, in order: modifiers (public, static), the return type (void if it returns nothing), the name, and a parameter list in parentheses. return ends the method and hands a value back to the caller.
// modifiers return type name parameters
public static double average(int a, int b) {
return (a + b) / 2.0; // the value handed back
}The anatomy of a method declaration. The parameters a and b are local variables that start with the values the caller passes in.
public class Main {
static void greet(String name) { // void: returns nothing
System.out.println("Hello, " + name);
}
static double average(int a, int b) {
return (a + b) / 2.0;
}
static boolean isEven(int n) {
return n % 2 == 0; // return a boolean expression directly
}
public static void main(String[] args) {
greet("Asha");
double avg = average(4, 7); // store the result...
System.out.println(avg);
System.out.println(isEven(10) + " " + isEven(7)); // ...or use it inline
System.out.println(average(1, 2) * 10);
}
}Hello, Asha
5.5
true false
15.0Write static int max3(int a, int b, int c) that returns the largest of three numbers and call it from main.
calculateTotal, sendEmail, isValid, hasPermission. Methods returning boolean read best as questions (is…, has…, can…). A method that needs "and" in its name is doing two jobs — split it.missing return statement
public class Main {
static int max(int a, int b) {
if (a > b) {
return a;
} else if (b > a) {
return b;
}
}
public static void main(String[] args) {
System.out.println(max(3, 7));
}
}Main.java:8: error: missing return statement
}
^
1 error
error: compilation failedA non-void method must return a value on every path. You know a == b is the only case left, but the compiler does not reason about values: it sees an if / else if with no final else, so there is a path that falls off the end.
Make the last branch an unconditional else, or end the method with a return.
static int max(int a, int b) {
if (a > b) {
return a;
}
return b; // covers b > a and a == b
}