- The Math class is part of the Java API.
- Math class methods enable the programmer to specify many common mathematical calculations.
- Methods are invoked by specifying the name of the method followed by its arguments, if any, enclosed in
parentheses: ( ).
- For example, printing the square root of 900 can be accomplished as follows:
System.out.println( Math.sqrt( 900.0 ) );
In this instance:
- The method name is Math.sqrt.
- It has 1 argument: 900.0, the number whose square root is sought.
- The type of the argument to Math.sqrt is double.
- The type of the value returned by Math.sqrt (in this case, 30) is double
- Normally, a method (e.g., drawString) is invoked by an object (e.g., g).
g.drawString("Send g the drawString message.", 25, 52);
- Class methods however are associated via the dot notation with a class name, in this case Math.
Another class method that we have seen is Integer.parseInt (Integer is the class name; parseInt is the
method name). Its argument is of type String; its return type is int;
Its "inverse" class method Integer.toString, takes an argument of type int, and returns a value of type String.
- Lastly, when you invoke an applet method within the definition of an applet [sub]class, the dot notation is
dropped:
showStatus("Applet started."); // apply showStatus to this applet class (e.g., Addition).
showStatus, the method name, is implicitly applied to the applet class in which the statement appears.
- If a method has an argument of a certain type, say int, then its argument can be any expression whose value is of
that type.
double c = 13.0, d = 3.0, e = 4.0;
System.out.println( c + Math.sqrt( c + d * f ) );
prints 18. At the time the statement is executed, Java:
- substitutes the value of c, d, and e in the expression:
System.out.println( 13.0 + Math.sqrt( 13.0 + 3.0 * 4.0 ) );
- evaluates the Math.sqrt argument expression:
System.out.println(13.0 + Math.sqrt( 25 ) );
- performs the Math.sqrt class method, substituting the returned value:
System.out.println( 13.0 + 5.0 ); // println with an argument of type double?
- evaluates the println argument expression:
System.out.println( 18.0 );
- performs the println method, sending "18" to the System.out Stream.
- Familiarize yourself with the Math class methods given on Chapter 4 of our text book:
- abs ( x )
- ceil ( x )
- cos ( x )
- exp ( x )
- floor ( x )
- log ( x )
- max ( x, y )
- min ( x, y )
- pow ( x, y )
- sin ( x )
- sqrt ( x )
- tan ( x )