Java Reference
In-Depth Information
I can safely bet that you will be asked a question on the exam regarding a
static method attempting to access a nonstatic field. Static methods cannot
reference the nonstatic fields of the class and do not have access to a this
reference. Understanding this rule implies your understanding of static
methods, and static methods are a fundamental aspect of the Java language,
so expect your knowledge of this subject to be tested on the exam.
Variable-Length Arguments
As of Java 5.0, a method can allow for a variable-length list of arguments to be passed
in to the method. The syntax for declaring a variable-length argument list is to use three
dots, referred to as an ellipsis, following the data type of the parameter. A method can
only declare one parameter as variable length, and it must appear at the end of the list of
parameters.
For example, the following method declaration allows for a variable number of String
references to be passed in:
public void logErrors(Date timeStamp, String... errors)
To invoke logErrors , the fi rst argument must be a java.util.Date object followed by
any number of String objects. Examine the following statements and determine if they are
valid method invocations of logErrors :
31. Date now = new Date();
32. m.logErrors(now);
33. m.logErrors(now, “Problem #1”);
34. m.logErrors(now, “a”, “b”, “c”, “d”, “e”, “f”);
35. String [] array = {“does”, “this”, “work?”};
36. m.logErrors(now, array);
Java treats a variable-length parameter as an array whose elements are the data type
of the parameter. The errors parameter in logErrors is actually an array of String
references, so each of the previous calls to logErrors is valid. The array is empty with the
method call on line 32. Line 33 creates an array with one String : “Problem #1” , and line
34 creates a String array containing six String objects. Line 36 already passes in an array,
so the compiler does not need to create a new one.
The following example shows the logErrors method in a class named MyErrorLog .
Notice on line 18 the logErrors method uses a for-each loop to iterate through the
variable-length parameter errors and write each one to a text fi le. Examine the code and
see if you can determine its result.
1. import java.io.*;
2. import java.util.Date;
3.
4. public class MyErrorLog {
Search WWH ::




Custom Search