|
|
Sample Exam Question |
||||||||||||||||||||||||||||||
|
The sample question for the Sun Certified Java Programmer Exam 310-020 is: Given the following code:
Which one or more of the following correctly describe the behavior when this program is compiled and run? a) compilation is successful and the output is: d1 is Fri December 31 00:00:00 GMT 1999 d2 is Fri December 31 00:00:00 GMT 1999 b) compilation is successful and the output is: d1 is Fri December 31 00:00:00 GMT 1999 d2 is Sun December 31 00:00:00 GMT 2000 c) compilation is successful and the output is: d1 is Sun December 31 00:00:00 GMT 2000 d2 is Sun December 31 00:00:00 GMT 2000 d) the assignment 'd1 = d2' is rejected by the compiler because the Date class cannot overload the operator '='. e) the expression (d1 is " + d1 + "\nd2 is " + d2) is rejected by the compiler because the Date class cannot overload the operator '+'.
Both of these line are perfectly legal, and do not result in a compilation error, so d) is false. I will also point out here that e) is also false, because Java is smart enough to call the method toString() for any object that is used in a String context. toString() is defined by the Object class and so it is available on all classes in Java. Most non-trivial classes override toString() to return more explicit information about themselves. The question becomes, how does altering an object in method effect the object in the calling method? It seems obvious that if Java is to be usable, that the call d2.setYear(100); must alter the data in d2 and that change must be visible to the calling method. So the value of d2 is changed. But what happens when the actual object reference is changed, as happens when d1 = d2;? Within method, d1 now refers to the same underlying object as d2. So within method, the year for d1 is 2000. However, within method, d1 is an automatic variable the is on the stack the refers to an object on the head. The assignment of d1 does not change the object, only the reference to it. As d1 is local to method, when method returns, the value of d1 is lost.
|
||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||