JAVA Math-Functions
JAVA Math-Functions
James Brucker
Mathematical Functions
The Math class contains methods for common math functions.
They are static methods, meaning you can invoke them using
overload: using the same name for functions that have different parameters.
Example: Math.abs( int ) has int parameter and returns an int result.
Math.abs( double ) has double parameter and returns a double
Overloaded Functions Example
Example Returns
Math.max( 2, 10 ) (int) 10
Math.max( -1L, -4L ) (long) -1L
Math.max( 2F, 10.0F ) (float) 10.0F
Math.max( -4.0, 0.5 ) (double) 0.5
Example Returns
Math.max( 2, 10.0F ) ?
Math.max(-1, -4L ) ?
Math.max( 3, 1.25 ) ?
Functions and Data Types
Java promotes one of the arguments until it finds a
matching function prototype.
double Example Promotion Then Call
Math.max( 2, 10.0F ) 2 to 2.0F max(2F, 10F)
Math.max(-1, -4L ) -1 to -1L max(-1L, -4L)
float
Math.max( 3, 2.236 ) 3 to 3.0 max(3.0,2.236)
long
Automatic Conversions
int
When necessary, Java automatically "promotes" an
argument to a higher data type according to the diagram.
short,char These widening conversions will never "overflow" the data
type, but may result in lose of precision
byte
Analyzing an Expression
How would you write this in Java syntax?
2
−b+ √ b −4 ac
x=
2a
2
−b+ √ b −4 ac
x=
2a
x = ( -b + Math.sqrt(b*b - 4*a*c) ) / ( 2 * a)
Analyzing an Expression
Converting Strings to Numbers
Many times we have a String containing a number.
How can we convert it to a number?
Java has "wrapper classes" for primitive data types.
Warning: if you apply these methods to a String that does not contain a valid
number, Java will throw an Exception at run-time.
Converting Numbers to Strings
Java automatically converts numbers to strings when:
used in print & println: System.out.println( x );
concatenated to a String: String s = "x = " + x;
To create a String from a numeric value use toString :
Example: find the distance from point (x1, y1) to (x2, y2)