Web server iis - Chapter 6 Methods 285 Figure 6.14 shows how
Chapter 6 Methods 285 Figure 6.14 shows how method fibonaccievaluates fibonacci(3). In the figure, f is an abbreviation for fibonacci. Figure 6.14 raises some interesting issues about the order in which Java compilers evaluate the operands of operators. This issue is different than the order in which operators are applied to their operands, namely the order dictated by the rules of operator precedence. From Fig. 6.14, it appears that while f(3)is being evaluated, two recursive calls will be made, namely f(2)and f(1). But in what order will these calls be made? Most programmers assume that the operands will be evaluated left to right. In Java, this assumption is true. The C and C++ languages (on which many of Java s features are based) do not specify the order in which the operands of most operators (including +) are evaluated. Therefore, the programmer can make no assumption in those languages about the order in which the calls in this example execute. The calls could, in fact, execute f(2)first andf(1)second, or the calls could be executed in the reverse order: f(1), then f(2). In this program and in most other programs, it turns out that the final result would be the same for either case. But in some programs, the evaluation of an operand may have side effects that could affect the final result of the expression. The Java language specifies that the order of evaluation of the operands is from left to right. Thus, the method calls are in fact f(2)first andf(1)second. Good Programming Practice 6.8 Do not write expressions that depend on the order of evaluation of the operands of an operator. Use of such expressions often results in programs that are difficult to read, debug, modify and maintain. A word of caution is in order about recursive programs like the one we use here to generate Fibonacci numbers. Each invocation of the fibonaccimethod that does not match one of the base cases (i.e., 0 or 1) results in two more recursive calls to the fibonacci method. This set of recursive calls rapidly gets out of hand. Calculating the Fibonacci value of 20 using the program in Fig. 6.13 requires 21,891 calls to the fibonaccimethod; calculating the Fibonacci value of 30 requires 2,692,537 calls to the fibonaccimethod. f( 3 ) f( 1 )f( 2 ) f( 1 ) f( 0 ) return 1 return 1 return 0 return + +return Fig. 6.14 Set of recursive calls to method fibonacci(fin this diagram). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01