Skip to main content
Engineering LibreTexts

12.2: Composition Revisited

  • Page ID
    15229
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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: Test.java  [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.


    This page titled 12.2: Composition Revisited is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?