Skip to main content
Engineering LibreTexts

12.2: Composition Revisited

  • Page ID
  • Just as with mathematical functions, Java methods can be composed. That means you can use one expression as part of another. For example, you can use any expression as an argument to a method:

    double x = Math.cos(angle + Math.PI / 2.0);

    This statement divides Math.PI by two, adds the result to angle, and computes the cosine of the sum. You can also take the result of one method and pass it as an argument to another:

    double x = Math.exp(Math.log(10.0));

    In Java, the log method always uses base e. So this statement finds the log base e of 10, and then raises e to that power. The result gets assigned to x.

    Some math methods take more than one argument. For example, Math.pow takes two arguments and raises the first to the power of the second. This line of code assigns the value 1024.0 to the variable x:

    double x = Math.pow(2.0, 10.0);

    When using Math methods, it is a common error to forget the Math. For example, if you try to invoke pow(2.0, 10.0), you get an error message like:

    File:  [line: 5]
    Error: cannot find symbol
        symbol:   method pow(double,double)
        location: class Test

    The message “cannot find symbol” is confusing, but the last line provides a useful hint. The compiler is looking for pow in the same class where it is used, which is Test. If you don’t specify a class name, the compiler looks in the current class.

    • Was this article helpful?