Chapter 6 Methods 249 6.3 Math Class Methods (Web host music)

Chapter 6 Methods 249 6.3 Math Class Methods Mathclass methods allow the programmer to perform certain common mathematical calculations. We use various Math class methods here to introduce the concept of methods. Throughout the book, we discuss many other methods from the classes of the Java API. Methods are called by writing the name of the method, followed by a left parenthesis, followed by the argument (or a comma-separated list of arguments) of the method, followed by a right parenthesis. For example, a programmer desiring to calculate the square root of 900.0 might write Math.sqrt( 900.0 ) When this statement executes, it calls staticMath method sqrt to calculate the square root of the number contained in the parentheses (900.0). The number 900.0 is the argument of method sqrt. The preceding expression evaluates to 30.0. Method sqrt method takes an argument of type double and returns a result of type double. Note that all Math class methods are static; therefore, they are invoked by preceding the name of the method with the class name Math and a dot (.) operator. To output the value of the preceding method call in the command window, a programmer might write System.out.println( Math.sqrt( 900.0 ) ); In this statement, the value that sqrt returns becomes the argument to method println. Software Engineering Observation 6.2 It is not necessary to import class Math to use its methods. Math is part of the java.lang package, which is automatically imported by the compiler. Common Programming Error 6.1 Forgetting to invoke a Math class method by preceding the name of the method with the class name Math and a dot operator (.) results in a syntax error. Method arguments may be constants, variables or expressions. If c1=13.0, d=3.0 and f=4.0, then the statement System.out.println( Math.sqrt( c1 + d * f ) ); calculates and prints the square root of 13.0+3.0*4.0=25.0, namely 5.0. Some Math class methods are summarized in Fig. 6.2. In the figure, the variables x and y are of type double. The Math class also defines two commonly used mathematical constants: Math.PI and Math.E. The constant Math.PI (3.14159265358979323846) of class Math is the ratio of a circle s circumference to its diameter. The constant Math.E (2.7182818284590452354) is the base value for natural logarithms (calculated with static Math method log). 6.4 Methods Methods allow the programmer to modularize a program. Variables declared in method definitions are local variables only the method that defines them knows they exist. Most methods have a list of parameters that provide the means for communicating information between methods via method calls. A method s parameters are also local variables. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Leave a Reply