The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Composition

Just as with mathematical functions, Java methods can be composed, meaning that you 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);

This statement takes the value Math.PI, divides it by two and adds the result to the value of the variable angle. The sum is then passed as an argument to the cos method. (Notice that PI is the name of a variable, not a method, so there are no arguments, not even the empty argument ()).

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 function 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; I hope you know what it is.



Last Update: 2011-01-24