Chapter 4 Methods

1.         See the section "Creating a Method."

 

            2.         void

 

3.         A syntax error occurs if a return statement does not appear in a non-void method. You can have a return statement in a void method, which simply exits the method.

 

4.         Method overloading is defining two methods with the same name but different parameter profiles. You can define two methods that have the same name but different parameters. However, you cannot define two methods in a class that have identical method names and parameter profiles but different return value types or different modifiers.

 

5.         You pass actual parameters by passing the right type of value in the right order. The actual parameter can have the same name as its formal parameter.

 

6.         "Pass by value" is to pass a copy of the value to the method. The output of the program is 0, because the variable max is not changed by invoking the method max.

 

7.        

 

 

8.         True.

 

9.         No.

 

10.       No.

 

11.       Computing a sales commission given the sales amount and the commission rate

                        Answer: non-void method with return type double

 

Printing a calendar for a month

Answer: void method

 

Computing a square root

                        Answer: non-void method with return type double

 

Testing whether a number is even and return true if it is

                        Answer: non-void method with return type boolean

 

Printing a message for a specified number of times

                        Answer: void method

 

Computing the monthly payment, given the loan amount, number of years, and annual interest rate.

Answer: non-void method with return type double.

            Finding the corresponding uppercase letter given a lowercase letter.

Answer: non-void method with return type char.

 

12.       b.

 

13.      

 

      Math.sqrt(4) = 2.0

      Math.sin(2*Math.PI) = 0

      Math.cos(2*Math.PI) = 1

      Math.pow(2, 2) = 4.0

      Math.log(Math.E) = 1

      Math.exp(1) = 2.718

      Math.max(2, Math.min(3, 4)) = 3

Math.rint(-2.5) = -2.0

Math.ceil(-2.5) = -2.0

Math.floor(-2.5) = -3.0

Math.round(-2.5f) = -2

Math.round(-2.5) = -2

Math.rint(2.5) = 2.0

Math.ceil(2.5) = 3.0

Math.floor(2.5) = 2.0

Math.round(2.5f) = 3

Math.round(-2.5) = -2

      Math.round(Math.abs(-2.5)) = 3

 

            14.       A method that calls itself.

 

            15.       One or more base cases (the simplest case) are used to stop recursion.

Every recursive call reduces the original problem, bringing it increasingly close to a base case until it becomes that case.

 

16.       The output is 15 (5 + 4 + 3 + 2 + 1 = 15)

 

17.       method1 is not defined correctly. It does not have a return type or void. The semicolon (;) in the method xMethod heading should be removed. if (n<0) should be removed, for otherwise the a compilation error is reported.