Java: The Power Function

By Xah Lee. Date: . Last updated: .

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);
        System.out.println(m);
    }
}

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

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

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.

Java

  1. Install
  2. javac java jar javadoc

Java Basics

  1. Print String
  2. Strings
  3. Power Function
  4. Java Types and Type Conversion
  5. Function
  6. Arrays

Class, Inheritance

  1. extends
  2. Constructor
  3. Constructor Return Type
  4. Extending a Class that has Explicit Constructors
  5. static
  6. this
  7. super
  8. Access Specifiers

Abstract class, Interface

  1. abstract
  2. Interface

Package

  1. Package

Misc

  1. Collection, Map
  2. Read/Write File
  3. Convert File Encoding
  4. Complex Numbers in Java
  5. Unicode
  6. Number Literals