Math Class & Class Methods

The Math class is one which has a bunch of methods that are quite useful quite often.

Among them are Math.random() and Math.pow() - see below.

But here's the thing that is different about them to note, they are class methods rather than instance methods. (Another way of putting this is that they are static.)

Usually we think of methods as being called from a particular instance of a class. For example:

public class AClass{
private String name = "not set yet";
public Class1(String name){ this.name = name; } public void printName(){
System.out.println(name); }

and then in another class, lines like:

Class1 x = new Class1("John");
x.method1(); Class1 y = new Class1("Bob");

Above, the method can only be called once an instance of the class is made. And note that depending on how each of the instance above were made, the method1 will do something differnt - as it is printing out John in the first case, and Bob in the second. Compare that to the following lines:

public class Math{     //btw, this is just a simplified version; the real pow method uses doubles
public int pow(int base, int power){
int total = base;
for(int i = 0; i < power; i++){
total *= base;
} return total; }
and then in another class, lines like:

So for the pow method of the Math class, there is no need to make an instance. That's because the pow method does not depend on any particular attributes of a particular instance of the Math class. It just works based on the parameters sent it.

Methods and attributes also are made to be class methods and attributes by using the static key word in their definition. (Refer to the earlier notes on static.)

Other Important Math Class Methods & Attributes


Math.round() - Rounds a double and returns a long. .5 is rounded up

Math.floor() - Takes a double down to the nearest whole number, but it remains a double, so 45.999 becomes 45.0

Math.ceil() - Takes a doulbe up to the nearest whole number, so 82.345 becomes 83.0

Math.random() - Returns a random double between 0.000000000000000 and .9999999999999999
--> With Math.random, to scale it up, you multiply, so Math.random() * 100 returns doubles between 0.000000000000000 and 99.99999999999999
--> And to change the range, add to get the lowest value, so Math.random() * 100 + 40 returns doubles between 40.00000000000000 to 139.9999999999999

(which obviously are not private, they must be declared as public in the Math class)

Math.PI - Yeilds the double 3.141592653589793

Math.E - Yeilds the double 2.718281828459045