The return type might actual java type such string int
Designing Methods 169
Remember that a method must have a return type. If no value is returned, the return type is void. You cannot omit the return type.
When checking return types, you also have to look inside the method body. Methods with a return type other than void are required to have a return statement inside the method body. This return statement must include the primitive or object to be returned. Methods that have a return type of void are permitted to have a return statement with no value returned or omit the return statement entirely.
public String walk4() { } // DOES NOT COMPILE
public walk5() { } // DOES NOT COMPILE
When returning a value, it needs to be assignable to the return type. Imagine there is a local variable of that type to which it is assigned before being returned. Can you think of how to add a line of code with a local variable in these two methods?
int integer() {
return 9;
}
int long() {]
return 9L; // DOES NOT COMPILE
}Method Name
Method names follow the same rules as we practiced with variable names in Chapter 1, “Java Building Blocks.” To review, an identifi er may only contain letters, numbers, $, or _. Also, the fi rst character is not allowed to be a number, and reserved words are not allowed. By convention, methods begin with a lowercase letter but are not required to. Since this is a review of Chapter 1, we can jump right into practicing with some examples: