Prev Main Next

Functions (Methods) That Act Like Expressions

In mathematics, a function takes one or more arguments and produces a result. For example, the square root function (sqrt) takes argument 16 and produces result 4. Graphically, you can understand the square root function by looking at how information flows through it.

In Java, a function is usually called a method. Unfortunately, the word method in English refers to how you do something. A mathematical function, such as the square root function, is defined quite independently of how you compute it. You can say that the square root of x is some number y so that y*y = x. How you find such a value y is another issue.

To emphasize the difference between information about what a function computes and how it works, I will depart from the usual Java terminology, and will call methods functions.


Employing a Function in Java

To use a function in Java, you write the name of the function followed by its argument in parentheses. What you get is an expression. For example, if the square root function is called sqrt, then you can write

  double x, y;
  x = 25.0;
  y = sqrt(x);
There is actually a square root function available for you, but it has a very long name in Java. It is called java.lang.Math.sqrt. (The dots are part of the name, just like the dots in www.yahoo.com are part of the name of Yahoo.) So you can write
  double x, y;
  x = 25.0;
  y = java.lang.Math.sqrt(x);
That is clumsy. There is a way to shorten it. If you write
  import java.lang.*;
just before your class, then you can call the square root function by a shorter name, Math.sqrt. So you write
  double x, y;
  x = 25.0;
  y = Math.sqrt(x);

Warning. You will be tempted to write

  import java.lang.Math.*;
to try to shorten the name even more. But for reasons that are to involved to go into right now, you cannot do that. The shortest you can get is Math.sqrt.


The argument can be any expression

The previous example used a variable, x, as the argument to the Math.sqrt function. But you can use any expression as the argument. For example, you can write the following in Java.

  double x, y, z;
  x = sqrt(36);
  y = sqrt(x + 10.0);
  z = sqrt(sqrt(x + 10.0));

Question. What are the values of x, y and z after running the statements just above this question? Answer[29]


Functions with more than one argument

If a function takes more than one argument, then you write the arguments in the parentheses, separated by commas. For example, there is a standard function called Math.pow, where Math.pow(x,y) produces xy. If you write

  double x,y,z;
  x = Math.pow(3.0,2.0);
  y = Math.pow(2.0,3.0);
  z = Math.pow(16.0, 1.0/2.0);
then you define x = 32 = 9, y = 23 = 8 and z = 161/2 = 4. The result is only approximate, and there might be some roundoff error.


Prev Main Next