Java Reference
In-Depth Information
Consider the following statement:
int x = 100 * Constants.MULTIPLIER;
When you compile the above statement, the compiler will replace Constants.MULTIPLIER with its value 12 and
your statement is compiled as
int x = 100 * 12;
Now, 100 * 12 is also a compile-time constant expression. The compiler will replace it with its value 1200 and
your original statement will be compiled as
int x = 1200;
There is one downside of this compiler optimization. If you change the value of the MULTIPLIER final variable in
the Constants class, you must recompile all the classes that refer to the Constants.MULTIPLIER variable. Otherwise,
they will continue using the old value of the MULTIPLIER constant that existed when they were compiled last time.
What is a varargs Method?
The term “varargs” is shorthand for “variable-length arguments.” The varargs feature was introduced in Java 5. It lets
you declare a method or constructor that accepts a variable number of arguments (or parameters). I will use only the
term “method” in our discussion. However, the discussion also applies to constructors.
The number of arguments a method accepts is called its arity. A method that accepts variable-length arguments
is called a variable-arity method or varargs method. What does a varargs method look like? Let's discuss how a non-
varargs method works before you look at a varargs method.
Consider the following code for a MathUtil class that declares a max() method. The method has two parameters.
It computes and returns the maximum of its two arguments.
public class MathUtil {
public static int max(int x, int y) {
int max = x;
if (y > max) {
max = y;
}
return max;
}
}
There is nothing extraordinary going on in the MathUtil class or in its max() method. Suppose you want to
compute the maximum of two integers, say 12 and 18; you would invoke the max() method as so:
int max = MathUtil.max(12, 18);
When the above statement is executed, 18 will be assigned to the variable max . Suppose you want to compute the
maximum of three integers. You might come up with the following logic:
int max = MathUtil.max(MathUtil.max(70, 9), 30);
 
Search WWH ::




Custom Search