Java Tutorial: The Power Function

By Xah Lee. Date: ,

Java doesn't provide the power operator. (For example, “^” 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);

In the above example, we defined 2 classes, T1, T2.

“T1” is the main class for this file. Save the file as

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.)

In the main class “T1”, the line:

T2 x1 = new T2();

It means: x1 is a variable, its type is T2. The value of x1 is a new instance of T2.

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.

Math (Java Platform SE 8 )