Java Tutorial: The Power Function

, ,

It's interesting that java doesn't provide the power operator. (⁖ “^” in 3^4). You have to use java.lang.Math.pow(3,4). That method returns type “double”.

import java.lang.Math;

class T2 {
    public double square (int n) {
        return java.lang.Math.pow(n,2);
    }
}

class T1 {
    public static void main(String[] arg) {
        T2 x1 = new T2();
        double m = x1.square(3);
        System.out.println(m);
    }
}

In the above example, we defined a class “T2” and “T1”.

“T1” is the main class for this file. The file name thus should be T1.java. The “T2” is a auxiliary class, that is, a helper class for what we need do in this package.

The “T2” class defines one method, the “square”. It takes a “integer” and returns a decimal number of type “double”. (“double” basically means a large decimal number. Whenever you want a decimal number, you should use the “double” type, unless you know what you are doing.)

In the main class “T1”, the line:

T2 x1 = new T2();

creates a new instance of the class “T2”, and named it “x1”.

The line:

double m = x1.square(3);

calls the “square” method of “x1”, and assign the result to “m”.

In java, all numbers have a type. All method definition must declare a type for each of their parameter, and declare a type for the thing the method returns.

Java Doc: Math

blog comments powered by Disqus