Q. What happens if I leave out the keyword static when defining a static method?
A. As usual, the best way to answer a question like this is to try it yourself and see what happens. Here is the result of omitting the static modifier from harmonic() in Harmonic:
Harmonic.java:15: error: non-static method harmonic(int)
cannot be referenced from a static context
double value = harmonic(arg);
Non-static methods are different from static methods. You will learn about the former in CHAPTER 3.
Q. What happens if I write code after a return statement?
A. Once a return statement is reached, control immediately returns to the caller, so any code after a return statement is useless. Java identifies this situation as a compile-time error, reporting unreachable code.
Q. What happens if I do not include a return statement?
A. There is no problem, if the return type is void. In this case, control will return to the caller after the last statement. When the return type is not void, Java will report a missing return statement compile-time error if there is any path through the code that does not end in a return statement.
Q. Why do I need to use the return type void? Why not just omit the return type?
A. Java requires it; we have to include it. Second-guessing a decision made by a programming-language designer is the first step on the road to becoming one.
Q. Can I return from a void function by using return? If so, which return value should I use?
A. Yes. Use the statement return; with no return value.
Q. This issue with side effects and arrays passed as arguments is confusing. Is it really all that important?
A. Yes. Properly controlling side effects is one of a programmer’s most important tasks in large systems. Taking the time to be sure that you understand the difference between passing a value (when arguments are of a primitive type) and passing a reference (when arguments are arrays) will certainly be worthwhile. The very same mechanism is used for all other types of data, as you will learn in CHAPTER 3.
Q. So why not just eliminate the possibility of side effects by making all arguments pass by value, including arrays?
A. Think of a huge array with, say, millions of elements. Does it make sense to copy all of those values for a static method that is going to exchange just two of them? For this reason, most programming languages support passing an array to a function without creating a copy of the array elements—Matlab is a notable exception.
Q. In which order does Java evaluate method calls?
A. Regardless of operator precedence or associativity, Java evaluates subexpressions (including method calls) and argument lists from left to right. For example, when evaluating the expression
f1() + f2() * f3(f4(), f5())
Java calls the methods in the order f1(), f2(), f4(), f5(), and f3(). This is most relevant for methods that produce side effects. As a matter of style, we avoid writing code that depends on the order of evaluation.