999 questions from cramming for sun java

256
Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035) SUN CERTIFIED PROGRAMMER FOR THE JAVA 2 PLATFORM 1.4 Available at: Authorized Prometric testing centres Exam number: CX-310-035 Prerequisites: None Exam type: Multiple choice and short answer Number of questions: 61 Pass score: 52% (32 of 61 questions) Time limit: 120 minutes Cost: US$150, or as priced in the country where the exam is taken 1 of 256

Upload: api-3845077

Post on 11-Apr-2015

443 views

Category:

Documents


0 download

DESCRIPTION

Very Good Questions for Cracking SUN java exams\\SCJA n SCJP

TRANSCRIPT

Page 1: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

SUN CERTIFIED PROGRAMMER FOR THE JAVA 2 PLATFORM 1.4 Available at: Authorized Prometric testing centres Exam number: CX-310-035 Prerequisites: None Exam type: Multiple choice and short answer Number of questions: 61 Pass score: 52% (32 of 61 questions) Time limit: 120 minutes Cost: US$150, or as priced in the country where the exam is taken

1 of 256

Page 2: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Exam Objectives

1 DECLARATIONS AND ACCESS CONTROL

1.1 Write code that declares, constructs and initialises arrays of any base type using any of the permitted forms both for declaration and for initialisation.

1.2 Declare classes, nested classes, methods, instance variables, static variables and automatic (method local) variables making appropriate use of all permitted modifiers (such as public, final, static, abstract, etc.). State the significance of each of these modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

1.3 For a given class, determine if a default constructor will be created and if so state the prototype of that constructor.

1.4 Identify legal return types for any method given the declarations of all related methods in this or parent classes.

2 FLOW CONTROL, ASSERTIONS, AND EXCEPTION HANDLING

2.1 Write code using if and switch statements and identify legal argument types for these statements.

2.2 Write code using all forms of loops including labeled and unlabeled, use of break and continue, and state the values taken by loop counter variables during and after loop execution.

2.3 Write code that makes proper use of exceptions and exception handling clauses (try, catch, finally) and declares methods and overriding methods that throw exceptions.

2.4 Recognize the effect of an exception arising at a specified point in a code fragment. Note: The exception may be a runtime exception, a checked exception, or an error (the code may include try, catch, or finally clauses in any legitimate combination).

2.5 Write code that makes proper use of assertions, and distinguish appropriate from inappropriate uses of assertions.

2.6 Identify correct statements about the assertion mechanism.

3 GARBAGE COLLECTION

3.1 State the behaviour that is guaranteed by the garbage collection system.

3.2 Write code that explicitly makes objects eligible for garbage collection.

3.3 Recognize the point in a piece of source code at which an object becomes eligible for garbage collection.

2 of 256

Page 3: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

4 LANGUAGE FUNDAMENTALS

4.1 Identify correctly constructed package declarations, import statements, class declarations (of all forms including inner classes) interface declarations, method declarations (including the main method that is used to start execution of a class), variable declarations, and identifiers.

4.2 Identify classes that correctly implement an interface where that interface is either java.lang.Runnable or a fully specified interface in the question.

4.3 State the correspondence between index values in the argument array passed to a main method and command line arguments.

4.4 Identify all Java programming language keywords. Note: There will not be any questions regarding esoteric distinctions between keywords and manifest constants.

4.5 State the effect of using a variable or array element of any kind when no explicit assignment has been made to it.

4.6 State the range of all primitive formats, data types and declare literal values for String and all primitive types using all permitted formats bases and representations.

5 OPERATORS AND ASSIGNMENTS

5.1 Determine the result of applying any operator (including assignment operators and instance of) to operands of any type class scope or accessibility or any combination of these.

5.2 Determine the result of applying the boolean equals (Object) method to objects of any combination of the classes java.lang.String, java.lang.Boolean and java.lang.Object.

5.3 In an expression involving the operators &, |, &&, || and variables of known values state which operands are evaluated and the value of the expression.

5.4 Determine the effect upon objects and primitive values of passing variables into methods and performing assignments or other modifying operations in that method.

6 OVERLOADING, OVERRIDING, RUNTIME TYPE AND OBJECT ORIENTATION

6.1 State the benefits of encapsulation in object oriented design and write code that implements tightly encapsulated classes and the relationships "is a" and "has a".

6.2 Write code to invoke overridden or overloaded methods and parental or overloaded constructors; and describe the effect of invoking these methods.

6.3 Write code to construct instances of any concrete class including normal top level classes and nested classes.

3 of 256

Page 4: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

7 THREADS

7.1 Write code to define, instantiate and start new threads using both java.lang.Thread and java.lang.Runnable.

7.2 Recognize conditions that might prevent a thread from executing.

7.3 Write code using synchronized wait, notify and notifyAll to protect against concurrent access problems and to communicate between threads.

7.4 Define the interaction among threads and object locks when executing synchronized wait, notify or notifyAll.

8 FUNDAMENTAL CLASSES IN THE JAVA.LANG PACKAGE

8.1 Write code using the following methods of the java.lang.Math class: abs, ceil, floor, max, min, random, round, sin, cos, tan, sqrt.

8.2 Describe the significance of the immutability of String objects.

8.3 Describe the significance of wrapper classes, including making appropriate selections in the wrapper classes to suit specified behavior requirements, stating the result of executing a fragment of code that includes an instance of one of the wrapper classes, and writing code using the following methods of the wrapper classes (e.g., Integer, Double, etc.): doubleValue floatValue intValue longValue parseXxx getXxx toString toHexString

9 THE COLLECTIONS FRAMEWORK

9.1 Make appropriate selection of collection classes/interfaces to suit specified behaviour requirements.

9.2 Distinguish between correct and incorrect implementations of hashcode methods.

4 of 256

Page 5: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

1. Which two create an instance of an array? (Choose two.)

A. int[ ] ia = new int[15];

B. float fa = new float[20];

C. char[ ] ca = "Some String";

D. Object oa = new float[20];

E. int ia[ ] [ ] = { 4, 5, 6 }, { 1,2,3 };

Answer: AD

Explanation: An array must be declared and constructed before it can be used. An array variable declaration has either the following syntax: <elementType>[ ] <arrayName>; or <elementType> <arrayName>[ ]; Once an array has been declared it can be constructed for a specific number of elements of the element data type, using the new operator. The resulting array can be assigned to a variable of the corresponding type: <arrayName> = new <elementType>[<noOfElements>]; The minimum value of <noOfElements> is 0, i.e. arrays with zero elements can be constructed in Java. The array declaration and construction can be combined: <elementType1> <arrayName>[ ] = new <elementType2>[<noOfElements>]; However, here array type <elementType2> must be assignable to array type <elementType1>. When the array is constructed, all its elements are initialised to the default value for <elementType2>. This is true for both member and local arrays when they are constructed. Java provides the means of declaring, constructing and explicitly initialising an array in one language construct: <elementType>[ ] <arrayName> = { <arrayInitializerCode> }; This form of initialisation applies to both members as well as local arrays. The initialisation code in the block results in the construction and initialisation of the array. For example the following array, anIntArray, is declared as an array of ints. It is constructed to hold 10 elements (equal to the number of items in the comma-separated list in the block), where the first element is initialised to 1, the second element to 3, and so on. int[ ] anIntArray = {1, 3, 49, 2, 6, 7, 15, 2, 1, 5}; In summary, an array type is written as the name of an element type followed by some number of empty pairs of square brackets [ ]. The number of bracket pairs indicates the depth of array nesting. An array's length is not part of its type. The element type of an array may be any type, whether primitive or reference.

5 of 256

Page 6: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

A is correct. It uses correct array declaration and correct array construction.

B is incorrect. It generates a compiler error: incompatible types because the array variable declaration is not correct. The array construction expects a reference type, but it is supplied with a primitive type in the declaration. This is why B doesn’t work and why D does work. It would compile if it was changed to any of the following: (i) float fa[ ] = new float[20]; (ii) float fa[]; … fa = new float[20]; (iii) float[] fa = new float[20]; (iv) float[] fa; … fa = new float[20]; C is incorrect. It generates a compiler error: incompatible types because a string literal is not assignable to a character type variable. The following is a suggested solution that compiles correctly (if an array of characters was required): char[ ] ca = {'S','o','m','e',' ','S','t','r','i','n','g'}; The following is a suggested solution that compiles correctly (if an array of strings was required): String[ ] ca = {"Some String"}; In both of the above, the data type returned by the array construction are of the correct data type to initialise the elements of array ca.

D is correct. All classes directly or indirectly extend the Object class. The Object class is the root of every inheritance hierarchy. The Object class defines the basic functionality that all objects exhibit and which all classes inherit. This also applies for array, since arrays are genuine objects in Java. My opinion is that this is allowed because the rule of thumb for converting reference values is that conversions up the inheritance hierarchy are allowed (upcasting), but conversions down the hierarchy require explicit casting (downcasting). That is, conversions that preserve the inheritance is-a relationship (an array is-a object) are allowed.

E is wrong, it generates a compiler error <identifier> expected. The compiler thinks that you are trying to create two arrays because there are two array initialisers to the right of the equals, whereas your intention was to create a 3 x 3 two-dimensional array. To correct the problem and make E compile you need to add an extra pair of curly brackets: int ia[ ] [ ] = { { 4, 5, 6 }, { 1,2,3 } };

Source code file: ArrayTest01.java

6 of 256

Page 7: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

2. Given: 01. public class ArrayTest { 02. public static void main(String[ ] args){ 03. float f1[ ], f2[ ]; 04. f1 = new float[10]; 05. f2 = f1; 06. System.out.println("f2[0] = " + f2[0]); 07. } 08. }

What is the result?

A. It prints f2[0] = 0.0

B. It prints f2[0] = NaN

C. An error at line 5 causes compile to fail.

D. An error at line 6 causes compile to fail.

E. An error at line 6 causes an exception at runtime.

Answer: A

Explanation: When you create an array (line 04) the elements are initialises to the default values for the primitive data type (float in this case - 0.0), so f1 will contain 10 elements each with a value of 0.0. f2 has been declared but has not been initialised, it has the ability to reference or point to an array but as yet does not point to any array. Line 05 copies the reference (pointer/memory address) of f1 into f2 so now f2 points at the array pointed to by f1. This means that the values returned by f2 are the values returned by f1. Changes to f1 are also changes to f2 because both f1 and f2 point to the same array. The following code illustrates this point: 01 public class ArrayTest02d { 02 public static void main(String[] args){ 03 float f1[], f2[]; 04 f1 = new float[10]; 05 for(int i = 0; i < 10; i++) f1[i] = i + 5; // init the array 06 f2 = f1; 07 System.out.println("f2[0] = " + f2[0]); // outputs 5.0 08 f1[0] = 99.99f; 09 System.out.println("f2[0] = " + f2[0]); // outputs 99.99 10 } 11 }

The following is a discussion on Not-a-Number (NaN).

The Java Language Specification 2 The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations. The IEEE 754 standard includes not only positive and negative numbers that consist of a sign and magnitude, but also positive and negative zeros, positive and negative infinities, and special Not-a-Number values (also abbreviated as NaN). A NaN value is used to represent the result of certain invalid operations such as dividing zero by zero. NaN constants of both float and double type are predefined as Float.NaN and Double.NaN.

For the most part, the Java platform treats NaN values of a given type as though collapsed into a single canonical value (and hence this specification normally refers to an arbitrary NaN as though to a canonical value). However, version 1.3 the Java platform introduced methods enabling the programmer to distinguish between NaN values: the Float.floatToRawIntBits and Double.doubleToRawLongBits methods. Refer to the

7 of 256

Page 8: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

specifications for the Float and Double classes for more information. In English the two floating-point types are float and double, they conform to the IEEE 754 specification. Many mathematical operations can yield results that have no expression in numbers (infinity, for example). To describe such non-numerical situations, both doubles and floats can take on values that are bit patterns that do not represent numbers. Rather, these patterns represent non-numerical values. The patterns are defined in the Float and Double classes and may be referenced as follows (NaN stands for Not a Number): Float.NaN Float.NEGATIVE_INFINITY Float.POSITIVE_INFINITY Double.NaN Double.NEGATIVE_INFINITY Double.POSITIVE_INFINITY The code below shows the use of these constants:

01 public class ArrayTest02a { 02 public static void main(String[] args) { 03 double d = -10.0 / 0.0; 04 if (d == Double.NEGATIVE_INFINITY) { 05 System.out.println( "d just exploded: " + d); 06 } 07 } 08 }

In this code fragment, the test on line 04 passes, so line 05 is executed. There is a significance associated with the NaN values. NaN values are used to indicate that a calculation has no result in ordinary arithmetic, such as some calculations involving infinity or the square root of a negative number. Two Nan values are defined in the java.lang package (Float.Nan and Double.Nan) and are considered non-ordinal for comparisons. This means that for any value of x, including NaN itself, all of the following comparisons will return false: x < Float.NaN x <= Float.NaN x == Float.NaN x > Float.NaN x >= Float.NaN In fact, the test Float.NaN != Float.NaN and the equivalent with Double.NaN return true, as you might deduce from the item above indicating that x == Float.NaN gives false even if x contains Float.NaN. The most appropriate way to test for a NaN result from a calculation is to use the Float.isNaN(float) or Double.isNaN(double) static methods provided in the java.lang package.

Source code files: ArrayTest02.java ArrayTest02a.java ArrayTest02b.java ArrayTest02c.java ArrayTest02d.java

8 of 256

Page 9: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

3. Which two cause a compiler error? (Choose two.)

A. int[ ] scores = {3, 5, 7};

B. int [ ][ ] scores = {2,7,6}, {9,3,45};

C. String cats[ ] = {"Fluffy", "Spot", "Zeus"};

D. boolean results[ ] = new boolean [3] {true, false, true};

E. Integer results[ ] = {new Integer(3), new Integer(5), new Integer(8)};

F. String[ ] dogs = new String[ ] {new String("Fido"), new String("Spike"), new String("Aiko")};

Answer: BD

Explanation: Read the explanations below in conjunction with those given for question 1. A does not cause a compiler error. Java provides the means of declaring, constructing and explicitly initialising an array in one language construct: <elementType>[ ] <arrayName> = { <arrayInitializerCode> }; This form of initialisation applies to both members as well as local arrays. The initialisation code in the block results in the construction and initialisation of the array. For example the following array, anIntArray, is declared as an array of ints. It is constructed to hold 10 elements (equal to the number of items in the comma-separated list in the block), where the first element is initialised to 1, the second element to 3, and so on. int[ ] anIntArray = {1, 3, 49, 2, 6, 7, 15, 2, 1, 5}; B generates a compiler error: <identifier> expected. The compiler thinks you are trying to create two arrays because there are two array initialisers to the right of the equals, whereas your intention was to create one 3 x 3 two-dimensional array. To correct the problem and make B compile you need to add an extra pair of curly brackets: int [ ] [ ] scores = { {2,7,6}, {9,3,45} }; C does not cause a compiler error. See the explanation above for A. D generates a compiler error: ';' expected. You cannot initialise an array in this manner because you are declaring the number of elements in two different places, between the brackets [3] and in the block {true, false, true}. Rewrite the line as follows to make it compile: boolean results[ ] = {true, false, true}; or boolean results[ ] = new boolean [ ] {true, false, true}; also works. Also see the explanation above for A. E compiles correctly. This code creates an array of arrays - it creates a one-dimensional array and initialises each element of this array according to the code in the block. See the explanation above for A. F compiles correctly. This code creates an array of string objects - it creates a one-dimensional array and initialises each element of this array according to the code in the block. See the explanation above for both A and D.

Source code file: ArrayTest03.java

9 of 256

Page 10: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

4. Which three form part of correct array declarations? (Choose three.)

A. public int a [ ]

B. static int [ ] a

C. public [ ] int a

D. private int a [3]

E. private int [3] a [ ]

F. public final int [ ] a

Answer: A, B, F

Explanation: An array declaration tells the compiler the array’s name and what type its elements will be not the number of elements in the array. A, B and F are valid array declarations. C is not a correct array declaration. The compiler complains with: illegal start of type. The brackets are in the wrong place. The following would work: public int[ ] a D is not a correct array declaration. The compiler complains with: ']' expected. A closing bracket is expected in place of the 3. The following works: private int a [] An array declaration tells the compiler the array’s name and what type its elements will be not the number of elements in the array. E is not a correct array declaration. The compiler complains with 2 errors: ']' expected A closing bracket is expected in place of the 3 and <identifier> expected A variable name is expected after a[ ] An array declaration tells the compiler the array’s name and what type its elements will be not the number of elements in the array. The following would work: private int[ ][ ] a

Source code file: ArrayTest04.java

10 of 256

Page 11: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

5. Which two cause a compiler error? (Choose two.)

A. float[ ] f = new float(3);

B. float f2[ ] = new float[ ];

C. float[ ]f1 = new float[3];

D. float f3[ ] = new float[3];

E. float f5[ ] = {1.0f, 2.0f, 2.0f};

F. float f4[ ] = new float[ ] {1.0f, 2.0f, 3.0f};

Answer: AB

Explanation: A causes two compiler errors ( '[' expected and illegal start of expression) because the wrong type of bracket is used, ( ) instead of [ ]. The following is the correct syntax: float[ ] f = new float[3]; B causes a compiler error ( '{' expected ) because the array constructor does not specify the number of elements in the array. The following is the correct syntax: float f2[ ] = new float[3]; C, D, E and F compile without error.

Source code file: ArrayTest04.java

11 of 256

Page 12: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

6. Given: 12. float f[ ][ ][ ] = new float[3][][]; 13. float f0 = 1.0f; 14. float[ ][ ] farray = new float[1][1];

Which is valid?

A. f[0] = f0;

B. f[0] = farray;

C. f[0] = farray[0];

D. f[0] = farray[0][0];

Answer: B

Explanation: A is incorrect. It results in the compiler error: incompatible types found float required float[][]. This means that f[0] is not the same data type as f0, and, they are not. f[0] is an array element that stores a reference to another array and you cannot assign a primitive value (the float f0) to a reference value. B is correct. You can assign one reference type to another. f[0] is a reference to a two dimensional array, farray is also a reference to a two dimensional array therefore farray can be assigned to f[0]. C is incorrect. It results in the compiler error: incompatible types found float[] required[][].You can assign one reference type to another. f[0] is a reference to a two dimensional array, farray[0] is reference to a one dimensional array therefore farray[0] cannot be assigned to f[0]. D is incorrect. It results in the compiler error: incompatible types found float required float[][].You can assign one reference type to another. f[0] is a reference to a two dimensional array, farray[0][0] is not a reference - it is a float therefore the float value stored in farray[0][0] cannot be assigned to the reference f[0].

Source code file: ArrayTest06.java

12 of 256

Page 13: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

7. Given: 01. public abstract class Test { 02. public abstract void methodA(); 03. 04. public abstract void methodB() 05. { 06. System.out.println("Hello"); 07. } 08. }

Which two changes, independently applied, allow this code to compile? (Choose two.)

A. add a method body to methodA

B. replace lines 5 -7 with a semicolon (";")

C. remove the abstract qualifier from the declaration of Test

D. remove the abstract qualifier from the declaration of methodA

E. remove the abstract qualifier from the declaration of methodB

Answer: BE

Explanation: Read this question carefully. How would you interpret the question if it had stated “simultaneously applied” rather than “independently applied”? I read this question as five different/separate/independent questions: 1). “If A is applied to the code as given will it allow the code to compile. 2). “If B is applied to the code as given will it allow the code to compile. 3). “If C is applied to the code as given will it allow the code to compile. 4). “If D is applied to the code as given will it allow the code to compile. 5). “If E is applied to the code as given will it allow the code to compile. Now which two of the above will allow the code to compile. To business, compiling the code as supplied generates a compiler error: abstract methods cannot have a body A is incorrect. If you add a method body to methodA you just get the compiler error message given above for both methodA and methodB. B is correct. This turns methodB into an abstract method and eliminates all compiler errors. C is incorrect. An abstract class is a class that has one or more abstract methods and methodA is an abstract method. D is incorrect. This causes the compiler error: missing method body, or declare abstract. This is self-explanatory. E is correct. This makes methodB into an ordinary method.

Source code file: ArrayTest06.java

13 of 256

Page 14: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

8. You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access that accomplishes this objective?

A. public

B. private

C. protected

D. transient

E. default access

Answer: C

Explanation: Access modifiers dictate which classes, not which instances, may access features. Methods and variables are collectively known as members. Method and variable members are given access control in exactly the same way. private makes a member accessible only from within its own class protected makes a member accessible only to classes in the same package or subclass of the class default access is very similar to protected (make sure you spot the difference) default access makes a member accessible only to classes in the same package public means that all other classes regardless of the package that they belong to, can access the member (assuming the class itself is visible) final makes it impossible to extend a class, when applied to a method it prevents a method from being overridden in a subclass, when applied to a variable it makes it impossible to reinitialise a variable once it has been initialised abstract declares a method that has not been implemented transient indicates that a variable is not part of the persistent state of an object volatile indicates that a thread must reconcile its working copy of the field with the master copy every time it accesses the variable After examining the above it should be obvious that the access modifier that provides the most restrictions for methods to be accessed from the subclasses of the class from another package is C – protected. A is also a contender but C is more restrictive, B would be the answer if the constraint was the “same package” instead of “any package” in other words the subclasses clause in the question eliminates default.

Source code file:

14 of 256

Page 15: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

9. You want a class to have access to members of another class in the same package. Which is the most restrictive access that accomplishes this objective?

A. public

B. private

C. protected

D. transient

E. default access

Answer: E

Explanation: The only two real contenders are C and E. Protected access (C) makes a member accessible only to classes in the same package or subclass of the class. While default access (E) makes a member accessible only to classes in the same package. Review the explanation for question 8 for more information.

Source code file:

15 of 256

Page 16: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

10. You want to limit access to a method of a public class to members of the same class. Which access accomplishes this objective?

A. public

B. private

C. protected

D. transient

E. default access

Answer: B

Explanation: Review the explanations for questions 8 and 9 for more information.

Source code file:

16 of 256

Page 17: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

11. Given: 01. public class Test { 02. public static void main(String args[]) { 03. class Foo { 04. public int i = 3; 05. } 06. Object o = (Object)new Foo(); 07. Foo foo = (Foo)o; 08. System.out.println("i = " + foo.i); 09. } 10. }

What is the result?

A. i =3

B. Compilation fails.

C. A ClassCastException is thrown at line 6.

D. A ClassCastException is thrown at line 7.

Answer: A

Explanation: B is not correct because the code compiles and runs ok. C is not correct because you can always cast up the hierarchy tree. D is not correct because o is a reference of type Object that points to a Foo object therefore Foo can be cast to a reference type of Foo.

Source code file: Test11.java and Test11a.java

17 of 256

Page 18: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

12. Given: 01. abstract class AbstractIt { 02. abstract float getFloat(); 03. } 04. public class AbstractTest extends AbstractIt { 05. private float f1 = 1.0f; 06. private float getFloat() { return f1; } 07. }

What is the result?

A. Compilation succeeds

B. An exception is thrown

C. Compilation fails because of an error at line 2

D. Compilation fails because of an error at line 6

Answer: D

Explanation: I got errors at line 4 – Class AbstractTest is public, should be declared in a file named Abstract Test.java And at line 6 – Abstract Test cannot override getFloat() in AbstractIt, attempting to assign weaker access privileges. This is probably the point of the question. The private on line 06 is more restrictive than the default access on line 02. Compilation fails so that rules out answers A and B. Line 2 compiles OK, ruling out answer C. So, by default the answer must be D.

Source code file:

18 of 256

Page 19: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

13 Given: 01. public class OuterClass { 02. private double d1 = 1.0; 03. // insert code here 04. }

Which two are valid if inserted at line 3 (Choose two)

A. static class InnerOne { public double methoda() { return d1; } }

B. static class InnerOne { static double methoda() { return d1; } }

C. private class InnerOne { public double methoda() { return d1; } }

D. protected class InnerOne { static double methoda() { return d1; } }

E. public abstract class InnerOne { public abstract double methoda(); }

Answer: C, E

Explanation: A, B and D are incorrect because the non-static variable d1 cannot be referenced from a static context. Static inner classes do not have any reference to an enclosing instance, therefore you cannot use the this keyword, either implied or explicit.

Source code file: OuterClass13.java

19 of 256

Page 20: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

14. Click on the Exhibit button 01. public class Test { 02. public int aMethod() { 03. static int i = 0; 04. i++; 05. return i; 06. } 07. public static void main(String args[]) { 08. Test test = new Test(); 09. test.aMethod(); 10. int j = test.aMethod(); 11. System.out.println(j); 12 } 13. }

What is the result?

A. 0

B. 1

C. 2

D. Compilation fails

Answer: D

Explanation: Compilation failed because static was an illegal start of expression - method variables do not have a modifier (they are always considered local). Two more errors followed on from this saying on both occasions cannot resolve symbol. Now, if the line 03 from the code was moved from the method to the class (see code below) then C would be the correct answer. public class Test14a { static int i = 0; public int aMethod() { i++; return i; } public static void main(String args[]) { Test14a test = new Test14a(); test.aMethod(); int j = test.aMethod(); System.out.println(j); } } Source code file: Test14.java Test14a.java

20 of 256

Page 21: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

15. Click on the Exhibit button

ClassOne.java: 01. package com.abc.pkg1; 02. public class ClassOne { 03. private char var = 'a'; 04. char getVar() { return var; } 05. }

ClassTest.java: 01. package com.abc.pkg2; 02. import com.abc.pkg1.ClassOne; 03. public class ClassTest extends ClassOne { 04. public static void main(String[] args) { 05. char a = new ClassOne.getVar(); 06. char b = new ClassOne.getVar(); 07. } 08. }

What is the result?

A. Compilation fails

B. Compilation succeeds and no exceptions are thrown

C. An exception is thrown at line 5 in ClassTest.java

D. An exception is thrown at line 6 in ClassTest.java

Answer: A

Explanation: It wouldn’t compile giving two errors: Cannot resolve symbol in line 5 char a = new ClassOne.getVar(); Cannot resolve symbol in line 6 char b = new ClassOne.getVar(); If lines 5 and 6 are amended: line 5: char a = new ClassOne().getVar(); line 6: char b = new ClassOne().getVar(); then the compilation still fails because getVar() has default access and not public or protected. Default allows package access but does not allow access from a sub-class while protected and public do. In this case, this is the reason that compilation fails. Another clue is that the package details are given.

Source code file:

21 of 256

Page 22: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

16. Given: 01. package test1; 02. public class Test1 { 03. static int x = 42; 04. } 01. package test2; 02. public class Test2 extends test1.Test1 { 03. public static void main(String[] args) { 04. System.out.println("x = "+x); 05. } 06. }

What is the result?

A. x = 0

B. x = 42

C. Compilation fails because of an error in line 2 of class Test2

D. Compilation fails because of an error in line 3 of class Test1

E. Compilation fails because of an error in line 4 of class Test2

Answer: E

Explanation: I got an error in line 4 saying, x is not public in Test1. Test1 cannot be accessed from outside package System.out.println(“x = ” + x); Think it through: ► What access modifier is needed to access a class member in another package? (Answer: public / protected.) ► What is the access modifier for x? (Answer: default.) ► What is the scope of default? (Answer: current package and not including sub classes.) From the compile error, in this case, it must be public/protected. However if you make the variable x in Test1 public static, then all the code compiles and the number 42 is output.

Source code file: Test16.java Test16a.java

22 of 256

Page 23: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

17. Given 01. public class Outer { 02. public void someOuterMethod() { 03. //Line 3 04. } 05. public class Inner { } 06. public static void main(String[] argv) { 07. Outer o = new Outer(); 08. //Line 8 09. } 10. }

Which instantiates an instance of inner?

A. new Inner(); //At line 3

B. new Inner(); //At line 8

C. new o.Inner(); //At line 8

D. new Outer.Inner(); //At line 8

Answer: A

Explanation: A compiles without problem B gives error – non-static variable cannot be referenced from a static context C package o does not exist D gives error – non-static variable cannot be referenced from a static context

Source code file: Outer.java

23 of 256

Page 24: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

18. Click the Exhibit button 01. class Super{ 02. public int i = 0; 03. 04. public Super(String text){ 05. i = 1; 06. } 07. } 08. 09. class Sub extends Super{ 10. public Sub(String text){ 11. i = 2; 12. } 13. 14. public static void main(String args[]){ 15. Sub sub = new Sub("Hello"); 16. System.out.println(sub.i); 17. } 18. }

What is the result?

A. 0

B. 1

C. 2

D. Compilation fails.

Answer: D

Explanation: A default no-args constructor is not created because there is a constructor supplied that has an argument, line 04. Therefore the sub-class constructor must explicitly make a call to the super class constructor: 10. public Sub(String text){ 11. super(text); // this must be the first line constructor 12. i = 2; 13. }

Source code file: Super18.java

24 of 256

Page 25: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

19. Which three statements are true? (Choose three.)

A. The default constructor initialises method variables.

B. The default constructor has the same access as its class.

C. The default constructor invokes the no-arg constructor of the superclass.

D. If a class lacks a no-arg constructor, the compiler always creates a default constructor.

E. The compiler creates a default constructor only when there are no other constructors for the class.

Answer: B, C, E

Explanation: A is the wrong answer because the default constructor does not initialise method variables. If you want to perform some initialisation you will have to write some constructors for your class. B sounds correct as in the example below class CoffeeCup { private int innerCoffee; public CoffeeCup() { } public void add(int amount) { innerCoffee += amount; } //... } The compiler gives default constructors the same access level as their class. In the example above, class CoffeeCup is public, so the default constructor is public. If CoffeeCup had been given package access, the default constructor would be given package access as well. C is correct. The Java compiler generates at least one instance initialisation method for every class it compiles. In the Java class file, the instance initialisation method is named "<init>." For each constructor in the source code of a class, the Java compiler generates one <init>() method. If the class declares no constructors explicitly, the compiler generates a default no-arg constructor that just invokes the superclass's no-arg constructor. As with any other constructor, the compiler creates an <init>() method in the class file that corresponds to this default constructor. D is wrong because the compiler does not always create a default constructor the main reason being that the compiler will not do so if a constructor is already declared by the programmer. E is correct. The compiler creates a default constructor if you do not declare any constructors in your class.

Source code file:

25 of 256

Page 26: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

20. Given 01. class TestSuper{ 02. TestSuper(int i) {} 03. } 04. class TestSub extends TestSuper{} 05. class TestAll{ 06. public static void main(String[] args){ 07. new TestSub(); 08. } 09. }

A. Compilation fails

B. The code runs without exception

C. An exception is thrown at line 7

D. An exception is thrown at line 2

Answer: A

Explanation: The code does not compile therefore the correct answer is A (the compiler cannot resolve the constructor TestSuper()) TestSub doesn’t have a constructor therefore the default constructor for TestSub calls the no-args constructor of the superclass(TestSuper), but TestSuper doesn’t have a no-args constructor because it already has a constructor with arguments The code will compile and run if you do something like the following: class TestSuper{ TestSuper(int i) {} } class TestSub extends TestSuper{ TestSub() { super(12); } } class TestAll{ public static void main(String[] args){ new TestSub(); } }

Source code file:

26 of 256

Page 27: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

21. Given 01. class Base{ 02. Base(){System.out.print("Base");} 03. } 04. public class Alpha extends Base{ 05. public static void main(String[] args){ 06. new Alpha(); 07. new Base(); 08. } 09. }

What is the result?

A. Base

B. BaseBase

C. Compilation fails

D. The code runs with no output

E. An exception is thrown at runtime

Answer: B

Explanation: A is wrong. It would be correct if either the main class or the subclass had not been instantiated. B is correct. It would be correct if the code had compiled, and the subclass Alpha had been saved in its own file. In this case Java supplies an implicit call from the sub-class constructor to the no-args constructor of the super-class therefore line 06 causes Base to be output. Line 07 also causes Base to be output C is wrong. The code compiles. D is wrong. There is output output. E is wrong. Because there are no errors in the code.

Source code file: Alpha.java

27 of 256

Page 28: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

22. Which two allow the class Thing to be instantiated using new Thing( )? (Choose two.)

A. public class Thing { }

B. public class Thing { public Thing() {} }

C. public class Thing { public Thing(void) {} }

D. public class Thing { public Thing(String s) {} }

E. public class Thing { public void Thing() {} public Thing(String s) {} }

Answer: AB

Explanation: A is correct because the compiler will add its own default constructor. public class Thing{ } class NextThing{ public static void main(String [] args){ new Thing(); } } B is correct because the programmer has added a constructor to the code. C is not correct. The compiler generates an error: illegal start of type. D is not correct. The code compiles when a string is added to the parameter. public class Thing{ public Thing(String s){} } class NextThing{ public static void main(String [] args){ Thing c1 = new Thing("hello"); } } But the question specifies new Thing( ) not new Thing(“Some king of string”), so this is wrong. E is not correct. This code compiles correctly, but, any code that tries to use the public void Thing() {} constructor will generate a compiler error (cannot resolve symbol) because of the void keyword. Constructors do not have a return type, we are dealing here with a method and not a constructor.

Source code files: Thing22a.java, NextThing22a.java Thing22b.java, NextThing22b.java Thing22c.java Thing22d.java, NextThing22d.java Thing22e.java, NextThing22e.java

28 of 256

Page 29: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

23. Given: 01. class A { 02. A( ) { } 03. } 04. 05. class B extends A { 06. }

Which two statements are true? (Choose two.)

A. Class B'S constructor is public.

B. Class B'S constructor has no arguments.

C. Class B'S constructor includes a call to this( ).

D. Class B'S constructor includes a call to super( ).

Answer: B, D

Explanation: A is wrong. Class B inherits Class A’s constructor which uses default access.

B is correct. Class B inherits Class A’s constructor which has no arguments.

C is wrong. There is just no implicit call to this( ).

D is correct. There is an implicit call to super( ) added by the compiler.

class A{ A() { System.out.println("Constructing A. "); } } class B extends A { B() { System.out.println("Constructing B. "); } } class OrderOfConstruction { public static void main(String args[]) { B b = new B(); } } This code compiles and runs whether B( ) is included or not.

Source code files:

29 of 256

Page 30: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

The following is a summary of the key points about constructors: 1) The constructor name must match the name of the class. 2) Constructors must not have a return type. 3) It’s legal (but stupid) to have a method with the same name as the class, but that doesn’t make it a constructor. If you see a return type, it’s a method rather than a constructor. 4) Constructors are not inherited in the same way as normal methods. You can only create an object if the class defines a constructor with an argument list that matches the one your new call provides. 5) If you define no constructor in a class, then the compiler provides a default that takes no arguments. If you define even a single constructor, this default is not provided. The default constructor is always a no-arg constructor. If you want a no-arg constructor and you’ve typed any other constructor(s) into your class code, the compiler won’t provide the no-arg constructor (or any other constructor) for you. In other words, if you’ve typed in a constructor with arguments, you won’t have a no-arg constructor unless you type it in yourself ! 6) The default constructor: Has the same access modifier as the class. Has no arguments. Includes a no-arg call to the super constructor (super()). 7) It is common to provide multiple overloaded constructors – that is, constructors with different argument lists. One constructor can call another using the syntax this(arguments). 8) A constructor delays running its body until the parent parts of the class have been initialised. This commonly happens because of an implicit call to super( ) (no-arg) added by the compiler. You can provide your own call to super(arguments) to control the way the parent parts are initialised. If you do so, it must be the first statement of the constructor. You cannot make a call to an instance method, or access an instance variable, until after the super constructor runs. 9) A constructor can use overloaded constructor versions to support its work. These are invoked using the syntax this(arguments) and if supplied, this call must be the first statement of the constructor. In such conditions, the initialization of the parent class is performed in the overloaded constructor. 10) The only way a constructor can be invoked is from within another constructor. In other words, you can’t write code that actually calls a constructor as follows: class Horse { Horse() { } // constructor void doStuff() { Horse(); // calling the constructor - illegal! } } 11) Every constructor must have as its first statement either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()). 12) A no-arg constructor is not necessarily the default constructor, although the default constructor is always a no-arg constructor. The default constructor is the one the compiler provides! While the default constructor is always a no-arg constructor, you’re free to put in your own no-arg constructor. 13) You can access static variables and methods, although you can use them only as part of the call to super() or this(). (Example: super(Animal.DoThings()))

30 of 256

Page 31: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

14) Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated. 15) Interfaces do not have constructors. Interfaces are not part of an object’s inheritance tree. 16) The following modifiers are the only ones that can be applied to constructors: public protected (default) – not a modifier but the name of the access if no modifier is specified private - means only code within the class itself can instantiate an object of that type,

so if the private-constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.

31 of 256

Page 32: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

24. Given: 1. public class Test { }

What is the prototype of the default constructor?

A. Test( )

B. Test(void)

C. public Test( )

D. public Test(void)

E. public void Test( )

Answer: C

Explanation: A and B are wrong because they use the default access modifier and the access modifier for the class is public (remember, the default constructor has the same access modifier as the class). C is correct. Just because it is. D is wrong. The void makes the compiler think that this is a method specification – in fact if it were a method specification the compiler would spit it out. E is wrong because this is a method prototype (specification) with the method name the same as the class name – stupid. You know it is a method because it specifies a return type and constructors do not return anything – not even void.

Source code files: Test24.java, Tester24.java

32 of 256

Page 33: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

25. In which two cases does the compiler supply a default constructor for class A? (Choose two.)

A. class A { }

B. class A { public A( ) { } }

C. class A { public A(int x) { } }

D. class Z { } class A extends Z { void A( ) { } }

Answer: A, D

Explanation: If you define no constructor in a class, then the compiler provides a default no-args constructor. If you define even a single constructor, this default is not provided. A is correct. No constructor is programmed so the compiler supplies the default. B is wrong. The default constructor is not supplied because the programmer has defined a constructor. C is wrong. The default constructor is not supplied because the programmer has defined a constructor. D is correct. No constructor is programmed so the compiler supplies the default (void A( ) { } is a method specification).

Source code files: A.java, B.java, C.java, Z.java

33 of 256

Page 34: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

26. What produces a compiler error?

A. class A { public A(int x) { } }

B. class A { } class B extends A { B( ) {} }

C. class A { A( ) { } } class B { public B( ) {} }

D. class Z { public Z(int) {} } class A extends Z { }

Answer: D

Explanation: A is wrong because it compiles correctly. Class A has a constructor supplied – that’s fine. B is wrong because it compiles correctly. Class A has no constructor so the compiler will supply a default no-arg constructor. Class B extends class A and it has a constructor, now, the compiler will automatically supply the constructor in B with an implicit call to super( ) (no-arg) and this will call the default constructor for A. C is wrong because it compiles correctly. Both classes have constructors. They don’t interfere with each other in any way, that’s OK. D is correct. It does not compile. Class Z has a constructor supplied therefore it has no default constructor. Class A extends Z and has no constructor supplied therefore the compiler will supply a default constructor. Now, the default constructor: includes a no-arg call to the super constructor (super( )), but because class Z has no default constructor we get a compiler error. Equally you could argue that the compiler error is generated because the class Z constructor specification does not supply an identifier, if corrected it could look like this: public Z(int xyz) {}.

Source code file: Zd26.java

34 of 256

Page 35: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

27. Given: 01. public class A{ 02. void A() { 03. System.out.println("Class A"); 04. } 05. public static void main(String[] args) { 06. new A(); 07. } 08. }

What is the result?

A. Class A

B. Compilation fails.

C. An exception is thrown at line 2.

D. An exception is thrown at line 6.

E. The code executes with no output.

Answer: E

Explanation: A is wrong. B is wrong. C is wrong. The code runs without exception. D is wrong. The code runs without exception. E is correct. The specification at line 2 is for a method and not a constructor and this method is never called therefore there is no output. The constructor that is called is the default constructor.

Source code file: A27.java

35 of 256

Page 36: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

28. Given: 01. public class ReturnIt { 02. returnType methodA(byte x, double y) { 03. return (long)x / y * 2; 04. } 05. }

What is the narrowest valid returnType for methodA in line 2?

A. int

B. byte

C. long

D. short

E. float

F. double

Answer: F

Explanation: However A, B, C, D and E are all wrong. Each of these would result in a narrowing conversion. Whereas we want a widening conversion, therefore the only correct answer is F. Don’t be put off by the long cast, this applies only to the variable x and not the rest of the expression. It is the variable y (of type double) that forces the widening conversion to double. Java’s widening conversions are: - From a byte to a short, an int, a long, a float, or a double. - From a short, an int, a long, a float, or a double. - From a char to an int, a long, a float, or a double. - From an int to a long, a float, or a double. - From a long to a float, or a double. - From a float to a double.

Source code file: ReturnIT28.java

36 of 256

Page 37: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

29. Given: 01. public class ReturnIt { 02. returnType methodA(byte x, double y) { 03. return (short)x / y * 2; 04. } 05. }

What is the narrowest valid returnType for methodA in line 2?

A. int

B. byte

C. long

D. short

E. float

F. double

Answer: F

Explanation: See the explanation for question 28.

Source code file: ReturnIt29.java

37 of 256

Page 38: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

30. Given: 01. class Super { 02. public float getNum( ) { return 3.0f; } 03. } 04. 05. public class Sub extends Super { 06. 07. }

Which method, placed at line 6, causes compilation to fail?

A. public void getNum( ) { }

B. public void getNum(double d) { }

C. public float getNum( ) { return 4.0f; }

D. public double getNum(float d) { return 4.0d; }

Answer: A

Explanation: The signature of a method consists of the name of the method and the number and types of formal parameters to the method. A class may not declare two methods with the same signature, or a compile-time error occurs. Java requires that overriding methods in a sub class MUST have :- a) The same signature as the overridden method in the super class. (i.e. the same name as the method in the super class and the same arguments as the method in the super class) b) The same return type as the method in the super class (unless the method in the super class is “private”) c) If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private ; otherwise, a compile-time error occurs. (JLS 8.4.6.3) Permitted variations in overriding method definition – d) the subclass (overriding) method may NOT be more private than the superclass (overridden) method but may be less. (Boone & Stanek p. 210) (JLS 8.4.6.3) e) the subclass method cannot add Exception types to those defined in the superclass method declaration. f) Overloaded Methods. If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures. (JLS 8.4.7) Overloaded methods let you reuse the same method name in a class, but with different arguments (and optionally, a different return type). Overloading a method often means you’re being a little nicer to those who call your methods, because your code takes on the burden of coping with different argument types rather than forcing the caller to do conversions prior to invoking your method. The rules are simple:

38 of 256

Page 39: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Overloaded methods must change the argument list. Overloaded methods can change the return type. Overloaded methods can change the access modifier. Overloaded methods can declare new or broader checked exceptions. A method can be overloaded in the same class or in a subclass.

The following table gives some examples of illegal overrides:

Illegal Override Code Problem with the Code

private void eat() { } Access modifier is more restrictive

public void eat() throws IOException { } Declares a checked exception not declared by superclass version

public void eat(String food) { } A legal overload, not an override, because the argument list changed

public String eat() { } Not an override because of the return type, but not an overload either because there’s no change in the argument list

Answer A fails to compile. Because of incompatible return type. The return type in the super class is float and the return type in A is void. It fails point b) above. In other words, it is not an override because of the change in the return type and it is also not an overload because the argument list has not changed. Answer B – compiled. This is not an override because of the change in the return type, the compiler considers this to be an overloaded method because the argument list has changed. Answer C – compiled. Standard overriding - overrides the super class method, changing the implementation. Answer D – compiled. This is not an override because of the change in the return type, the compiler considers this to be an overloaded method because the argument list has changed. NOTE – as given compilation fails in any case – Super.java:5: class Sub is public, should be declared in a file named Sub.java public class Sub extends Super{ In order to compile anything – 1) make both classes access default. 2) make Super public and Sub default 3) make both classes public

Source code file:

39 of 256

Page 40: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

31. Click the Exhibit button. 01. class Super { 02. public int getLength() { return 4; } 03. } 04. 05. public class Sub extends Super { 06. public long getLength() { return 5; } 07. 08. public static void main(String[] args) { 09. Super sooper = new Super(); 10. Sub sub = new Sub(); 11. System.out.println( 12. sooper.getLength() + "," + sub.getLength()); 13. } 14. }

What is the output?

A. 4,4

B. 4,5

C. 5,4

D. 5,5

E. Compilation fails.

Answer: E

Explanation: Refer to the explanation given in question 30 The return type of getLength( ) in the super class is int and the return type in the sub class is long. In other words, it is not an override because of the change in the return type and it is also not an overload because the argument list has not changed.

Source code file:

40 of 256

Page 41: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

32. Click the Exhibit button. 01. class Super { 02. public Integer getLength() {return new Integer(4); } 03. } 04. 05. public class Sub extends Super { 06. public Long getLength() {return new Long(5); } 07. 08. public static void main(String[] args) { 09. Super sooper = new Super(); 10. Sub sub = new Sub(); 11. System.out.println( 12. sooper.getLength().toString() + “,” + 13. sub.getLength().toString() ); 14. } 15. }

What is the output?

A. 4,4

B. 4,5

C. 5,4

D. 5,5

E. Compilation fails.

Answer: E

Explanation: Refer to the explanation given in question 30 for more information. Answer E is correct, compilation fails – The return type of getLength( ) in the super class is an object of reference type Integer and the return type in the sub class is an object of reference type Long. In other words, it is not an override because of the change in the return type and it is also not an overload because the argument list has not changed.

Source code file:

41 of 256

Page 42: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

33. Given: 01. public class X { 02. public X aMethod() {return this;} 03. } 01. public class Y extends X { 02. 03. }

Which two methods can be added to the definition of class Y? (Choose two.)

A. public void aMethod() {}

B. private void aMethod() {}

C. public void aMethod(String s) {}

D. private Y aMethod() { return null;}

E. public X aMethod() { return new Y(); }

Answer: CE

Explanation: Refer to the explanation given in question 30 for more information. Answer A fails - it is not an override because of the change in the return type and it is also not an overload because the argument list has not changed. Answer B fails - the subclass (overriding) method may NOT be more private than the superclass (overridden) method. Answer C is acceptable – The sub class aMethod is not an override because of the change in the return type, it overloads the super class aMethod – matching name but different arguments. Answer D fails – - the subclass (overriding) method may NOT be more private than the superclass (overridden) method. Answer E is acceptable - The sub class aMethod overrides the super class aMethod – matching signature and return type.

Source code file:

42 of 256

Page 43: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

34. Click the Exhibit button. 01. interface Beta {} 02. 03. class Alpha implements Beta { 04. String testIt() { 05. return "Tested"; 06. } 07. } 08. 09. public class Main1 { 10. static Beta getIt() { 11. return new Alpha(); 12. } 13. public static void main(String[] args) { 14. Beta b = getIt(); 15. System.out.println(b.testIt()); 16. } 17. }

What is the result?

A. Tested

B. Compilation fails.

C. The code runs with no output.

D. An exception is thrown at runtime.

Answer: B

Explanation: a) A variable whose declared type is an interface type may have as its value a reference to any instance of a class which implements the specified interface. It is not sufficient that the class happen to implement all the abstract methods of the interface; the class or one of its superclasses must actually be declared to implement the interface, or else the class is not considered to implement the interface. JLS 9 So variable b of type Beta may hold a reference to class Alpha, which implements Beta – line 3. Method getIt() of Main1 class returns a reference to class Alpha so variable b should be created with that reference – line 14. b) The type of the object reference determines which variable you access. The type of the underlying object determines which method you invoke. “All-in-one Java 2 Exam Guide” Boone & Stanek p.109 Answer A – is wrong. Method testIt() is not a member of Beta so cannot be referred to by variable b (which is type Beta) – EXCEPT that the underlying reference is type Alpha and testIt() is a method of Alpha - see b) above? But the compiler can only use the compile-time reference (type Beta) to resolve the method invocation so compilation fails. If Beta declared testIt() then the reference would be valid and the overriding testIt() method in Alpha could be invoked. (providing the access modifiers are correct - the overriding method may NOT be more private than the overridden method but may be less. (JLS 8.4.6.3) Then A would be the correct answer.

43 of 256

Page 44: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Answer B is correct. The compiler complains that it “cannot resolve symbol” (the testIt() method). See A above. Answer C is wrong – cannot see a means by which this could be correct. Answer D is wrong – cannot see a means by which this could be correct.

Source code file:

44 of 256

Page 45: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

35. Click the Exhibit button. 01. interface Animal { 02. void soundOff(); 03. } 04. 05. class Elephant implements Animal { 06. public void soundOff() { 07. System.out.print1n("Trumpet"); 08. } 09. } 10. 11. class Lion implements Animal { 12. public void soundOff() { 13. System.out.print1n("Roar"); 14. } 15. } 16. 17. class Alpha1 { 18. static Animal get(String choice) { 19. if (choice.equalsIgnoreCase("meat eater") ) { 20. return new Lion(); 21. } else { 22. return new Elephant(); 23. } 24. } 25. }

Which compiles?

A. new Animal().soundOff();

B. Elephant e = new Alpha1();

C. Lion l = Alpha1.get("meat eater");

D. new Alpha1().get("veggie").soundOff();

Answer: D

Explanation: Refer to the explanation of question 34 for more information. Answer A fails –Animal is an interface and cannot be instantiated. Answer B fails - Alpha1 is not a subclass of Elephant so Elephant is ineligible to hold a reference to Alpha1. A reference to a class may only be assigned to a variable that has a class type of the same class or the reference must be to a subclass of the variable’s type. Answer C fails – Incompatible types. Alpha1.get() returns a reference of type Animal. Animal is an interface implemented by Lion and Elephant. The actual reference returned is to either Elephant or Lion. So a variable of type Animal could hold a reference to class Lion (JLS 5.2) but not the reverse, but the variable l (type Lion) receives a reference of either type Lion or type Elephant which can be cast from type Animal (interface) to type Lion (class), a narrowing reference conversion (JLS 5.1.5). This would compile if the returned reference was cast to type Lion. Answer D will compile - Alpha1.get returns a reference of type Animal which contains a reference to either class Lion or class Elephant, both of which implement interface Animal. The method .soundOff () is implemented by both Elephant and Lion so can be invoked by a refernce to either class.

Source code file:

45 of 256

Page 46: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

36. Given: 01. class A { 02. protected int method1(int a, int b) {return 0; } 03. }

Which two are valid in a class that extends class A? (Choose two.)

A. public int method1(int a, int b) {return 0; }

B. private int method1(int a, int b) { return 0; }

C. private int method1(int a, long b) {return 0; }

D. public short method1(int a, int b) { return 0; }

E. static protected int method1(int a, int b) { return 0; }

Answer: A, C

Explanation: A is correct - because the class that extends A is just simply overriding method1. B is wrong - because it can't override as there are less access privileges in the subclass method1. C is correct - because it is overloading and not overriding (it has different arguments to the super class method). D is wrong - because to override it, the return type needs to be an integer. The different return type means that the method is not overriding but the same argument list means that the method is not overloading. Conflict – compile time error. E is wrong - because you can't override a method and make it a class method i.e. using static.

Source code file:

46 of 256

Page 47: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

37. Click the Exhibit button. 01. class A { 02. final public int methodl(int a, int b) {return 0; } 03. } 04. class B extends A { 05. public int method1 (int a, int b) {return 1; } 06. } 07. public class Test { 08. public static void main(String args[]) { 09. B b; 10. System.out.println("x = " + b.method1(0, 1)); 11. } 12. }

What is the result?

A. x = 0

B. x = 1

C. Compilation fails.

D. An exception is thrown at runtime.

Answer: C

Explanation: The code doesn't compile because the method in class A is final and so cannot be overridden.

Source code file:

47 of 256

Page 48: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

38. Given: 11. switch(x) { 12. default: 13. System.outprintln("Hello"); 14. }

Which two are acceptable types for x? (Choose two.)

A. byte

B. long

C. char

D. float

E. Short

F. Long

Answer: A, C

Explanation: Switch statements are based on integer expressions and since both bytes and chars can implicitly be widened to an integer, these can also be used. Also shorts can be used. Short and Long are wrapper classes and reference types can not be used as variables.

Source code file:

48 of 256

Page 49: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

39. Given: 11. int x = 3; 12. int y = 1; 13. if (x = y) { 14. System.out.println("x =" + x); 15. }

What is the result?

A. x = 1

B. x = 3

C. Compilation fails.

D. The code runs with no output

E. An exception is thrown at runtime.

Answer: C

Explanation: Line 13 uses an assignment as opposed to comparison. Because of this, the if statement receives an integer value instead of a boolean. And so the compilation fails.

Source code file:

49 of 256

Page 50: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

40. Click the Exhibit button. 01. public class SwitchTest { 02. public static void main(String[] args) { 03. System.out.println("value =" + switchIt(4)); 04. } 05. public static int switchIt(int x) { 06. int j = 1; 07. switch (x) { 08. case l: j++; 09. case 2: j++; 10. case 3: j++; 11. case 4: j++; 12. case 5: j++; 13. default: j++; 14. } 15. return j + x; 16. } 17. }

What is the result?

A. value = 3

B. value = 4

C. value = 5

D. value = 6

E. value = 7

F. value = 8

Answer: F

Explanation: Because there are no break statements, once the desired result is found, the program continues though each of the remaining options.

Source code file:

50 of 256

Page 51: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

41. Click the Exhibit button. 01. public class Test { 02. public static void main(String args[]) { 03. int i = 1, j = 0; 04. switch(i) { 05. case 2: j += 6; 06. case 4: j += 1; 07. default: j += 2; 08. case 0: j += 4; 09. } 10. System.out.println("j = " + j); 11. } 12. }

What is the result?

A. 0

B. 2

C. 4

D. 6

E. 9

F. 13

Answer: D

Explanation: Because there are no break statements, the program gets to the default case and adds 2 to j, then goes to case 0 and adds 4 to the new j. The result is j = 6.

Source code file:

51 of 256

Page 52: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

42. Given: 11. Float f = new Float("12"); 12. switch (f) { 13. case 12: System.out.println("Twelve"); 14. case 0: System.out.println("Zero"); 15. default: System.out.println("Default"); 16. }

What is the result?

A. Zero

B. Twelve

C. Default

D. Twelve Zero Default

E. Compilation fails.

Answer: E

Explanation: The switch statement can only be supported by integers or variables more "narrow" than an integer i.e. byte, char, short. Here a Float wrapper object is used and so the compilation fails.

Source code file:

52 of 256

Page 53: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

43. Given: 11. for(int i = 0; i < 3; i++) { 12. switch(i) { 13. case 0: break; 14. case 1: System.out.print("one "); 15. case 2: System.out.print("two "); 16. case 3: System.out.print("three "); 17. } 18. } 19. System.out.println("done");

What is the result?

A. done

B. one two done

C. one two three done

D. one two three two three done

E. Compilation fails

Answer: D

Explanation: The variable i will have the values 0, 1 and 2. When i is 0, nothing will be printed because of the break in case 0. When i is 1, “one two three ” will be output because case 1, case 2 and case 3 will be executed (they don’t have break statements). When i is 2, “two three ” will be output because case 2 and case 3 will be executed (again no break statements). Finally, when the for loop finishes “done” will be output.

Source code file: Q43.java

53 of 256

Page 54: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

44. Click the Exhibit button. 11. public void foo( boolean a, boolean b){ 12. if( a ) { 13. System.out.println("A"); 14. } else if(a && b) { 15. System.out.println( "A&&B"); 16. } else { 17. if ( !b ) { 18. System.out.println( "notB") ; 19. } else { 20. System.out.println( "ELSE" ) ; 21. } 22. } 23. }

Which is correct?

A. If a is true and b is true then the output is "A&&B"

B. If a is true and b is false then the output is "notB"

C. If a is false and b is true then the output is "ELSE"

D. If a is false and b is false then the output is "ELSE"

Answer: C

Explanation: A is wrong. The output is “A”. When a is true, irrespective of the value of b, only the line 13 output will be executed. The condition at line 14 will never be evaluated (when a is true it will always be trapped by the line 12 condition) therefore the output will never be “A&&B”. B is wrong. The output is “A”. When a is true, irrespective of the value of b, only the line 13 output will be executed. C is correct. The output is "ELSE". Only when a is false do the output lines after 16 get some chance of executing. D is wrong. The output is “notB”.

Source code file: Q44.java.

54 of 256

Page 55: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

45. Given: 11. public void test(int x) { 12. int odd = x % 2; 13. if(odd) { 14. System.out.println("odd"); 15. } else { 16. System.out.println("even"); 17. } 18. }

Which statement is true?

A. Compilation fails.

B. "odd" will always be output.

C. "even" will always be output

D. "odd" will be output for odd values of x, and "even" for even values.

E. "even" will be output for odd values of x, and "odd" for even values.

Answer: A

Explanation: The compiler will complain because of incompatible types (line 13), the if expects a boolean but it gets an integer. Don’t be mislead by this question, it has nothing to do with modulus (remainder operator).

Source code file: Q45.java.

55 of 256

Page 56: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

46. Given: 11. boolean bool = true; 12. if(bool = false) { 13. System.out.println("a"); 14. } else if(bool) { 15. System.out.println("b"); 16. } else if(!bool) { 17. System.out.println("c"); 18. } else { 19. System.out.println("d"); 20. }

What is the result?

A. a

B. b

C. c

D. d

E. Compilation fails.

Answer: C

Explanation: Whoever devised this question pulled a bit of a cunning stunt. Look closely at line 12, is this an equality check (==) or an assignment (=). The condition at line 12 evaluates to false and also assigns false to bool. bool is now false so the condition at line 14 is not true. The condition at line 16 checks to see if bool is not true ( if !(bool == true) ), it isn’t so line 17 is executed.

Source code file: Q46.java.

56 of 256

Page 57: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

47. Given: 11. int i = l, j = -1; 12. switch (i) { 13. case 0, 1: j = 1; 14. case 2: j = 2; 15. default: j = 0; 16. } 17. System.out.println("j = " + j);

What is the result?

A. j = -1

B. j = 0

C. j = 1

D. j = 2

E. Compilation fails.

Answer: E

Explanation: The case statement takes only a single argument. The case statement on line 13 is given two arguments so the compiler complains.

Source code file: Q47.java.

57 of 256

Page 58: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

48. Given: 11. int i = O; 12. while(1) { 13. if(i == 4) { 14. break; 15. } 16. ++i; 17. } 18. System.out.println("i = " + i);

What is the result?

A. i = 0

B. i = 3

C. i = 4

D. i = 5

E. Compilation fails.

Answer: E

Explanation: Compilation fails because the argument of the while loop, the condition, must be of primitive type boolean. In Java, 1 does not represent the true state of a boolean, rather it is seen as an integer. A to D cannot be correct as the loop condition breaks down. Read the Notes On Unlabeled Statements after Q48.

Source code file:

58 of 256

Page 59: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Notes On Unlabeled Statements Both the break statement and the continue statement can be unlabeled or labeled. Although it’s far more common to use break and continue unlabeled, the exam expects you to know how labeled break and continue work. A break statement (unlabeled) will exit out of the innermost looping construct and proceed with the next line of code beyond the loop block. The following example demonstrates a break statement: boolean problem = true; while (true) { if (problem) { System.out.println("There was a problem"); break; } } //next line of code In the previous example, the break statement is unlabeled. The following is another example of an unlabeled continue statement: while (!EOF) { //read a field from a file if (there was a problem) { //move to the next field in the file continue; } } In this example, there is a file being read from one field at a time. When an error is encountered, the program moves to the next field in the file and uses the continue statement to go back into the loop (if it is not at the end of the file) and keeps reading the various fields. If the break command were used instead, the code would stop reading the file once the error occurred and move on to the next line of code. The continue statement gives you a way to say, “This particular iteration of the loop needs to stop, but not the whole loop itself. I just don’t want the rest of the code in this iteration to finish, so do the iteration expression and then start over with the test, and don’t worry about what was below the continue statement.”

59 of 256

Page 60: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

49. Given: 11. int i = 1, j = 10; 12. do { 13. if(i > j) { 14. break; 15. } 16. j--; 17. } while (++i < 5); 18. System.out.println("i = " + i + " and j = " + j);

What is the result?

A. i = 6 and j = 5

B. i = 5 and j = 5

C. i = 6 and j = 4

D. i = 5 and j = 6

E. i = 6 and j = 6

Answer: D

Explanation: This loop is a do-while loop, which always executes the code block within the block at least once, due to the testing condition being at the end of the loop, rather than at the beginning. This particular loop is exited prematurely if i becomes greater than j. The order is, test i against j, if bigger, it breaks from the loop, decrements j by one, and then tests the loop condition, where a pre-incremented by one i is tested for being lower than 5. The test is at the end of the loop, so i can reach the value of 5 before it fails. So it goes, start: 1, 10 2, 9 3, 8 4, 7 5, 6 loop condition fails. Read the Notes On Unlabeled Statements after Q48.

Source code file:

60 of 256

Page 61: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

50. Given: 11. int i = 1, j = 10; 12. do { 13. if(i > j) { 14. continue; 15. } 16. j--; 17. } while (++i < 6); 18. System.out.println("i = " + i + " and j = " + j);

What is the result?

A. i = 6 and j = 5

B. i = 5 and j = 5

C. i = 6 and j = 4

D. i = 5 and j = 6

E. i = 6 and j = 6

Answer: A

Explanation: This is similar to the last question. j is decremented by one within the loop, i is incremented by one in the test condition for the do-while loop. The if condition within the loop is never accessed, since the only time i is greater than j arises in the loop test condition when i is incremented to six, breaking the condition. So the continue isn’t actually called. Once again the variables follow: 1,10 2, 9 3, 8 4, 7 5, 6 6, 5 break loop Read the Notes On Unlabeled Statements after Q48.

Source code file: Q50.java.

61 of 256

Page 62: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

51. Given: 11. int i = l, j = 10; 12. do { 13. if(i++ > --j) { 14. continue; 15. } 16. } while (i < 5); 17. System.out.println("i = " + i + " and j = " + j);

What is the result?

A. i = 6 and j = 5

B. i = 5 and j = 5

C. i = 6 and j = 4

D. i = 5 and j = 6

E. i = 6 and j = 6

Answer: D

Explanation: D is correct. Again, it’s a do-while loop, the continue does not get called into play. The pattern is 1,10 2, 9 3, 8 4, 7 5, 6 do-while condition fails, line is printed with current i, j values. Read the Notes On Unlabeled Statements after Q48.

Source code file:

62 of 256

Page 63: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

52. Given: 11. int x = l, y = 6; 12. while (y--) { 13. x++; 14. } 15. System.out.println("x = " + x +" y = " + y);

What is the result?

A. x = 6 y = 0

B. x = 7 y = 0

C. x = 6 y = -1

D. x = 7 y = -1

E. Compilation fails.

Answer: E

Explanation: Compilation fails because the while loop demands a boolean argument for it’s looping condition, but in the code, it’s given an int argument. while(true){//insert code here}

Source code file:

63 of 256

Page 64: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

53. Given: 11. int i = 0, j = 5; 12. tp: for (;;) { 13. i++; 14. for (;;) { 15. if(i > --j) { 16. break tp; 17. } 18. } 19. System.out.println("i =" + i + ", j = " + j);

What is the result?

A. i = 1, j = 0

B. i = 1, j = 4

C. i = 3, j = 4

D. i = 3, j = 0

E. Compilation fails.

Answer: E

Explanation: If you examine the code carefully you will notice a missing curly bracket, this would cause the code to fail. For more information see the Notes on Labelled Statements after Q53a.

Source code file: Q53.java

64 of 256

Page 65: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

53a. Given: 11. int i = 0, j = 5; 12. tp: for (;;) { 13. i++; 14. for (;;) { 15. if(i > --j) { 16. break tp; 17. } 18. } 19. } 20. System.out.println("i =" + i + ", j = " + j);

What is the result?

A. i = 1, j = 0

B. i = 1, j = 4

C. i = 3, j = 4

D. i = 3, j = 0

E. Compilation fails.

Answer: A

Explanation: This is the same question as Q53 but I have inserted line 19 with a closing curly bracket. This code contains two nested infinite loops. The outer loop executes only once and sets the value of i to 1 (line 13). The second loop then starts and compares i with a decrementing j. The sequence of comparisons (line 15) goes like: i j 1 4 1 3 1 2 1 1 1 0 At this point the break to tp on line 16 is executed, causing the labelled loop (the outer one) to be exited and program execution to continue at line 20. For more information see the Notes on Labelled Statements after Q53a.

Source code file: Q53a.java

65 of 256

Page 66: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Notes on Labelled Statements You need to understand the difference between labeled and unlabeled break and continue. The labeled varieties are needed only in situations where you have a nested loop, and need to indicate which of the nested loops you want to break from, or from which of the nested loops you want to continue with the next iteration. A break statement will exit out of the labeled loop, as opposed to the innermost loop, if the break keyword is combined with a label. An example of what a label looks like is in the following code: foo: for (int x = 3; x < 20; x++) { while(y > 7) { y--; } } The label must adhere to the rules for a valid variable name and should adhere to the Java naming convention. The syntax for the use of a label name in conjunction with a break statement is the break keyword, then the label name, followed by a semicolon. A more complete example of the use of a labeled break statement is as follows: outer: for(int i = 0; i < 10; i++) { while (y > 7) { System.out.println("Hello"); break outer; } // end of inner loop System.out.println("Outer loop."); // Won't print } // end of outer for loop System.out.println("Good-Bye"); Running this code produces: Hello Good-Bye In this example the word Hello will be printed one time. Then, the labeled break statement will be executed, and the flow will exit out of the loop labeled outer. The next line of code will then print out Good-Bye. Let’s see what will happen if the continue statement is used instead of the break statement. The following code example is the same as the preceding one, with the exception of substituting continue for break: outer: for (int i = 0; i < 10; i++) { for (int j = 0; j < 5; j++) { System.out.println("Hello"); continue outer; } // end of inner loop System.out.println("outer"); // Never prints } System.out.println("Good-Bye"); Running this code produces: Hello Hello … … Hello Good-Bye In this example, Hello will be printed ten times. After the continue statement is executed, the flow continues with the next iteration of the loop identified with the label. Finally, when the condition in the outer loop evaluates to false, the i loop will finish and Good-Bye will be printed.

66 of 256

Page 67: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

53b. Given: 11. int i = 0, j = 5; 12. tp: for (;;) { 13. i++; 14. for (;;) { 15. if(i > --j) { 16. break tp; 17. } 18. } 19. System.out.println("i =" + i + ", j = " + j); 20. }

What is the result?

A. i = 1, j = 0

B. i = 1, j = 4

C. i = 3, j = 4

D. i = 3, j = 0

E. Compilation fails.

Answer: E

Explanation: This is the same question as Q53 (see also Q53a) but I have inserted line 20 with a closing curly bracket. Compilation will fail on this code, because the line: System.out.println("i =" + i + "j = " + j); cannot be called. The compiler returns unreachable statement error. When the loop breaks, it returns to the label, which is before the original for loop. The program goes to the loop, increments and decrements the variables, until breaking condition is met, then exits the loop to the first executable statement after line 20 (the end of the labelled block). For more information see the Notes on Labelled Statements after Q53a.

Source code file: Q53b.java

67 of 256

Page 68: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

54. Given: 11. for (int i = 0; i < 4; i += 2) { 12. System.out.print(i + “ “); 13. } 14. System.out.println(i);

What is the result?

A. 0 2 4

B. 0 2 4 5

C. 0 1 2 3 4

D. Compilation fails.

E. An exception is thrown at runtime.

Answer: D

Explanation: Compilation fails on the line 14 - System.out.println(i); as the variable i has only been declared within the for loop. It is not a recognised variable outside the code block of loop.

Source code file: Q54.java.

See also: Q195

68 of 256

Page 69: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

55. Given: 10. int i = 0; 11. for (; i < 4; i += 2) { 12. System.out.print(i + “ “); 13. } 14. System.out.println(i);

What is the result?

A. 0 2 4

B. 0 2 4 5

C. 0 1 2 3 4

D. Compilation fails.

E. An exception is thrown at runtime.

Answer: A

Explanation: As the variable i was declared outside the loop it can be referenced at any point after its declaration, both inside and outside the for loop.

Source code file: Q55.java.

69 of 256

Page 70: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

56. Click the Exhibit button. 01. public class Alpha1 { 02. public static void main( String[] args ) { 03. boolean flag; int i = 0; 04. do { 05. flag = false; 06. System.out.println( i++ ); 07. flag = i < 10; 08. continue; 09. } while ( (flag)? true:false); 10. } 11. }

What is the result?

A. 000000000

B. 0123456789

C. Compilation fails

D. The code runs with no output

E. The code enters an infinite loop

F. An exception is thrown at runtime

Answer: B

Explanation: A “do..while” loop will always run at least once, however while flag is set to true the loop will continue to run. On each loop flag is set to true if i is less than 10. Once i is 10 or greater, flag will be set to false and the loop will stop. A continue statement may occur only in a while, do, or for statement; statements of these three kinds are called iteration statements. Control passes to the loop-continuation point of an iteration statement. A continue statement with no label attempts to transfer control to the innermost enclosing while, do, or for statement of the immediately enclosing method or initializer block; this statement, which is called the continue target, then immediately ends the current iteration and begins a new one. In the code above the loop-continuation point is located at line 9. This leads to the conclusion that there is no need for the continue statement at line 8. If lines of code were inserted between lines 8 and 9 then the compiler would complain about unreachable code. For more information on the continue statement see Notes On Unlabeled Statements after Q48.

Source code file: Q56.java Q56a.java

70 of 256

Page 71: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

57. Given: 01. public class Delta { 02. static boolean foo(char c) { 03. System.out.print(c); 04. return true; 05. } 06. public static void main( String[] argv ) { 07. int i = 0; 08. for (foo('A'); foo('B')&&(i < 2); foo('C')) { 09. i++; 10. foo('D'); 11. } 12. } 13. }

What is the result?

A. ABDCBDCB

B. ABCDABCD

C. Compilation fails.

D. An exception is thrown at runtime.

Answer: A

Explanation: ‘A’ is only printed once at the very start as it is in the initialisation section of the for loop. The loop will only initialise that once. ‘B’ is printed as it is part of the test carried out in order to run the loop. ‘D’ is printed as it is in the loop. ‘C’ is printed as it is in the increment section of the loop and will ‘increment’ only at the end of each loop. Here ends the first loop. Again ‘B’ is printed as part of the loop test. ‘D’ is printed as it is in the loop. ‘C’ is printed as it ‘increments’ at the end of each loop. Again ‘B’ is printed as part of the loop test. At this point the test fails because the other part of the test (i<2) is no longer true. i has been increased in value by 1 for each loop with the line: i++; This results in a printout of ABDCBDCB Loops have three parts, initialisation, condition and increment. Always know when and how often these pieces of code are executed.

Source code file: Q57.java.

71 of 256

Page 72: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

58. Given: 11. for( int i = min; i < max; i++) { 12. System.out.println(i); 13. }

If min and max are arbitrary integers, what gives the same result?

A. int i = min; while(i < max) { System.out.println(i++); }

B. int i = min; do { System.out.println(i++); } while( i < max) ;

C. for (int i = min; i < max; System.out.println(++i));

D. for (int i = min; i++ < max; System.out.println(i));

Answer: A

Explanation: A is the only answer that will give the same output as the original code in every situation. B will always run at least once, so in a situation where min is greater than or equal to max the output from B will differ from the original code. C & D will always display a value of i 1 greater than: the Original Code or A or B where min is less than max. This is because C & D increment i before printing it, whereas the Original Code & A & B increment i after it is printed. The following table gives some test values and their outcome.

Same output as the code in the question?

min max A B C D

0 9 Yes Yes No No

0 1 Yes Yes No No

1 1 Yes No Yes Yes

1 0 Yes No Yes Yes

9 0 Yes No Yes Yes

Source code file: Q58.java

72 of 256

Page 73: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

59. Click the Exhibit button. 01. public class Test { 02. public static String output = ""; 03. 04. public static void foo(int i) { 05. try { 06. if(i == 1) { 07. throw new Exception(); 08. } 09. output += "1"; 10. } 11. catch(Exception e) { 12. output += "2"; 13. return; 14. } 15. finally { 16. output += "3"; 17. } 18. output += "4"; 19. } 20. 21. public static void main(String args[]) { 22. foo(0); 23. foo(1); 24. System.out.println(output); 25. } 26. }

What is the value of the variable output at line 24?

Answer:

Answer:13423

Explanation: The output at line 24 is 13423. This is because when the line foo(0) is run foo will test if the input is 1. If the test fails, the if statement is not executed and the line output +=”1” is run. This will add 1 to the string. A finally statement is executed after a try statement so the line output +=”3” is run. This brings the string to “13”. The last line of foo is now run and adds 4 to the string, making it “134”. foo exits and main continues to execute. Now the line foo(1) is run. The input character is tested to see if it is 1. The test passes and an exception is thrown. The try statement stops executing at that point and the line output+=”1” is skipped over. The catch statement contains the line output+=”2” so the value of the output string is now “1342”. The catch statement also contains the line: return; . This should end the execution of foo but because it happens in a try..catch..finally block, the finally statement must be executed before foo ends. This results in the addition of 3 to the string. The value of the string is now “13423” and the program ends. In the original question line 24 was blank and the question was “What is the value of the variable output at line 23?”.

Source code file: Q59.java.

73 of 256

Page 74: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

60. Given: 01. public class Foo { 02. public static void main(String[] args) { 03. try { 04. return; 05. } finally { 06. System.out.println( "Finally" ); 07. } 08. } 09. }

What is the result?

A. Finally

B. Compilation fails.

C. The code runs with no output.

D. An exception is thrown at runtime.

Answer: A

Explanation: If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances: An exception arising in the finally block itself The death of the thread The use of System.exit() Turning off the power to the CPU I suppose the last three could be classified as VM shutdown.

Source code file: Q60.java.

74 of 256

Page 75: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

61. Given: 01. public class ExceptionTest { 02. class TestException extends Exception {} 03. public void runTest() throws TestException {} 04. public void test() /* Point X */ { 05. runTest(); 06. } 07. }

At Point X on line 4, which code is necessary to make the code compile?

A. No code is necessary.

B. throws Exception

C. catch ( Exception e )

D. throws RuntimeException

E. catch ( TestException e )

Answer: B

Explanation: A is wrong. If you compile the code as given the compiler will complain: ”unreported exception … must be caught or declared to be thrown” The class extends Exception so we are forced to test for exceptions. B is correct. This works because it DOES throw an exception if an error occurs C is wrong. The catch statement belongs in a method body not a method specification. D is wrong. TestException is a subclass of Exception therefore the test method, in this example, must throw TestException or some other class further up the Exception tree. Throwing RuntimeException is just not on as this belongs in the java.lang.RuntimeException branch (it is not a superclass of TestException). The compiler complains with the same error as in A above. E is wrong. The catch statement belongs in a method body not a method specification.

Source code file: Q61a.java Q61b.java Q61c.java Q61d.java Q61e.java

75 of 256

Page 76: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

62. Which statement is true?

A. catch(X x) can catch subclasses of X.

B. The Error class is a RuntimeException.

C. Any statement that can throw an Error must be enclosed in a try block.

D. Any statement that can throw an Exception must be enclosed in a try block.

E. Any statement that can throw a RuntimeException must be enclosed in a try block.

Answer: A

Explanation: A is correct. If the class specified in the catch clause does have subclasses, any exception object that subclasses the specified class will be caught as well. B is wrong. The error class is a subclass of Throwable and not Runtime Exception. (See image.) C is wrong. You do not catch this class of error. D is wrong. An exception can be thrown to the next method higher up the call stack. E is wrong. You do not catch this class of error.

Source code file:

76 of 256

Page 77: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

63. Which four can be thrown using the throw statement? (Choose four.)

A. Error

B. Event

C. Object

D. Throwable

E. Exception

F. RuntimeException

Answer: ADEF

Explanation: These are the only four that can be thrown. An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch The Throwable class is the superclass of all errors and exceptions in the Java language. The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch (checked exceptions) RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. Also look at the image in the Q62 explanation.

Source code file:

77 of 256

Page 78: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

64. Given: 11. try { 12. int x = 0; 13. int y = 5 / x; 14. } catch (Exception e) { 15. System.out.println("Exception"); 16. } catch (ArithmeticException ae) { 17. System.out.println(" Arithmetic Exception"); 18. } 19. System.out.println("finished");

What is the result?

A. finished

B. Exception

C. Compilation fails.

D. Arithmetic Exception

Answer: C

Explanation: Compilation fails because Arithmetic Exception has already been caught. Arithmetic Exception is a subclass of java.lang.Exception, by time the ArithmeticException has been specified it has already been caught by the Exception class. If ArithmeticException appears before Exception, then the file will compile. When catching exceptions the more specific exceptions must be listed before the more general (the subclasses must be caught before the superclasses).

Source code file: Q64.java

See also: Q189

78 of 256

Page 79: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

65. Click the Exhibit button. 01. public class Test { 02. public static void aMethod() throws Exception { 03. try { 04. throw new Exception(); 05. } finally { 06. System.out.println("finally"); 07. } 08. } 09. public static void main(String args[]) { 10. try { 11. aMethod(); 12. } catch (Exception e) { 13. System.out.println("exception"); 14. } 15. System.out.println("finished"); 16. } 17. }

What is the result?

A. finally

B. exception finished

C. finally exception finished

D. Compilation fails

Answer: C

Explanation: This is what happens: (1) The execution of the try block (line 03) completes abruptly because of the throw statement (line 04). (2) The exception cannot be assigned to the parameter of any catch clause of the try statement therefore the finally block is executed (line 05) and “finally” is output (line 06). (3) The finally block completes normally, and then the try statement completes abruptly because of the throw statement (line 04). (4) The exception is propagated up the call stack and is caught by the catch in the main method (line 12). This prints “exception”. (5) Lastly program execution continues, because the exception has been caught, and “finished” is output (line 15).

Source code file: Q65.java

79 of 256

Page 80: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

66. Click the Exhibit button. 01. public class X { 02. public static void main(String [] args) { 03. try { 04. badMethod(); 05. System.out.print("A"); 06. } 07. catch (Exception ex) { 08. System.out.print("B"); 09. } 10. finally { 11. System.out.print("C"); 12. } 13. System.out.print("D"); 14. } 15. public static void badMethod() { 16. throw new RuntimeException(); 17. } 18. }

What is the result?

A. AB

B. BC

C. ABC

D. BCD

E. Compilation fails.

Answer: D

Explanation: (1) A RuntimeException is thrown (see image Q62), this is a subclass of exception. (2) The exception causes the try to complete abruptly (line 04) therefore line 05 is never executed. (3) The exception is caught (line 07) and “B” is output (line 08) (4) The finally block (line 10) is always executed (keeping in mind the exceptions listed in the explanation to Q60) and “C” is output (line 11). (5) The exception was caught, so the program continues with line 13 and outputs “D”.

Source code file: Q66.java

80 of 256

Page 81: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

67. Click the Exhibit button. 01. public class X { 02. public static void main(String [] args) { 03. try { 04. badMethod(); 05. System.out.print("A"); 06. } 07. catch (Exception ex) { 08. System.out.print("B"); 09. } 10. finally { 11. System.out.print("C"); 12. } 13. System.out.print("D"); 14. } 15. public static void badMethod() { 16. throw new Error(); 17. } 18. }

What is the result?

A. ABCD

B. Compilation fails.

C. C is printed before exiting with an error message.

D. BC is printed before exiting with an error message.

E. BCD is printed before exiting with an error message.

Answer: C

Explanation: Error is thrown but not recognised line(16) because the only catch attempts to catch an Exception and Exception is not a superclass of Error. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java.lang.Error).

Source code file: Q67.java

81 of 256

Page 82: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

68. Click the Exhibit button. 01. public class X { 02. public static void main(String [] args) { 03. try { 04. badMethod(); 05. System.out.print("A"); 06. } 07. catch (Exception ex) { 08. System.out.print("B"); 09. } 10. finally { 11. System.out.print("C"); 12. } 13. System.out.print("D"); 14. } 15. public static void badMethod() {} 16. }

What is the result?

A. AC

B. BC

C. ACD

D. ABCD

E. Compilation fails

Answer: C

Explanation: There is no exception thrown, so all the code with the exception of the catch statement block is run.

Source code file: Q68.java

82 of 256

Page 83: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

69. Click the Exhibit button. 01. public class X { 02. public static void main(String [] args) { 03. try { 04. badMethod(); 05. System.out.print("A"); 06. } 07. catch (RuntimeException ex) { 08. System.out.print("B"); 09. } 10. catch (Exception ex1) { 11. System.out.print("C"); 12. } 13. finally { 14. System.out.print("D"); 15. } 16. System.out.print("E"); 17. } 18. public static void badMethod() { 19. throw new RuntimeException(); 20. } 21. }

What is the result?

A. BD

B. BCD

C. BDE

D. BCDE

E. ABCDE

F. Compilation fails.

Answer: C

Explanation: A Run time exception is thrown and caught in the catch statement on line 07. All the code after the finally statement is run because the exception has been caught.

Source code file:

83 of 256

Page 84: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

70. Which statement is true?

A. A try statement must have at least one corresponding catch block.

B. Multiple catch statements can catch the same class of exception more than once.

C. An Error that might be thrown in a method must be declared as thrown by that method, or be handled within that method.

D. Except in case of VM shutdown, if a try block starts to execute, a corresponding finally block will always start to execute.

E. Except in case of VM shutdown, if a try block starts to execute, a corresponding finally block must always run to completion.

Answer: D

Explanation: A is wrong. A try statement can exist without catch, but it must have a finally statement. B is wrong. A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause. If that catch block completes normally, then the try statement completes normally. C is wrong. Exceptions of type Error and RuntimeException do not have to be caught, only checked exceptions (java.lang.Exception) have to be caught (see image for Q60). However, speaking of Exceptions, Exceptions do not have to be handled in the same method as the throw statement. They can be passed to another method. D is correct. If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances: An exception arising in the finally block itself The death of the thread The use of System.exit() Turning off the power to the CPU I suppose the last three could be classified as VM shutdown. E is wrong. If the finally block completes abruptly for any reason then the try statement completes abruptly for the same reason (if an exception had already been thrown then this original exception is discarded).

Source code file:

84 of 256

Page 85: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

71. Given: 01. class Exc0 extends Exception { } 02. class Exc1 extends Exc0 { } 03. public class Test { 04. public static void main(String args[]) { 05. try { 06. throw new Exc1(); 07. } catch (Exc0 e0) { 08. System.out.println("Ex0 caught"); 09. } catch (Exception e) { 10. System.out.println("exception caught"); 11. } 12. } 13. }

What is the result?

A. Ex0 caught

B. exception caught

C. Compilation fails because of an error at line 2.

D. Compilation fails because of an error at line 6.

Answer: A

Explanation: An exception Exc1 is thrown and is caught by the catch statement on line 07. The code is executed in this block. There is no finally block of code to execute.

Source code file:

85 of 256

Page 86: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

72. Given: 20. public float getSalary(Employee e) { 21. assert validEmployee(e); 22. float sal = lookupSaIary(e); 23. assert (sal>0); 24. return sal; 25. } 26. private int getAge(Employee e) { 27. assert validEmployee( e); 28. int age = lookupAge(e); 29. assert (age>0); 30. return age; 31. }

Which line is a violation of appropriate use of the assertion mechanism?

A. line 21

B. line 23

C. line 27

D. line 29

Answer: A

Explanation: A is the correct answer. It is a violation of the appropriate use of the assertion mechanism. You do not use the assertion mechanism to validate the arguments of a public method. By convention, pre-conditions on public methods are enforced by explicit checks that throw particular, specified exceptions. For example: /** * Sets the refresh rate. * * @param rate refresh rate, in frames per second. * @throws IllegalArgumentException if rate <= 0 or * rate > MAX_REFRESH_RATE. */ public void setRefreshRate(int rate) { // Enforce specified precondition in public method if (rate <= 0 || rate > MAX_REFRESH_RATE) throw new IllegalArgumentException("Illegal rate: " + rate); setRefreshInterval(1000/rate); } This convention is unaffected by the addition of the assert construct. Do not use assertions to check the primitive parameters of a public method. An assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError. B is wrong. It is not a violation of the appropriate use of the assertion mechanism. It is OK to assert the post-conditions of a method no matter whether it is a public or a private method. C is wrong. It is not a violation of the appropriate use of the assertion mechanism. It is OK to assert the pre-conditions of a private method.

86 of 256

Page 87: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

D is wrong. Line 29 does not violate the appropriate use of the assertion mechanism. You can use an assertion to test a nonpublic method's pre/postcondition that you believe will be true no matter what a client does with the class. For example, an assertion is appropriate in the following "helper method" that is invoked by the previous method (see explanation B above): /** * Sets the refresh interval * (which must correspond to a legal frame rate). * * @param interval refresh interval in milliseconds. */ private void setRefreshInterval(int interval) { // Confirm adherence to precondition in nonpublic method assert interval > 0 && interval <= 1000/MAX_REFRESH_RATE : interval; ... // Set the refresh interval } Note, the above assertion will fail if MAX_REFRESH_RATE is greater than 1000 and the client selects a refresh rate greater than 1000. This would, in fact, indicate a bug in the library!

Source code file:

Exam Objective/s: 2.4 and 2.5

87 of 256

Page 88: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Notes on Assertions Assertions work quite simply. You always assert that something is true. If it is, no problem. Code keeps running. But if your assertion turns out to be wrong (false), then a stop-the-world AssertionError is thrown (that you should never, ever handle!) right then and there, so you can fix whatever logic flaw led to the problem. Assertions come in two flavors: simple and really simple, as follows: Really Simple private void doStuff() { assert (y > x); // more code assuming y is greater than x } Simple private void doStuff() { assert (y > x): "y is " + y " " x is " + x; // more code assuming y is greater than x } The difference between them is that the simple version adds a second expression, separated from the first (boolean expression) by a colon, that adds a little more information to the stack trace. Both versions throw an immediate AssertionError, but the simple version gives you a little more debugging help while the really simple version simply tells you that your assumption was false. Assertions are typically enabled when an application is being tested and debugged, but disabled when the application is deployed. The assertions are still in the code, although ignored by the JVM, so if you do have a deployed application that starts misbehaving, you can always choose to enable assertions in the field for additional testing.

88 of 256

Page 89: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

73. Which fragment is an example of inappropriate use of assertions?

A. assert (!(map.contains(x))); map.add(x);

B. if(x>0) { } else { assert (x == 0); }

C. public void aMethod(int x) { assert (x > 0); }

D. assert(invariantCondition()); return retval;

E. switch (x) { case 1: break; case 2: break; default: assert (x == 0); }

Answer: C

Explanation: Assert shouldn’t be used for preconditions within public methods. Also see the explanation for Q72.

Source code file:

Exam Objective/s: 2.4 and 2.5

89 of 256

Page 90: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

74. Given: 01. public class Test { 02. public static void main(String[] args) { 03. int x = 0; 04. assert (x > 0) : "assertion failed"; 05. System.out.println("finished"); 06. } 07. }

What is the result?

A. finished

B. Compilation fails.

C. An AssertionError is thrown.

D. An AssertionError is thrown and finished is output

Answer: C

Explanation: An assertion Error is thrown as normal giving the output “assertion failed”. The word “finished” is not printed (ensure you run with the –ea option) Assertion failures are generally labeled in the stack trace with the file and line number from which they were thrown, and also in this case with the error’s detail message “assertion failed”. The detail message is supplied by the assert statement in line 04.

Source code file:

Exam Objective/s: 2.4 and 2.5

90 of 256

Page 91: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

75. Given: 01. public class Test { 02. public static void main(String[] args) { 03. int x = 0; 04. assert (x > 0) ? "assertion failed" : "assertion passed" ; 05. System.out.println("finished"); 06. } 07. }

What is the result?

A. finished

B. Compiliation fails.

C. An AssertionError is thrown and finished is output.

D. An AssertionError is thrown with the message "assertion failed."

E. An AssertionError is thrown with the message "assertion passed."

Answer: B

Explanation: Compilation Fails. You can’t use the Assert statement in a similar way to the ternary operator. Don’t confuse.

Source code file:

Exam Objective/s: 2.4 and 2.5

91 of 256

Page 92: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

76. Which three statements are true? (Choose three.)

A. Assertion checking is typically enabled when a program is deployed.

B. It is never appropriate to write code to handle failure of an assert statement.

C. Assertion checking is typically enabled during program development and testing.

D. Assertion checking can be selectively enabled or disabled on a per-package basis, but not on a per-class basis.

E. Assertion checking can be selectively enabled or disabled on both a per-package basis and a per-class basis.

Answer: BCE

Explanation: A is wrong. It’s just not true. B is correct. You’re never supposed to handle an assertion failure. C is correct. Assertions let you test your assumptions during development, but the assertion code—in effect—evaporates when the program is deployed, leaving behind no overhead or debugging code to track down and remove. D is wrong. See the explanation for E below. E is correct. Assertion checking can be selectively enabled or disabled on a per-package basis. Note that the package default assertion status determines the assertion status for classes initialized in the future that belong to the named package or any of its "subpackages". The assertion status can be set for a named top-level class and any nested classes contained therein. This setting takes precedence over the class loader's default assertion status, and over any applicable per-package default. If the named class is not a top-level class, the change of status will have no effect on the actual assertion status of any class. See Example of methods used to set assertion status on both a per-class basis, and per package basis j2sdk1.4.0\docs\guide\lang\assert.html Section “Enabling and Disabling Assertions“

Source code file:

Exam Objective/s: 2.4 and 2.5

92 of 256

Page 93: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

77. Which statement is true about assertions in the Java programming language?

A. Assertion expressions should not contain side effects.

B. Assertion expression values can be any primitive type.

C. Assertions should be used for enforcing preconditions on public methods.

D. An AssertionError thrown as a result of a failed assertion should always be handled by the enclosing method.

Answer: A

Explanation: A is correct. Because assertions may be disabled, programs must not assume that the boolean expressions contained in assertions will be evaluated. Thus these expressions should be free of side effects. That is, evaluating such an expression should not affect any state that is visible after the evaluation is complete. Although it is not illegal for a boolean expression contained in an assertion to have a side effect, it is generally inappropriate, as it could cause program behaviour to vary depending on whether assertions are enabled or disabled. Assertion checking may be disabled for increased performance. Typically, assertion checking is enabled during program development and testing and disabled for deployment. B is wrong. Because you assert that something is “true”. True is Boolean. So, an expression must evaluate to Boolean, not int or byte or anything else. Use the same rules for an assertion expression that you would use for a while condition. C is wrong. Usually, enforcing a precondition on a public method is done by condition-checking code that you write yourself, to give you specific exceptions. Also see the explanation for question 72. j2sdk1.4.0\docs\guide\lang\assert.html : See “Preconditions, Postconditions, and Class Invariants” D is wrong. “You’re never supposed to handle an assertion failure” Not all legal uses of assertions are considered appropriate. As with so much of Java, you can abuse the intended use for assertions, despite the best efforts of Sun’s Java engineers to discourage you. For example, you’re never supposed to handle an assertion failure. That means don’t catch it with a catch clause and attempt to recover. Legally, however, AssertionError is a subclass of Throwable, so it can be caught. But just don’t do it! If you’re going to try to recover from something, it should be an exception. To discourage you from trying to substitute an assertion for an exception, the AssertionError doesn’t provide access to the object that generated it. All you get is the String message.

Source code file:

Exam Objective/s: 2.4 and 2.5

93 of 256

Page 94: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

78. Which statement is true?

A. Assertions can be enabled or disabled on a class-by-class basis.

B. Conditional compilation is used to allow tested classes to run at full speed.

C. Assertions are appropriate for checking the validity of arguments in a method.

D. The programmer can choose to execute a return statement or to throw an exception if an assertion fails.

Answer: A

Explanation: A is correct. The assertion status can be set for a named top-level class and any nested classes contained therein. This setting takes precedence over the class loader's default assertion status, and over any applicable per-package default. If the named class is not a top-level class, the change of status will have no effect on the actual assertion status of any class. Also see the explanation for Q76. B is wrong. Is there such a thing as conditional compilation in Java? C is wrong. For private methods - yes. But do not use assertions to check the parameters of a public method. An assert is inappropriate in public methods because the method guarantees that it will always enforce the argument checks. A public method must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError. D is wrong. Because you’re never supposed to handle an assertion failure. That means don’t catch it with a catch clause and attempt to recover.

Source code file:

Exam Objective/s: 2.4 and 2.5

94 of 256

Page 95: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

79. Given: 1. public class Test79{ 2. public static void main( String[] argv){ 3. // insert statement here 4. } 5. }

Which statement, inserted at line 3, produces the following output? Exception in thread "main" java.lang.AssertionError: true at Test79.main(Test.java:3)

A. assert true;

B. assert false;

C. assert false: true;

D. assert false == true;

E. assert false: false;

Answer: C

Explanation: An assertion will raise an exception if its condition returns false. In the answers given above A returns true while B, C, D and E all return false. My conclusion is that the question must be rephrased to: Which statement, inserted at line 3 does not raise an exception? Answer: A A Compiles and runs without exception B. Compiles but fails at runtime with the exception: Exception in thread "main" java.lang.AssertionError: true at Test79.main(Test79.java:3) C Compiles but fails at runtime with the exception: Exception in thread "main" java.lang.AssertionError: true at Test79.main(Test79.java:3) D Compiles but fails at runtime with the exception: Exception in thread "main" java.lang.AssertionError at Test79.main(Test79.java:3) E Compiles but fails at runtime with the exception: Exception in thread "main" java.lang.AssertionError: false at Test79.main(Test79.java:3)

Source code file: Test79.java Compile with: javac -source 1.4 Test79.java Run with: java -ea Test79

Exam Objective/s: 2.4 and 2.5

95 of 256

Page 96: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

80. Given: 11. public class Test { 12. public void foo() { 13. assert false; 14. assert false; 15. } 16. public void bar(){ 17. while(true){ 18. assert false; 19. } 20. assert false; 21. } 22. }

What causes compilation to fail?

A. Line 13

B. Line 14

C. Line 18

D. Line 20

Answer: D

Explanation: D is correct. Compilation fails because of an unreachable statement at line 20. It is a compile-time error if a statement cannot be executed because it is unreachable. The question is now, why is line 20 unreachable? If it is because of the assert then surely line 14 would also be unreachable. The answer must be something other than assert. Examine the following: A while statement can complete normally if and only if at least one of the following is true: - The while statement is reachable and the condition expression is not a constant expression with value true. -There is a reachable break statement that exits the while statement. The while statement at line 17 is infinite and there is no break statement therefore line 20 is unreachable. You can test this with the following code: public class Test80 { public void foo() { assert false; assert false; } public void bar(){ while(true){ assert false; break; } assert false; } }

Source code file: Test80.java Compile with: javac -source 1.4 Test80.java

Exam Objective/s: 2.4 and 2.5

96 of 256

Page 97: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

General Notes On Garbage Collection: The heap is that part of memory where Java objects live, and it’s the one and only part of memory that is in any way involved in the garbage collection process. So, all of garbage collection revolves around making sure that the heap has as much free space as possible. This boils down to deleting any objects that are eligible for garbage collection. An object is eligible for garbage collection when no live thread can access it – in other words when an object on the heap is no longer reachable by the Java program running. In other, other words, if an object can be accessed from a live thread, it can’t be garbage collected. About the only thing you can guarantee is that if you are running very low on memory, the garbage collector will run before the JVM throws an OutOfMemoryException. Some points about the finalize() method that you need to remember:

For any given object, finalize() will be called only once by the garbage collector. Calling finalize() can actually result in saving an object from deletion (for more

information, research memory leaks). The following program lets you see the effects of garbage collection. It lets us know how much total memory the JVM has available to it and how much free memory it has. It then creates 10,000 Date objects. After this, it tells you how much memory is left and then calls the garbage collector (which, if it decides to run, should halt the program until all unused objects are removed). The final free memory result should indicate whether it has run.

01. import java.util.Date; 02. public class CheckGC { 03. public static void main(String [] args) { 04. Runtime rt = Runtime.getRuntime(); 05. System.out.println("Total JVM memory: " + rt.totalMemory()); 06. System.out.println("Before Memory = " + rt.freeMemory()); 07. Date d = null; 08. for(int i = 0;i<10000;i++) { 09. d = new Date(); 10. d = null; 11. } 12. System.out.println("After Memory = " + rt.freeMemory()); 13. rt.gc(); // an alternate to System.gc() 14. System.out.println("After GC Memory = " + rt.freeMemory()); 15. } 16. }

Islands of Isolation

There is a way in which objects can become eligible for garbage collection, even if they still have valid references! We think of this scenario as islands of isolation. A simple example is a class that has an instance variable that is a reference variable to another instance of the same class. Now imagine that two such instances exist and that they refer to each other. If all other references to these two objects are removed, then even though each object still has a valid reference, there will be no way for any live thread to access either object. When the garbage collector runs, it will discover any such islands of objects and will remove them. As you can imagine, such islands can become quite large, theoretically containing hundreds of objects. Examine the following code:

01. public class Island { 02. Island i; 03. public static void main(String [] args) { 04. Island i2 = new Island(); 05. Island i3 = new Island(); 06. Island i4 = new Island();

97 of 256

Page 98: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

07. i2.i = i3; // i2 refers to i3 08. i3.i = i4; // i3 refers to i4 09. i4.i = i2; // i4 refers to i2 10. i2 = null; 11. i3 = null; 12. i4 = null; 13. // do complicated, memory intensive stuff 14. } 15. }

When the code reaches // do complicated, the three Island objects (previously known as i2, i3, and i4) have instance variables so that they refer to each other, but their links to the outside world (i2, i3, and i4) have been nulled. These three objects are eligible for garbage collection because no live thread can access them even though they references.

Study the following figure to reinforce the concepts of objects without references and islands of isolation.

98 of 256

Page 99: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

81. What allows the programmer to destroy an object x?

A. x.delete()

B. x.finalize()

C. Runtime.getRuntime().gc()

D. explicitly setting the object's reference to null

E. ensuring there are no references to the object

F. Only the garbage collection system can destroy an object.

Answer: F

Explanation: A is wrong. I found 4 delete() methods in all of the Java class structure. They are: (1) delete() - Method in class java.io.File Deletes the file or directory denoted by this abstract pathname. (2) delete(int, int) - Method in class java.lang.StringBuffer Removes the characters in a substring of this StringBuffer. (3) delete(int, int) - Method in interface javax.accessibility.AccessibleEditableText Deletes the text between two indices (4) delete(int, int) - Method in class javax.swing.text.JTextComponent.AccessibleJTextComponent Deletes the text between two indices None of these destroy the object to which they belong. B is wrong. I found 19 finalize() methods. The most interesting, from this question’s point of view, was the finalize() method in class java.lang.Object which is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. This method does not destroy the object to which it belongs. C is wrong. But it is interesting. The Runtime class has many methods, two of which are:

getRuntime() - Returns the runtime object associated with the current Java application gc() - Runs the garbage collector. Calling this method suggests that the Java virtual

machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects. Interesting as this is, it doesn’t destroy the object. D is wrong. Setting the object’s reference to null does just that. It doesn’t set the object to null. Also there might be other references to the object hanging around. E is wrong. If there are no references to an object your program cannot access the object, but the object might still exist on the heap. F is correct. When an object is no longer referenced, it may be reclaimed by the garbage collector. If an object declares a finalizer, the finalizer is executed before the object is reclaimed to give the object a last chance to clean up resources that would not otherwise be released. When a class is no longer needed, it may be unloaded.

Source code file:

Exam Objective/s:

99 of 256

Page 100: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

82. Which statement is true?

A. Memory is reclaimed by calling Runtime.gc().

B. Objects are not collected if they are accessible from live threads.

C. Objects that have finalize() methods are never garbage collected.

D. Objects that have finalize() methods always have their finalize() methods called before the program ends.

E. An OutOfMemory error is only thrown if a single block of memory cannot be found that is large enough for a particular requirement.

Answer: B

Explanation: A is wrong. Runtime.gc() asks the garbage collector to run, but the garbage collector never makes any guarantees about when it will run or what unreachable objects it will free from memory. B is correct. If an object can be accessed from a live thread, it can’t be garbage collected. C is wrong. The finalize() method is called by the garbage collector when the garbage collector sees that the object cannot be referenced. Java provides this mechanism for you so that you can run some code just before your object is deleted by the garbage collector. This is a good idea because it enables you to close any resources opened by your object before your object is deleted. However, any code that you put into your class’s overridden finalize() method is not guaranteed to run. The finalize() method for any given object might run, but you can’t count on it, so don’t put any essential code into your finalize() method. There is another caveat, it is possible, through poor programming of the finalize() method to cause an object to never be garbage collected (for more information, research memory leaks). This last point is not of concern to us here in this question. D is wrong. If this were the case then the garbage collector would actively hang onto objects until a program finishes – this goes against the purpose of the garbage collector. E is wrong. The garbage collector runs immediately the system is out of memory before an OutOfMemoryException is thrown by the JVM.

Source code file:

Exam Objective/s:

100 of 256

Page 101: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

83. Which statement is true?

A. Programs will not run out of memory.

B. Objects that will never again be used are eligible for garbage collection.

C. Objects that are referred to by other objects will never be garbage collected.

D. Objects that can be reached from a live thread will never be garbage collected.

E. Objects are garbage collected immediately after the system recognizes they are eligible.

Answer: D

Explanation: A is wrong. Even though Java applications can run out of memory there another answer supplied that is more right. B is wrong. “Never again be used” does not mean that there are no more references to the object. C is wrong. See the note above on Islands of Isolation (An object is eligible for garbage collection when no live thread can access it - even though there might be references to it). D is correct. E is wrong. The garbage collector guarantees nothing.

Source code file:

Exam Objective/s:

101 of 256

Page 102: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

84. Click the Exhibit button. 01. class TestA { 02. TestB b; 03. TestA() { 04. b = new TestB(this); 05. } 06. } 07. class TestB { 08. TestA a; 09. TestB(TestA a) { 10. this.a = a; 11. } 12. } 13. class TestAll { 14. public static void main (String args[]) { 15. new TestAll().makeThings(); 16. // ...code continues on 17. } 18. void makeThings() { 19. TestA test = new TestA(); 20. } 21. }

Which two statements are true after line 15, before main completes? (Choose two.)

A. Line 15 causes a stack overflow.

B. An exception is thrown at runtime.

C. The object referenced by a is eligible for garbage collection.

D. The object referenced by b is eligible for garbage collection.

E. The object referenced by a is not eligible for garbage collection.

F. The object referenced by b is not eligible for garbage collection.

Answer: CD

Explanation: This is not as tricky as it seems. In the exam you will need to absorb the code quickly. After looking at the code ask yourself some questions:

Q. Is recursion a factor? - A. No. Q. Is there anything in the code that could throw an exception? - A. No. Q. After line 15, does a reference exist for TestA. - Yes. This is held in TestB. Q. After line 15, does a reference exist for TestB. - Yes. This is held in TestA. Q. After line 15, can a live thread access TestA. - No - can be garbage collected. Q. After line 15, can a live thread access TestB. - No - can be garbage collected.

This question tests your knowledge of “islands of isolation”. For more information see General Notes On Garbage Collection above. A is wrong. There is nothing recursive about any of this code. Program compiles ok and runs to completion without exception. B. is wrong. Program compiles ok and runs to completion without exception. C. is correct. Because the object referenced by a cannot be accessed by a live thread. D. is correct. Because the object referenced by b cannot be accessed by a live thread.

102 of 256

Page 103: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

E is wrong. Because the object referenced by a cannot be accessed by a live thread even though a reference to that object exists. F is wrong. Because the object referenced by b cannot be accessed by a live thread even though a reference to that object exists.

Source code file: Test84.java

Exam Objective/s:

103 of 256

Page 104: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

85. Click the Exhibit button. 01. class A { 02. } 03. class Alpha { 04. private A myA = new A(); 05. 06. void doIt(A a) { 07. a = null; 08. } 09. void tryIt() { 10. doIt(myA); 11. } 12. }

Which two statements are correct? (Choose two.)

A. There are no instances of A that will become eligible for garbage collection.

B. Explicitly setting myA to null marks that instance to be eligible for garbage collection.

C. Any call on tryIt() causes the private instance of A to be marked for garbage collection.

D. Private instances of A become eligible for garbage collection when instances of Alpha become eligible for garbage collection.

Answer: B, D

Explanation: A is wrong. Instances of A will eventually become eligible for garbage collection. B is correct. I tested this by experimenting. C is wrong. This is wrong. The method tryIt() does not have direct access to the private instance of A, it has only access to a copy of the reference to A. Now setting a copy to null is not the same as setting the original to null (remember that all variables, primitive and reference are passed by value and not by reference). D is correct. I tested this by experimenting. When Alpha is garbage collected there is then no thread of execution that can access A.

Source code file: Alpha85.java.

Exam Objective/s:

104 of 256

Page 105: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

86. Given: 10. public Object m() { 11. Object o = new Float(3.14F); 12. Object [] oa = new Object[l]; 13. oa[0] = o; 14. o = null; 15. oa[0] = null; 16. return o; 17. }

When is the Float object, created in line 11, eligible for garbage collection?

A. just after line 13

B. just after line 14

C. just after line 15

D. just after line 16 (that is, as the method returns)

Answer: C

Explanation: A is wrong. This simply copies the object reference into the array. B is wrong. The reference o is set to null, but, oa[0] still maintains the reference to the Float object. C is correct. The thread of execution will then not have access to the object. D is wrong. Because of C.

Source code file:

Exam Objective/s:

105 of 256

Page 106: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

87. Given: 10. public Object m() { 11. Object o = new Float(3.14F); 12. Object [] oa = new Object[l]; 13. oa[0] = o; 14. o = null; 15. return oa[0]; 16. }

When is the Float object, created in line 11, eligible for garbage collection?

A. just after line 13

B. just after line 14

C. never in this method

D. just after line 15 (that is, as the method returns)

Answer: C

Explanation: C is correct. Because the reference to the object is returned and possibly maintained in code outside this method - as long as there is any reference to the object in the code it cannot be collected. C is the answer and it precludes all other answers

Source code file:

Exam Objective/s:

106 of 256

Page 107: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

88. Given: 12. void start() { 13. A a = new A(); 14. B b = new B(); 15. a.s(b); 16. b = null; 17. a = null; 18. System.out.println("start completed"); 19. }

When is the B object, created in line 14, eligible for garbage collection?

A. after line 16

B. after line 17

C. after line 18 (when the method ends)

D. There is no way to be absolutely certain.

E. The object is NOT eligible for garbage collection.

Answer: D

Explanation: D is correct. I think there are too many unknowns about the method s and the classes A and B to be able to answer this question with any certainty. Examine the code in Q88.java for a possible implementation of the method s and the classes A and B.

Source code file: Q88.java (the code is shown on the next page for your reference.)

Exam Objective/s:

107 of 256

Page 108: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

01. class Q88 { 02. 03. public static void main(String[] args) { 04. Q88 testQ88 = new Q88(); 05. testQ88.start(); 06. System.gc(); 07. System.out.println("Program Finished. Goodbye."); 08. } 09. 10. void start() { 11. A a = new A(); 12. B b = new B(); 13. a.s(b); 14. b = null; System.gc(); 15. a = null; System.gc(); 16. System.out.println("start completed"); 17. } 18. } // end of class Q88 19. 20. class A { 21. 22. public void s (B b) { 23. System.out.println("Just Entered Method s of Class A"); 24. b.start(); //start the thread 25. System.out.println("Exiting Method s of Class A"); 26. } 27. 28. protected void finalize() { 29. System.out.println("Finalizing Class A"); 30. } 31. 32. } // end of class A 33. 34. class B extends Thread { 35. 36. public void run() { 37. System.out.println("Class B Thread: Started"); 38. for (int i = 0; i < 10000; i++) { 39. if ( i % 1000 == 0 ) { 40. System.out.println("Class B Thread: Running: " + i); 41. } 42. } 43. System.out.println("Class B Thread: Ending"); 44. System.gc(); 45. } 46. 47. protected void finalize() { 48. System.out.println("Finalizing Class B"); 49. } 50. 51. } // end of class B

108 of 256

Page 109: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

89. Given: 01. class Test { 02. private Demo d; 03. void start() { 04. d = new Demo(); 05. this.takeDemo(d); 06. } 07. 08. void takeDemo(Demo demo) { 09. demo = null; 10. demo = new Demo(); 11. } 12. }

When is the Demo object, created on line 4, eligible for garbage collection?

A. After line 5

B. After line 9

C. After the start() method completes

D. When the takeDemo() method completes

E. When the instance running this code is made eligible for garbage collection

Answer: E

Explanation: A is wrong. The variable d is a member of the Test class and is never directly set to null. B is wrong. A copy of the variable d is set to null and not the actual variable d. C is wrong. The variable d exists outside the start() method (it is a class member). So, when the start() method finishes the variable d still holds a reference. D is wrong. The variable d exists outside the takeDemo() method (it is a class member). The method takeDemo() operates only on a copy of the variable d and not the actual variable. E is correct. By a process of elimination.

Source code file:

Exam Objective/s:

109 of 256

Page 110: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

90. Given: 01. class Bar { } 01. class Test { 02. Bar doBar() { 03. Bar b = new Bar(); 04. return b; 05. } 06. public static void main (String args[]) { 07. Test t = new Test(); 08. Bar newBar = t.doBar(); 09. System.out.println("newBar"); 10. newBar = new Bar(); 11. System.out.println("finishing"); 12. } 13. }

At what point is the Bar object, created on line 3, eligible for garbage collection?

A. after line 8

B. after line 10

C. after line 4, when doBar() completes

D. after line 11, when main() completes

Answer: B

Explanation: A is wrong. This actually protects the object from garbage collection. B is correct. All references to the Bar object created on line 3 are destroyed when a new reference to a new Bar object is assigned to the variable newBar on line 10. Therefore the Bar object, created on line 3, is eligible for garbage collection after line 10. C is wrong. Because the reference in the doBar() method is returned on line 4 and is stored in newBar on line 8. This preserver the object created on line 3. D is wrong. Not applicable because the object is eligible for garbage collection after line 10.

Source code file: Test90.java

Exam Objective/s:

110 of 256

Page 111: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

90a. Given the following code 01. class HappyGarbage01 { 02. public static void main(String args[]) { 03. HappyGarbage01 h = new HappyGarbage01(); 04. h.methodA(); 05. } 06. Object methodA() { 07. Object obj1 = new Object(); 08. Object [] obj2 = new Object[1]; 09. obj2[0] = obj1; 10. obj1 = null; 11. return obj2[0]; 12. } 13. }

Where will be the most chance of the garbage collector being invoked?

A. After line 9

B. After line 10

C. After line 11

D. Garbage collector never invoked in methodA()

E. Compilation error

Answer: D

Explanation: A is wrong. Because the reference to obj1 is stored in obj2[0]. The Object obj1 still exists on the heap and can be accessed by an active thread through the reference stored in obj2[0]. B is wrong. Because it is only one of the references to the object obj1, the other reference is maintained in obj2[0]. C is wrong. The garbage collector will not be called here because a reference to the object is being maintained and returned in obj2[0]. D is correct. Garbage collection takes place after the method has returned its reference to the object. The method returns to line 04, there is no reference to store the return value so in my opinion garbage collection takes place after line 04. E is wrong. The code compiles without error.

Source code file:

Exam Objective/s:

111 of 256

Page 112: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Modifiers

Study the following table. Using it you will be able to answer the next series of questions.

112 of 256

Page 113: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

91. Given: 01. public class F0091 { 02. public void main( String[] args ) { 03. System.out.println( "Hello" + args[0] ); 04. } 05. }

What is the result if this code is executed with the command line: java F0091 world

A. Hello

B. Hello Foo91

C. Hello world

D. Compilation fails.

E. The code does not run.

Answer: E

Explanation: A is wrong. For the reason stated in E below. B is wrong. For the reason stated in E below. C is wrong. For the reason stated in E below. If the error in E did not occur then the correct answer would be C. D is wrong. The code does not have any syntax errors that would cause an error at compilation. E is correct. A runtime error will occur owning to the main method of the code fragment not being declared static: Exception in thread "main" java.lang.NoSuchMethodError: main The Java Language Specification clearly states: "The main method must be declared public, static, and void. It must accept a single argument that is an array of strings."

Source code file:

Exam Objective/s:

113 of 256

Page 114: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

92. Click the Exhibit button. 01. package foo; 02. 03. import java.util.Vector; 04. 05. private class MyVector extends Vector { 06. int i = 1; 07. public MyVector() { 08. i = 2; 09. } 10. } 11. 12. public class MyNewVector extends MyVector { 13. public MyNewVector() { 14. i = 4; 15. } 16. public static void main(String args[]) { 17. MyVector v = new MyNewVector(); 18. } 19. }

What is the result?

A. Compilation succeeds.

B. Compilation fails because of an error at line 05.

C. Compilation fails because of an error at line 06.

D. Compilation fails because of an error at line 14.

E. Compilation fails because of an error at line 17.

Answer: B

Explanation: A is wrong. The compilation fails due to the reason outlined below. B is correct. The code fails here during compilation due to the private modifier. This means that its members can only be accessed from an instance of this class. In this code fragment the MyNewVector class will be unable to extend the class due to its private modifier.

C is wrong. This declaration is valid though it will not take place.

D is wrong. This declaration is valid in and of itself given that extension allows access to variables of the parent class.

E is wrong. This declaration is valid as its possible to make a reference to a parent object.

Source code file: MyNewVector.java

Exam Objective/s:

114 of 256

Page 115: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

93. Click the Exhibit button. 01. package foo; 02. 03. import java.util.Vector; 04. 05. protected class MyVector extends Vector{ 06. int i = 1; 07. public MyVector() { 08. i = 2; 09. } 10. } 11. 12. public class MyNewVector extends MyVector { 13. public MyNewVector() { 14. i = 4; 15. } 16. public static void main(String args[]) { 17. MyVector v = new MyNewVector(); 18. } 19. }

What is the result?

A. Compilation succeeds.

B. Compilation fails because of an error at line 05.

C. Compilation fails because of an error at line 06.

D. Compilation fails because of an error at line 14.

E. Compilation fails because of an error at line 17.

Answer: B

Explanation: A is wrong. Compilation succeeding is false due to error described in Answer B.

B is correct. The code fails at line 5 as a class may not be defined as protected. Only methods, variables and constructors may be declared protected. A class can only be Public, Default, Final or Abstract.

C is wrong. This declaration is valid in and of itself.

D is wrong. This declaration is valid as a subclass may access its superclasse’s members.

E is wrong. This declaration is valid as one can create a reference to a superclass object.

Source code file:

Exam Objective/s:

115 of 256

Page 116: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Notes on Interfaces Interfaces are contracts for what a class can do, but they say nothing about the way in which the class must do it.

• Interfaces can be implemented by any class, from any inheritance tree.

• An interface is like a 100-percent abstract class, and is implicitly abstract whether you type the abstract modifier in the declaration or not.

• An interface can have only abstract methods, no concrete methods allowed. The method prototypes in an interface are all abstract by virtue of their declaration, and should not be declared abstract.

• Member declarations in an interface disallow the use of some declaration modifiers; you cannot use transient, volatile, or synchronized in a member declaration in an interface. Also, you may not use the private and protected specifiers when declaring members of an interface.

• Interfaces are by default public and abstract—explicit declaration of these modifiers is optional.

• Interfaces can have constants, which are always implicitly public, static, and final.

• Interface constant declarations of public, static, and final are optional in any combination.

• A legal nonabstract implementing class has the following properties:

o It provides concrete implementations for all methods from the interface.

o It must follow all legal override rules for the methods it implements.

o It must not declare any new checked exceptions for an implementation method.

o It must not declare any checked exceptions that are broader than the exceptions declared in the interface method.

o It may declare runtime exceptions on any interface method implementation regardless of the interface declaration.

o It must maintain the exact signature and return type of the methods it implements (but does not have to declare the exceptions of the interface).

• A class implementing an interface can itself be abstract.

• An abstract implementing class does not have to implement the interface methods (but the first concrete subclass must).

• A class can extend only one class, but it can implement many.

• Interfaces can extend one or more other interfaces.

• Interfaces cannot extend a class, or implement a class or interface.

• When taking the exam, verify that interface and class declarations are legal before verifying other code logic.

116 of 256

Page 117: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

94. Given: 01. public interface Foo { 02. int k = 4; 03. }

Which three are equivalent to line 2? (Choose three.)

A. final int k = 4;

B. public int k = 4;

C. static int k = 4;

D. abstract int k = 4;

E. volatile int k = 4;

F. protected int k = 4;

Answer: ABC

Explanation: Interfaces can have constants, which are always implicitly public, static, and final. Interface constant declarations of public, static, and final are optional in any combination. A is correct. (See note above, and Notes on Interfaces before this question.)

B is correct. (See note above, and Notes on Interfaces before this question.)

C is correct. (See note above, and Notes on Interfaces before this question.)

D is wrong. The Abstract modifier can only be applied to classes and methods.

E is wrong. The volatile modifier is applied to variables that are to be modified simultaneously by other threads that may be running and from the note above we know that interfaces can have constants, which are always implicitly public, static, and final.

F is wrong. Because interfaces can have constants, which are always implicitly public, static, and final.

Source code file:

Exam Objective/s:

117 of 256

Page 118: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

95. Which two are valid declarations within an interface definition? (Choose two.)

A. void methoda();

B. public double methoda();

C. public final double methoda();

D. static void methoda(double d1);

E. protected void methoda(double d1);

Answer:AB

Explanation: A is correct. No access modifier implies that the method is both abstract and public which is acceptable. Interfaces are by default public and abstract—explicit declaration of these modifiers is optional.

B is correct. A public access modifier is acceptable. The method prototypes in an interface are all abstract by virtue of their declaration, and should not be declared abstract. C is wrong. The final modifier means that this method cannot be constructed in a subclass. A final method cannot be abstract.

D is wrong. Static is concerned with the class and not an instance.

E is wrong. Protected is not permitted when declaring a method of an interface. See information below. Member declarations in an interface disallow the use of some declaration modifiers; you cannot use transient, volatile, or synchronized in a member declaration in an interface. Also, you may not use the private and protected specifiers when declaring members of an interface.

(Source: JavaTutorial\java\interpack\createinterface.html)

Source code file:

Exam Objective/s:

118 of 256

Page 119: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Java’s Operators

Java’s operators are shown in the following table. They are listed in precedence order, with the highest precedence at the top of the table. Each group has been given a name for reference purposes. That name is shown in the left column of the table. Arithmetic and comparison operators are each split further into two sub groupings because they have different levels or precedence.

Category Operators

Unary ++ –– + – ! ~ ()

Arithmetic * / % + –

Shift << >> >>>

Comparison < <= > >= instanceof == !=

Bitwise & ^ |

Short-circuit && ||

Conditional (the only ternary operator) ?:

Assignment = “op=”

Evaluation Order

In Java, unlike many other languages, the apparent order of evaluation of operands in an expression is fixed. Specifically, all operands are evaluated left to right, even if the order of execution of the operations is something different. This is most noticeable in the case of assignments. Consider this code fragment:

1. int [] a == { 4, 4 }; 2. int b = 1; 3. a[b] == b = 0;

In this case, it might be unclear which element of the array is modified: What is the value of b used to select the array element, 0 or 1? An evaluation from left to right requires that the leftmost expression, a[b], be evaluated first, so it is a reference to the element a[1]. Next, b is evaluated, which is simply a reference to the variable called b. The constant expression 0 is evaluated next, which clearly does not involve any work. Now that the operands have been evaluated, the operations take place. This is done in the order specified by precedence and associativity. For assignments, associativity is right-to-left, so the value 0 is first assigned to the variable called b and then the value 0 is assigned into the last element of the array a.

119 of 256

Page 120: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Bitwise Operators

The bitwise operators take two individual bit numbers, then use AND/OR to determine the result on a bit-by-bit basis. There are three bitwise operators: & AND | inclusive OR ^ exclusive OR The & (AND) operator will set the resulting bit to 1 if both bits are 1. The | (OR) operator will set the resulting bit to 1 if either (of both) of the bits is a 1. The ^ (XOR) operator will set the resulting bit to 1 if both bits are different.

Examples:

10 & 9 10 & 5 10 | 9 10 | 5 10 ^ 9 10 ^ 5

1 0 1 0

1 0 0 1

& -------

1 0 0 0

1 0 1 0

0 1 0 1

& -------

0 0 0 0

1 0 1 0

1 0 0 1

| -------

1 0 1 1

1 0 1 0

0 1 0 1

| -------

1 1 1 1

1 0 1 0

1 0 0 1

^ -------

0 0 1 1

1 0 1 0

0 1 0 1

^ -------

1 1 1 1

8 decimal 0 decimal 11 decimal 15 decimal 3 decimal 15 decimal

Bitwise Complement Operator

The ~ operator is a flip-the-bits operator. It will change all 1s to 0s and vice versa. Look at the following code: class Bitwise { public static void main(String [] args) { int x = 5; System.out.println("x is initially " + x); x = ~x; System.out.println("~x is equal to " + x); } } This program is changing every bit into its complement; thus, the output from this program is the following: x is initially 5 ~x is equal to -6 In bit representation, the conversion looks like this, ~0000 0000 0000 0000 0000 0000 0000 0101 and converts to 1111 1111 1111 1111 1111 1111 1111 1010

120 of 256

Page 121: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

96. Given: 01. public class Test { 02. public static void leftshift(int i, int j) { 03. i<<=j; 04. } 05. public static void main(String args[]) { 06. int i = 4, j = 2; 07. leftshift(i, j); 08. System.out.printIn(i); 09. } 10. }

What is the result?

A. 2

B. 4

C. 8

D. 16

E. The code will not compile.

Answer: B

Explanation: Java only ever passes arguments to a method by value (i.e. a copy of the variable) and never by reference. Therefore the value of the variable i remains unchanged in the main method. If you are clever you will spot that 16 is 4 multiplied by 2 twice, (4 * 2 * 2) = 16. If you had 16 left shifted by three bits then 16 * 2 * 2 * 2 = 128. If you had 128 right shifted by 2 bits then 128 / 2 / 2 = 32. Keeping these points in mind, you don’t have to go converting to binary to do the left and right bit shifts.

Source code file: Test96.java

Exam Objective/s:

121 of 256

Page 122: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

96a. Given: 01. public class Test96a { 02. public static int leftshift(int i, int j) { 03. return i<<=j; 04. } 05. public static void main(String args[]) { 06. int i = 4, j = 2; 07. System.out.println(leftshift(i, j)); 08. } 09. }

What is the result?

A. 2

B. 4

C. 8

D. 16

E. The code will not compile.

Answer: D

Explanation: Examine line 3 i<<=j this is a shortcut form of i = i << j. So we must left shift i by j bits. In this case i has the value 4 and j has the value 2: 4<<=2. The binary for 4 is 100 shifting this left by 2 bits we get 10000 which is decimal 16 (4*2*2).

Source code file: Test96.java

Exam Objective/s:

122 of 256

Page 123: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

97. Which two are equivalent? (Choose Two)

A. 3/2

B. 3<2

C. 3*4

D. 3<<2

E. 3*2^2

F. 3<<<2

Answer: C, D

Explanation: A is wrong. 3/2=1 (integer arithmetic). B is wrong. 3<2=false. C is correct. 3*4=12. D is correct. 3<<2=12. In binary 3 is 11, now shift the bits two places to the left and we get 1100 which is 12 in binary (3*2*2). E is wrong. 3*2^2=4. The evaluation order for this expression is (3*2)^2 (see notes above on precedence order). So (3*2)^2 = 6^2. In binary this is 110^010. Now the ^ (XOR) operator will set the resulting bit to 1 if both bits are different. Therefore 110^010=100, or 4 in decimal. F is wrong. There is no unsigned left shift operator in Java.

Source code file: Test97.java

Exam Objective/s:

See also: Q199

123 of 256

Page 124: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

98. Which two values are equal?

A. 16<<2

B. 16/3*2

C. 16>>2

D. 16<<<2

E. 16>>>2

F. 16/2

Answer: C,E

Explanation: The answer can be derived in either of two ways. (1). The hard way, work everything out and do the bit shifting. (2). The easy way, look for the expressions that are functionally equivalent. Can you spot why C and E are functionally equivalent (if E was -16 >>> 2 would you get the same answer?). 16 decimal is 10000 binary. A is wrong. 16 << 2 = 64 (1000000 binary) B is wrong. 16 / 3 * 2 = 10. Integer arithmetic. C is correct. 16 >> 2 = 4 D is wrong. 16 <<< 2 There is no signed left shift operator in Java. E is correct. 16 >>> 2 = 4 F is wrong. 16 / 2 = 8

Source code file: BitShifter.java

Exam Objective/s:

124 of 256

Page 125: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

99. Which two are equivalent? (Choose Two)

A. 16>4

B. 16/2

C. 16*4

D. 16>>2

E. 16/2^2

F. 16>>>2

Answer: D, F

Explanation: Can you spot the expressions that are functionally equivalent? A is wrong. 16 > 4 = true B is wrong. 16 / 2 = 8 C is wrong. 16 * 4 = 64 D is correct. 16 >> 2 = 4 E is wrong. 16 /2 ^ 2 = 10 F is correct. 16 >>> 2 = 4

Source code file: BitShifter.java

Exam Objective/s:

125 of 256

Page 126: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Notes on Threads

Here are some of the key points on threads.

Creating, Instantiating, and Starting New Threads

Threads can be created by extending Thread and overriding the public void run() method.

Thread objects can also be created by calling the Thread constructor that takes a Runnable argument. The Runnable object is said to be the target of the thread.

You can call start() on a Thread object only once. If start() is called more than once on a Thread object, it will throw a RuntimeException.

It is legal to create many Thread objects using the same Runnable object as the target. When a Thread object is created, it does not become a thread of execution until its

start() method is invoked. When a Thread object exists but hasn’t been started, it is in the new state and is not considered alive.

Transitioning Between Thread States

Once a new thread is started, it will always enter the runnable state. The thread scheduler can move a thread back and forth between the runnable state

and the running state. Only one thread can be running at a time, although many threads may be in the

runnable state. There is no guarantee that the order in which threads were started determines the

order in which they’ll run. There’s no guarantee that threads will take turns in any fair way. It’s up to the thread

scheduler, as determined by the particular virtual machine implementation. If you want a guarantee that your threads will take turns regardless of the underlying JVM, you should can use the sleep() method. This prevents one thread from hogging the running process while another thread starves.

A running thread may enter a blocked/waiting state by a wait(), sleep(), or join() call. A running thread may enter a blocked/waiting state because it can’t acquire the lock for

a synchronized block of code. When the sleep or wait is over, or an object’s lock becomes available, the thread can

only re-enter the runnable state. It will go directly from waiting to running (well, for all practical purposes anyway).

A dead thread cannot be started again.

Sleep, Yield, and Join

Sleeping is used to delay execution for a period of time, and no locks are released when a thread goes to sleep.

A sleeping thread is guaranteed to sleep for at least the time specified in the argument to the sleep method (unless it’s interrupted), but there is no guarantee as to when the newly awakened thread will actually return to running.

The sleep() method is a static method that sleeps the currently executing thread. One thread cannot tell another thread to sleep.

The setPriority() method is used on Thread objects to give threads a priority of between 1 (low) and 10 (high), although priorities are not guaranteed, and not all JVMs use a priority range of 1-10.

If not explicitly set, a thread’s priority will be the same priority as the thread that created this thread (in other words, the thread executing the code that creates the new thread).

The yield() method may cause a running thread to back out if there are runnable threads of the same priority. There is no guarantee that this will happen, and there is no guarantee that when the thread backs out it will be different thread selected to run. A thread might yield and then immediately reenter the running state.

The closest thing to a guarantee is that at any given time, when a thread is running it will usually not have a lower priority than any thread in the runnable state. If a low-priority thread is running when a high-priority thread enters runnable, the JVM will preempt the

126 of 256

Page 127: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

running low-priority thread and put the high-priority thread in. When one thread calls the join() method of another thread, the currently running thread

will wait until the thread it joins with has completed. Think of the join() method as saying, “Hey thread, I want to join on to the end of you. Let me know when you’re done, so I can enter the runnable state.”

Concurrent Access Problems and Synchronized Threads

Synchronized methods prevent more than one thread from accessing an object’s critical method code.

You can use the synchronized keyword as a method modifier, or to start a synchronized block of code.

To synchronize a block of code (in other words, a scope smaller than the whole method), you must specify an argument that is the object whose lock you want to synchronize on.

While only one thread can be accessing synchronized code of a particular instance, multiple threads can still access the same object’s unsynchronized code.

When an object goes to sleep, it takes its locks with it. Static methods can be synchronized, using the lock from the java.lang.Class instance

representing that class.

Communicating with Objects by Waiting and Notifying

The wait() method lets a thread say, “there’s nothing for me to do here, so put me in your waiting pool and notify me when something happens that I care about.” Basically, a wait() call means “wait me in your pool,” or “add me to your waiting list.”

The notify() method is used to send a signal to one and only one of the threads that are waiting in that same object’s waiting pool.

The method notifyAll() works in the same way as notify(), only it sends the signal to all of the threads waiting on the object.

All three methods—wait()/notify()/notifyAll()—must be called from within a synchronized context! A thread invokes wait()/notify() on a particular object, and the thread must currently hold the lock on that object.

Deadlocked Threads

Deadlocking is when thread execution grinds to a halt because the code is waiting for locks to be removed from objects.

Deadlocking can occur when a locked object attempts to access another locked object that is trying to access the first locked object. In other words, both threads are waiting for each other’s locks to be released; therefore, the locks will never be released!

Deadlocking is bad. Don’t do it.

The ways a running thread could leave the running state:

A call to sleep() Guaranteed to cause the current thread to stop executing for at least the specified sleep duration (although it might be interrupted before its specified time).

A call to yield() Not guaranteed to do much of anything, although typically it will cause the currently running thread to move back to runnable so that a thread of the same priority can have a chance.

A call to join() Guaranteed to cause the current thread to stop executing until the thread it joins with (in other words, the thread it calls wait() on) completes. If the thread it’s trying to join with is not alive, however, the current thread won’t need to back out.

The thread’s run() method completes. Duh. A call to wait() on an object. A thread can’t acquire the lock on the object whose method code it’s attempting to run.

127 of 256

Page 128: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Important Thread Methods Summary

join() - waits for this thread to die. notify() - wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods. notifyAll() - wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods. resume() - Deprecated. This method exists solely for use with suspend(), which has been deprecated because it is deadlock-prone. Resumes a suspended thread. First, the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException (in the current thread). If the thread is alive but suspended, it is resumed and is permitted to make progress in its execution. run() - when the run() method returns, the thread has finished its task and is considered dead. There is no way out of this state. Once a thread is dead, it may not be started again; if you want the thread’s task to be performed again, you have to construct and start a new thread instance. The dead thread continues to exist; it is an object like any other object, and you can still access its data and call its methods. You can’t make it run again. setPriority() - changes the priority of this thread. Threads are assigned priorities that the thread scheduler can use to determine how the threads will be treated. The thread scheduler can use thread priorities to determine which thread gets to run. The thread scheduler usually decides to let the thread with the highest priority in the Ready-to-run state get CPU time. sleep() - Causes the currently executing thread to sleep (temporarily cease execution) for a specified number of milliseconds. The thread does not lose ownership of any monitors. stop() - Deprecated. Forces the thread to stop executing. This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait. suspend() - Deprecated. This method has been deprecated, as it is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes. First, the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException (in the current thread). If the thread is alive, it is suspended and makes no further progress unless and until it is resumed. wait() - causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. yield() - causes the currently executing thread object to temporarily pause and allow other threads to execute

128 of 256

Page 129: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

100. Which of the following will directly stop the execution of a Thread? (Choose two)

A. wait()

B. notify()

C. notifyall()

D. exits synchronized code

E. setPriority()

Answer: A, E

Explanation: A is correct. wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. B is wrong. notify() - wakes up a single thread that is waiting on this object's monitor. C is wrong. notifyAll() - wakes up all threads that are waiting on this object's monitor. D is wrong. Typically, releasing a lock means the thread holding the lock (in other words, the thread currently in the synchronized method) exits the synchronized method. At that point, the lock is free until some other thread enters a synchronized method on that object. Does entering/exiting synchronized code mean that the thread execution stops? Not necessarily because the thread can still run code that is not synchronized. I think the word directly in the question gives us a clue. Exiting synchronized code does not directly stop the execution of a thread. E is correct. setPriority() changes the priority of this thread. Does changing a threads priority mean that the thread execution stops? If you lower a thread’s priority so that there is another thread with a higher priority you get something close to a guarantee that at any given time, when a thread is running it will usually not have a lower priority than any thread in the runnable state. If a low-priority thread is running when a high-priority thread enters runnable, the JVM will preempt the running low-priority thread and put the high-priority thread in. This scenario would directly stop the execution of a thread.

Source code file:

Exam Objective/s:

129 of 256

Page 130: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

101. Which of the following will not directly cause a thread to stop? (Select two).

A. notify()

B. wait()

C. exits synchronized code

D. setPriority()

E. InputStream access

F. sleep()

Answer: A, C

Explanation: A is correct. notify() - wakes up a single thread that is waiting on this object's monitor. B is wrong. wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. C is correct. Typically, releasing a lock means the thread holding the lock (in other words, the thread currently in the synchronized method) exits the synchronized method. Exiting synchronized code does not directly stop the execution of a thread. (Also see the explanation for Q104.) D is wrong. Changing a thread’s priority can cause a thread to stop running. (Also see the explanation for Q104.) E is wrong. Methods of the InputStream class block until input data is available, the end of the stream is detected, or an exception is thrown. Blocking means that a thread may stop until certain conditions are met. F is wrong. sleep() - Causes the currently executing thread to sleep (temporarily cease execution) for a specified number of milliseconds. The thread does not lose ownership of any monitors.

Source code file:

Exam Objective/s:

130 of 256

Page 131: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

102. Which two methods may not directly cause a thread to stop executing? (Select two).

A. sleep();

B. stop();

C. yield();

D. wait();

E. notify();

F. notifyAll();

G. synchronized();

Answer: E, F

Explanation: A is wrong. sleep() - Causes the currently executing thread to sleep (temporarily cease execution) for a specified number of milliseconds. The thread does not lose ownership of any monitors. B is wrong. stop() is deprecated. It forces the thread to stop executing and is inherently unsafe. (Also see the notes above on Important Thread Methods Summary) C is wrong. This is a very polite method, it causes the currently executing thread object to temporarily pause and allow other threads to execute. D is wrong. wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. E is correct. notify() - wakes up a single thread that is waiting on this object's monitor. F is correct. notifyAll() - wakes up all threads that are waiting on this object's monitor. G is wrong. synchronized() is used to synchronize a block of code (preventing more than one thread from accessing the critical block of code), you must specify an argument that is the object whose lock you want to synchronize on.

Source code file:

Exam Objective/s:

131 of 256

Page 132: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

103. Which method registers a thread in a thread scheduler?

A. run();

B. construct();

C. start();

D. register();

E. schedule();

Answer: C

Explanation: A is wrong. The run() method of a thread is like the main() method to an application. Starting the thread causes the object's run method to be called in that separately executing thread. B is wrong. There is no construct() method in the Thread class. C is correct. The start() method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. D is wrong. There is no register() method in the Thread class. E is wrong. There is no schedule() method in the Thread class.

Source code file:

Exam Objective/s:

132 of 256

Page 133: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

104. What is the name of the method used to start a thread execution?

A. init();

B. start();

C. run();

D. resume();

E. execute();

F. build();

Answer: B

Explanation: A is wrong. There is no init() method in the Thread class. B is Correct. The start() method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. C is wrong. The run() method of a thread is like the main() method to an application. Starting the thread causes the object's run method to be called in that separately executing thread. D is wrong. The resume() method is deprecated. It resumes a suspended thread. E is wrong. There is no execute() method in the Thread class. F is wrong. There is no build() method in the Thread class.

Source code file:

Exam Objective/s:

133 of 256

Page 134: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

105. Which will contain the body of the thread?

A. run();

B. start();

C. stop();

D. main();

E. init();

Answer: A

Explanation: A is Correct. The run() method to a thread is like the main() method to an application. Starting the thread causes the object's run method to be called in that separately executing thread. B is wrong. The start() method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. C is wrong. The stop() method is deprecated. It forces the thread to stop executing. D is wrong. Is the main entry point for an application. E is wrong. There is no init() method in the Thread class.

Source code file:

Exam Objective/s:

134 of 256

Page 135: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

106. Under which conditions will a currently executing thread stop?

A. When an interrupted exception occurs.

B. When a thread of higher priority is ready (becomes runnable).

C. When the thread creates a new thread.

D. When the stop() method is called.

Answer: B, D

Explanation: See the notes above on The ways a running thread could leave the running state. A is wrong. B is correct. C is wrong. D is correct.

Source code file:

Exam Objective/s:

135 of 256

Page 136: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

107. Which of the following statements are true?

A. All the threads created in a class will come to an end at the same time.

B. You can stop a thread indefinitely if you wish to.

C. You can start a thread only by extending the Thread class.

D. Multiple threads accessing the same variable will lead to producing unpredictable values in the variable.

E. JVM exits after the main() thread is exited even if there might be some threads running.

Answer: B, D

Explanation: See the notes above on The ways a running thread could leave the running state. A is wrong. Just not true. B is correct. Checkout the following: sleep(), yield(), join(), the thread’s run() method completes, wait() and a thread can’t acquire the lock on the object whose method code it’s attempting to run. C is wrong. You can also implement the runnable interface. D is correct. You cannot predict in which order the threads will update the variable or which thread will be first/last. E is wrong. All threads (not just main) must be finished before the JVM exits.

Source code file:

Exam Objective/s:

136 of 256

Page 137: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

108. Examine the following code: 01. class s extends Thread { 02. int j = 0; 03. public void run() { 04. try{ Thread.sleep(5000); } 05. catch(Exception e) { } 06. j = 100; 07. } 08. 09. public static void main(String args[]) { 10. s t1 = new s(); 11. t1.start(); 12. System.out.println(t1.j); 13. } 14. }

What do you have to do to ensure that 'j' will print 100

A. You have to make t1 a Daemon Thread

B. You have to join t1 to main

C. You have to suspend main() when the thread starts and resume it after the value of 'j' is set to 100

D. You have to interrupt the main thread

Answer: B

Explanation: You can use the join() method to coordinate your activities with another thread by waiting for the other thread to complete its task. Calling a thread’s join() method causes the caller to block until the target thread dies. Alternatively you can poll the thread by calling join() with a number of milliseconds to wait. This is a very course form of synchronization. Using wait() and notify() would be a much more general and powerful mechanism for coordinating the activities of threads. The following code has been amended to use the join() method. Lines 12 thru 14 are the addition lines of code.

01. class s extends Thread { 02. int j = 0; 03. public void run() { 04. try { Thread.sleep(5000); } 05. catch(Exception e) { } 06. j=100; 07. } 08. 09. public static void main(String args[]) { 10. s t1 = new s(); 11. t1.start(); 12. try { 13. t1.join(); // wait for thread to die 14. } catch (InterruptedException e) { } 15. System.out.println(t1.j); 16. } 17. }

Source code file:

Exam Objective/s:

137 of 256

Page 138: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

109. What do you have to do to ensure that j will have the value 10 at line 16. 01. class A implements Runnable { 02. int i; 03. public void run () { 04. try { 05. Thread.sleep(5000); 06. i = 10; 07. } catch(InterruptedException e) { } 08. } 09. } 10. public class Test108 { 11. public static void main (String args[]) { 12. try { 13. A a = new A(); 14. Thread t = new Thread(a); 15. t.start(); 16. int j = a.i; 17. } catch (Exception e) { } 18. } 19. }

A. You have to make t a Daemon Thread

B. You have to join t to main

C. Suspend main() when the thread starts and resume it after the value of 'j' is set to 10

D. You have to interrupt the main thread

Answer: B

Explanation: You can use the join() method to coordinate your activities with another thread by waiting for the other thread to complete its task. Calling a thread’s join() method causes the caller to block until the target thread dies. Alternatively you can poll the thread by calling join() with a number of milliseconds to wait. Using wait() and notify() would be a much more powerful means of coordinating the activities of threads. The following code incorporates the join() method. The new code is highlighted:

class A implements Runnable { int i; public void run () { try { Thread.sleep(5000); i = 10; } catch(InterruptedException e) { } } } public class Test108 { public static void main (String args[]) { try { A a = new A(); Thread t = new Thread(a); t.start(); try { t.join(); // wait for thread to die } catch (InterruptedException e) { } int j = a.i; } catch (Exception e) { } } }

Source code file:

Exam Objective/s:

138 of 256

Page 139: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

110. What happens when you compile/run this code? 01. public class Q1 implements Runnable 02. { 03. public void run(String s) 04. { 05. System.out.println("Before start of Thread: " + s); 06. System.out.println("After stop of Thread: " + s); 07. } 08. 09. public static void main(String[] args) 10. { 11. Q1 a = new Q1(); 12. Thread t = new Thread(a); 13. t.start(); 14. } 15. }

A. Compilation error at line 1

B. Runtime exception at line 13

C. Compilation error at line 14

D. Prints "Before start of Thread After Start of Thread”

E. None of the above

Answer: A

Explanation: The compiler complains with the error: Q1.java:1: Q1 should be declared abstract; it does not define run() in Q1 Because the Runnable interface defines a run() method with void return type and no parameters. The method given in the problem has a String parameter, so the compiler will complain that class Q1 does not define void run() from interface The run() method above has a String parameter, therefore it does not implement the run() method of the Runnable interface and because the Runnable interface is not fully implemented the Q1 class must be an abstract class. The following code works. The changes are in bold: 01. public class Q1 implements Runnable 02. { 03. public void run() 04. { 05. System.out.println("Before start of Thread"); 06. System.out.println("After stop of Thread"); 07. } 08. 09. public static void main(String[] args) 10. { 11. Q1 a = new Q1(); 12. Thread t=new Thread(a); 13. t.start(); 14. } 15. }

Source code file:

Exam Objective/s:

139 of 256

Page 140: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

111. What is output from the following code: 01. class s1 implements Runnable { 02. int x = 0, y = 0; 03. int addX() {x++; return x;} 04. int addY() {y++; return y;} 05. public void run() { 06. for(int i = 0; i < 10; i++) 07. System.out.println(addX() + " " + addY()); 08. } 09. public static void main(String args[]) { 10. s1 run = new s1(); 11. Thread t1 = new Thread(run); 12. Thread t2 = new Thread(run); 13. t1.start(); 14. t2.start(); 15. } 16. }

A. Compile time Error: There is no start() method

B. Will print in this order: 1 1 2 2 3 3 4 4 5 5…

C. Will print but not exactly in an order (e.g: 1 1 2 2 1 1 3 3…)

D. Will print in this order: 1 2 3 4 5 6…1 2 3 4 5 6…

E. Will print in this order 1 2 3 4 5 6 7 8…

Answer: B

Explanation: Both threads are operating on the same instance variables. If you modify the code of the run() method to print the thread name:

public void run() { for(int i = 0; i < 10; i++) Thread.currentThread().getName() + ": "

System.out.println(

+ addX() + " " + addY()); }

You will get an output similar to the following:

Source code file:

Exam Objective/s:

140 of 256

Page 141: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

112. What will be output from the following code: 01. public class Test107 implements Runnable { 02. private int x; 03. private int y; 04. 05. public static void main(String args[]) { 06. Test107 that = new Test107(); 07. (new Thread(that)).start(); 08. (new Thread(that)).start(); 09. } 10. 11. public synchronized void run() { 12. for(int i = 0; i < 10; i++) { 13. x++; 14. y++; 15. System.out.println("x = " + x + ", y = " + y); 16. } 17. } 18. }

A. Compilation error.

B. Will print in this order: x = 1 y = 1 x = 2 y = 2 x = 3 y = 3 x = 4 y = 4 x = 5 y = 5… but the output will be produced by both threads running simultaneously.

C. Will print in this order: x = 1 y = 1 x = 2 y = 2 x = 3 y = 3 x = 4 y = 4 x = 5 y = 5… but the output will be produced by first one thread then the other. This is guaranteed by the synchronised code.

D. Will print but not exactly in an order (e.g: x = 1 y = 1 x = 2 y = 2 x = 1 y = 1 x = 3 y = 3…)

E. Will print in this order: x = 1 y = 2 x = 3 y = 4 x = 5 y = 6… x = 1 y = 2 x = 3 y = 4 x = 5 y = 6…

F. Will print in this order x = 1 y = 2 x = 3 y = 4 x = 5 y = 6 x = 7 y = 8…

Answer: C

Explanation: Both threads are operating on the same instance variables. Because the code is synchronized the first thread will complete before the second thread begins. Modify line 15 to print the thread names: System.out.println(Thread.currentThread().getName() + " x = " + x + ", y = " + y); And you will get an output similar to the following:

Source code file: Test107.java

Exam Objective/s:

141 of 256

Page 142: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

113. What is output from the following code? 01. class s1 implements Runnable { 02. int x = 0, y = 0; 03. int addX() {x++; return x;} 04. int addY() {y++; return y;} 05. public void run() { 06. for(int i = 0; i < 10; i++) 07. System.out.println(addX() + " " + addY()); 08. } 09. public static void main(String args[]) { 10. s1 run1 = new s1(); 11. s1 run2 = new s1(); 12. Thread t1 = new Thread(run1); 13. Thread t2 = new Thread(run2); 14. t1.start(); 15. t2.start(); 16. } 17. }

A. Compile time Error: There is no start() method

B. Will print in this order: 1 1 2 2 3 3 4 4 5 5…

C. Will print but not exactly in an order (e.g: 1 1 2 2 1 1 3 3…)

D. Will print in this order: 1 2 3 4 5 6…1 2 3 4 5 6…

E. Will print in this order 1 2 3 4 5 6 7 8…

Answer: C

Explanation: Both threads are operating on different sets of instance variables. If you modify the code of the run() method to print the thread name it will help to clarify the output:

public void run() { for(int i = 0; i < 10; i++) System.out.println( Thread.currentThread().getName() + ": " + addX() + " " + addY()); }

and you will get an output similar to the following:

Source code file:

Exam Objective/s:

142 of 256

Page 143: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

114. Given: 01. class Test109 implements Runnable { 02. private int x; 03. private int y; 04. public void run() { 05. // code goes here 06. } 07. public static void main(String args[]) { 08. Test109 h = new Test109(); 09. new Thread(h).start(); 10. new Thread(h).start(); 11. } 12. void setX(int i) { 13. x = i; 14. } 15. void setY(int j) { 16. y = j; 17. } 18 synchronized void setXY(int i) { 19. setX(i); 20. setY(i); 21. } 22. synchronized boolean check() { 23. return x != y; 24. } 25. }

Select a true statement from the following.

A. The check() method never returns true.

B. Multiple threads accessing setX(), setY() can result in check() returning true.

C. Multiple threads accessing setXY() can result in check() returning true.

D. Compilation error because there is no start().

Answer: B

Explanation: A is wrong.Circumstances may permit the check() method to return true. B is correct. After a call to setX() and setY(), the variables x and y may have the same values - there are no guarantees with threads about which thread runs first, when/if it is interrupted, at what point it is interrupted, which thread will finish first/last. Therefore a call to check() may/may not return false. for (int i = 0; i < 5000; i++) { this.setX( i ); this.setY( i ); System.out.println(i + " ... " + Thread.currentThread().getName() + ": " + this.x + " " + this.y + " " + check() ); } C is wrong. After a call to setXY(), the variables x and y will have the same values (because of the synchronised code), therefore a call to check() will always return false. for (int i = 0; i < 5000; i++) { this.setXY( i ); System.out.println(i + " ... " +

143 of 256

Page 144: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Thread.currentThread().getName() + ": " + this.x + " " + this.y + " " + check() ); } D is wrong. The code compiles fine, start() is a method in the thread class.

Source code file: Test109.java

Exam Objective/s:

144 of 256

Page 145: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

115. Given 01. class Test115 implements Runnable { 02. int x = 0, y = 0; 03. synchronized void addX(){ x++; } 04. synchronized void addY(){ y++; } 05. void addXY() { x++; y++; } 06. boolean check() { return (x > y) ? true: false; } 07. 08. public void run() { 09. // code goes here 10. System.out.println( check() ); 11. } 12. public static void main(String args[]) { 13. Test115 run = new Test115(); 14. Thread t1 = new Thread(run); 15. Thread t2 = new Thread(run); 16. t1.start(); 17. t2.start(); 18. } 19. }

In what order must these methods be called in order that check() will return true? (Select all that apply.)

A. Call addX() and addY() simultaneously for number of times in run().

B. Call addY() and addX() simultaneously for number of times in run().

C. Call addXY() for number of times in run().

D. The check() method never returns true.

Answer: A, B, C

Explanation: I ran the code as follows and each time check() returned false which might lead you to choose D as the correct answer: However, there are no guarantees with threads about which thread runs first, when/if it is interrupted, at what point it is interrupted, which thread will finish first/last. class Test115 implements Runnable { int x = 0, y = 0; boolean worked = false; synchronized void addX(){ x++; } synchronized void addY(){ y++; } void addXY() { x++; y++; } boolean check() { return (x > y) ? true: false; } public void run() { // code goes here for (int i = 0; i < 1000; i++) { //this.addX( ); //this.addY( ); //this.addX( ); this.addXY( ); if (check()) worked = true; } System.out.println(Thread.currentThread().getName() + " Was true returned? " + worked ); } public static void main(String args[]) {

145 of 256

Page 146: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Test115 run = new Test115(); Thread t1 = new Thread(run); Thread t2 = new Thread(run); t1.start(); t2.start(); } }

Source code file: Test115.java

Exam Objective/s:

146 of 256

Page 147: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

116. Given: 01. class Test116 { 02. static final StringBuffer sb1 = new StringBuffer(); 03. static final StringBuffer sb2 = new StringBuffer(); 04. public static void main(String args[]) { 05. 06. new Thread() { 07. public void run() { 08. synchronized(sb1) { 09. sb1.append("A"); 10. sb2.append("B"); 11. } 12. } 13. }.start(); 14. 15. new Thread() { 16. public void run() { 17. synchronized(sb1) { 18. sb1.append("C"); 19. sb2.append("D"); 20. } 21. } 22. }.start(); 23. 24. System.out.println (sb1 + " " + sb2); 25. } 26. }

What will be the output?

A. main() will finish before starting threads.

B. main() will finish in the middle of one thread.

C. main() will finish after one thread.

D. main() will finish in middle of the second thread.

E. main() will finish after the second thread

F. Cannot be determined.

Answer: F

Explanation: Can you guarantee the order in which threads are going to run? No you can’t. So how do you know what the output will be? The output cannot be determined. Change line 23 to: try { Thread.sleep(5000); } catch(InterruptedException e) { } and you have some chance of predicting the outcome.

Source code file: Test116.java

Exam Objective/s:

147 of 256

Page 148: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

117. Given: 01. class Happy extends Thread { 02. 03. final StringBuffer sb1 = new StringBuffer(); 04. final StringBuffer sb2 = new StringBuffer(); 05. 06. public static void main(String args[]) { 07. final Happy h = new Happy(); 08. 09. new Thread() { 10. public void run() { 11. synchronized(this) { 12. h.sb1.append("A"); 13. h.sb2.append("B"); 14. System.out.println(h.sb1); 15. System.out.println(h.sb2); 16. } 17. } 18. }.start(); 19. 20. new Thread() { 21. public void run() { 22. synchronized(this) { 23. h.sb1.append("D"); 24. h.sb2.append("C"); 25. System.out.println(h.sb2); 26. System.out.println(h.sb1); 27. } 28. } 29. }.start(); 30. } 31. }

What will be output?

A. ABBCAD

B. ABCBCAD

C. CDADACB

D. CDDACB

E. Output non-deterministic because of the chance of 'deadlock'.

F. Output determined by the underlying platform.

Answer: F

Explanation: Can you guarantee the order in which threads are going to run? No you can’t. So how do you know what the output will be? The output cannot be determined.

Source code file: Test117.java

Exam Objective/s:

148 of 256

Page 149: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

118. Given: 01. class s implements Runnable { 02. int x, y; 03. public void run() { 04. for(int i = 0; i < 1000; i++) 05. synchronized(this) { 06. x = 12; 07. y = 12; 08. } 09. System.out.println(x + " " + y); 10. } 11. public static void main(String args[]) 12. { 13. s run = new s(); 14. Thread t1 = new Thread(run); 15. Thread t2 = new Thread(run); 16. t1.start(); 17. t2.start(); 18. } 19. }

What will be the result?

A. DeadLock

B. Execute without any problems and print 12 12 12 12

C. Compilation Error

D. Cannot determine output.

Answer: B

Explanation:

Source code file: Test118.java

Exam Objective/s:

149 of 256

Page 150: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

119. Given 01. class X implements Runnable { 02. public static void main(String args[]) { 03. // What should be inserted here? 04. } 05. public void run() {} 06. }

Which of the following line of code is suitable to start a thread

A. Thread t = new Thread(X);

B. Thread t = new Thread(X); t.start();

C. X run = new X(); Thread t = new Thread(run);

D. Thread t = new Thread(); x.run();

Answer: C

Explanation:

Source code file: Test119.java

Exam Objective/s:

150 of 256

Page 151: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

120. What will be the result of the following code? 01. class s1 extends Thread{ 02. public void run() { 03. for(int i = 0; i < 3; i++) { 04. System.out.println("A"); 05. System.out.println("B"); 06. } 07. } 08. 09. } 10. 11. class Test120 extends Thread { 12. public void run() { 13. for(int i = 0; i < 3; i++) { 14. System.out.println("C"); 15. System.out.println("D"); 16. } 17. } 18. 19. public static void main(String args[]) { 20. s1 t1 = new s1(); 21. Test120 t2 = new Test120(); 22. t1.start(); 23. t2.start(); 24. } 25. }

A. Compile time Error There is no start method

B. Will print in this order AB CD AB......

C. Will print but not be able to predict the Order

D. Will print in this order ABCD......ABCD......

Answer: C

Explanation:

Source code file: Test120.java

Exam Objective/s:

151 of 256

Page 152: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

121. Given: 01. public class Q121 implements Runnable { 02. public void run (Thread t) { 03. System.out.println("Running"); 04. } 05. public static void main (String[] args) { 06. new Thread (new Q121()).start(); 07. } 08. }

What is the result?

A. An exception is thrown.

B. The program exists without printing anything.

C. An error at line 1 causes compilation to fail.

D. An error at line 2 causes the compilation to fail.

E. “Running” is printed and the program exits.

Answer: C

Explanation: Due to the passing of the Thread t parameter in the run method (line 02). The compiler complains with the following: Q121.java:1: Q121 is not abstract and does not override abstract method run() in java.lang.Runnable because the Runnable interface defines a run() method with void return type and no parameters. The method given in the problem has a Thread parameter, so the compiler will complain that class Q121 does not define void run() from interface The run() method above has a Thread parameter, therefore it does not implement the run() method of the Runnable interface and because the Runnable interface is not fully implemented the Q121 class must be an abstract class.

Certification Objective:

Source Code: Q121.java

See Also: Question 110.

152 of 256

Page 153: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

122. Which statement is true?

A. If only one thread is blocked in the wait method of an object, and another thread executes the modify on that same object, then the first thread immediately resumes execution.

B. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, it is still possible that the first thread might never resume execution.

C. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, then the first thread definitely resumes execution as a direct and sole consequence of the notify call.

D. If two threads are blocked in the wait method of one object, and another thread executes the notify method on the same object, then the first thread that executed the wait call first definitely resumes execution as a direct and sole consequence of the notify call.

Answer: B

Explanation: A is incorrect – just because another thread activates the modify method in A this does not mean that the thread will automatically resume execution B is correct – The notify method only wakes the thread. It does not guarantee that the thread will run. C is incorrect – This is incorrect because as said in Answer B notify only wakes the thread but further to this once it is awake it goes back into the stack and awaits execution therefore it is not a “direct and sole consequence of the notify call” D is incorrect – The notify method wakes one waiting thread up. If there are more than one sleeping threads then the choice as to which thread to wake is made by the machine rather than you therefore you cannot guarantee that the notify’ed thread will be the first waiting thread.

Certification Objective:

Source Code:

See Also:

153 of 256

Page 154: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

123. Which two can be used to create a new Thread? (Choose Two)

A. Extend java.lang.Thread and override the run() method.

B. Extend java.lang.Runnable and override the start() method.

C. Implement java.lang.Thread and implement the run() method.

D. Implement java.lang.Runnable and implement the run() method.

E. Implement java.lang.Thread and implement the start() method.

Answer: A, D

Explanation: There are two ways of creating a thread; extend (sub-class) the Thread class and implement the Runnable interface. For both of these ways you must implement (override and not overload) the public void run() method. Keeping this in mind you can see that the answer is A and D. A is correct - Extending the Thread class and overriding its run method is a valid procedure. D is correct - You must implement interfaces, and runnable is an interface and you must also include the run method. B is wrong - Runnable is an interface which implements not Extends. Gives the error: (No interface expected here) C is wrong - You cannot implement java.lang.Thread (This is a Class). (Implements Thread, gives the error: Interface expected). Implements expects an interface.

E is wrong - You cannot implement java.lang.Thread (This is a class). You Extend classes, and Implement interfaces. (Implements Thread, gives the error: Interface expected) There are two ways to create a new thread of execution: One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.

Certification Objective:

Source Code:

See Also:

154 of 256

Page 155: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

124. Given: 01. public class SyncTest { 02. private int x; 03. private int y; 04. private synchronized void setX(int i) {x = 1;} 05. private synchronized void setY(int i) {y = 1;} 06. public void setXY(int i){setX(i); setY(i);} 07. public synchronized Boolean check() {return x != y;} 08. }

Under which conditions will check() return true when called from a different class?

A. check() can never return true.

B. check() can return true when setXY() is called by multiple threads.

C. check() can return true when multiple threads call setX() and setY() separately.

D. check() can only return true if SyncTest is changed to allow x and y to be set separately.

Answer: B

Explanation: C is wrong because both methods are private and cannot be called from a different class.

Certification Objective:

Source Code:

See Also:

155 of 256

Page 156: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

125. Exhibit: 01. class Q125 implements Runnable { 02. int i; 03. public void run () { 04. try { 05. Thread.sleep(5000); 06. i = 10; 07. } catch(InterruptedException e) {} 08. } 09. } 10. 11. class Test { 12. public static void main(String args[]) { 13. try { 14. Q125 a = new Q125(); 15. Thread t = new Thread(a); 16. t.start(); 17. 18. int j = a.i; 19. System.out.println("The value of j is: " + j); 20. } catch (Exception e) {} 21. } 22. }

Which statement at line 17 will ensure that j = 10 at line 19?

A. a.wait();

B. t.wait();

C. t.join();

D. t.yield();

E. t.notify();

F. a.notify();

G. t.interrupt();

Answer: C

Explanation: You can use the join() method to coordinate your activities with another thread by waiting for the other thread to complete its task. Calling a thread’s join() method causes the caller to block until the target thread dies. Alternatively you can poll the thread by calling join() with a number of milliseconds to wait. Using wait() and notify() would be a much more powerful means of coordinating the activities of threads.

Certification Objective:

Source Code:

See Also: Question 109

156 of 256

Page 157: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

126. Given: 01. public class Q126 implements Runnable { 02. private int x; 03. private int y; 04. 05. public static void main(String [] args) { 06. Q126 that = new Q126(); 07. (new Thread(that)).start( ); 08. (new Thread(that)).start( ); 09. } 10. 11. public synchronized void run( ) { 12. for (;;) { 13. x++; 14. y++; 15. System.out.println("x = " + x + "y = " + y); 16. } 17. } 18. }

What is the result?

A. An error at line 11 causes compilation to fail.

B. Errors at lines 7 and 8 cause compilation to fail.

C. The program prints pairs of values for x and y that might not always be the same on the same line (for example, “x=2, y=1”)

D. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears twice (for example, “x=1, y=1” followed by ”x=1, y=1”¨)

E. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears once (for example, “x=1, y=1” followed by “x=2, y=2”¨)

Answer: E

Explanation: The synchronized code is the key to answering this question. Because x and y are both incremented inside the synchronized method they are always incremented together. Also keep in mind that the two threads share the same reference to the Q126 object. Also note that because of the infinite loop at line 12, only one thread ever gets to execute.

Certification Objective:

Source Code: Q126.java

See Also: Question 112

157 of 256

Page 158: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

127. Given: 01. public class Q126a implements Runnable{ 02. private int x; 03. private int y; 04. 05. public static void main(String[] arg){ 06. Q126a that = new Q126a(); 07. (new Thread(that)).start(); 08. (new Thread(that)).start(); 09. } 10. 11. public void run(){ 12. for(;;){ 13. x++; 14. y++; 15. System.out.println("x = " + x + " y = " + y); 16. } 17. } 18. }

What is the result?

A. Errors at lines 7 and 8 cause compilation to fail.

B. The program prints pairs of values for x and y that might not always be the same on the same line (for example, “x=2, y=1”)

C. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears twice (for example, “x=1, y=1” followed by ”x=1, y=1”¨)

D. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears only for once (for example, “x=1, y=1” followed by “x=2, y=2”¨)

Answer: B

Explanation: A is incorrect. It compiles. B is correct. C is incorrect. Because the threads share the same object D is incorrect. The method is not synchronized. There is a big chance to be interrupted between incrementing statements and print out statement by each thread.

Source: Q126a.java

158 of 256

Page 159: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

128. Which two CANNOT directly cause a thread to stop executing? (Choose Two)

A. Exiting from a synchronized block.

B. Calling the wait() method on an object.

C. Calling notify() method on an object.

D. Calling read() method on an InputStream object.

E. Calling the SetPriority() method on a Thread object.

Answer: A, C

Explanation: A is correct. Typically, releasing a lock means the thread holding the lock (in other words, the thread currently in the synchronized method) exits the synchronized method. Exiting synchronized code does not directly stop the execution of a thread. (Also see the explanation for Q104.) C is correct. notify() - wakes up a single thread that is waiting on this object's monitor.

Certification Objective:

Source Code: Q126.java

See Also: Question 101 Question 104

128a. Which two CANNOT directly cause a thread to stop executing? (Choose Two)

A. Calling the yield method.

B. Calling the wait method on an object.

C. Calling the notify method on an object.

D. Calling the notifyAll method on an object.

E. Calling the start method on another Thread object.

Answer: C, D

Explanation:

Certification Objective:

Source Code:

See Also:

159 of 256

Page 160: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

129. Given: 01. public class Q128{ 02. public static void main(String[] args) { 03. final StringBuffer s1= new StringBuffer(); 04. final StringBuffer s2= new StringBuffer(); 05. 06. new Thread () { 07. public void run() { 08. synchronized(s1) { 09. s1.append("A"); 10. synchronized(s2) { 11. s2.append("B"); 12. System.out.print(s1); 13. System.out.print(s2); 14. } 15. } 16. } 17. }.start(); 18. 19. new Thread() { 20. public void run() { 21. synchronized(s2) { 22. s2.append("C"); 23. synchronized(s1) { 24. s1.append("D"); 25. System.out.print(s2); 26. System.out.print(s1); 27. } 28. } 29. } 30. }.start(); 31. 32. } 33. }

Which two statements are true? (Choose Two)

A. The program prints “ABBCAD”

B. The program prints “CDDACB”

C. The program prints “ADCBADBC”

D. The output is a non-deterministic point because of a possible deadlock condition.

E. The output is dependent on the threading model of the system the program is running on.

Answer: D, B

Explanation: D is correct - A deadlock situation could occur because of the order in which objects are used to lock the synchronized code (remember each object hase only one lock). s1 and s2 lines 8 and 10, s2 and s1 lines 21 and 23 - this crossover could signal a deadlock situation.

Certification Objective:

Source Code: Q128.java

160 of 256

Page 161: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

See Also:

161 of 256

Page 162: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

130. Which method in the Thread class is used to create and launch a new thread of execution?

A. run();

B. start();

B. execute();

C. run(Runnable r);

D. start(Runnable r);

E. execute(Thread t);

Answer: B

Explanation:

Certification Objective:

Source Code:

See Also:

162 of 256

Page 163: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

131. What will happen when you attempt to compile and run the following code? 01. public class ThreadDemo { 02. private int count = 1; 03. public synchronized void doSomething() { 04. for (int i = 0; i < 10; i++) 05. System.out.println(count++); 06. } 07. public static void main(String[] args) { 08. ThreadDemo demo = new ThreadDemo(); 09. Thread a1 = new A(demo); 10. Thread a2 = new A(demo); 11. a1.start(); 12. a2.start(); 13. } 14. } 15. class A extends Thread { 16. ThreadDemo demo; 17. public A(ThreadDemo td) { 18. demo = td; 19. } 20. public void run() { 21. demo.doSomething(); 22. } 23. }

A. It will print the numbers 0 to 19 sequentially

B. It will print the numbers 1 to 20 sequentially

C. It will print the numbers 1 to 20, but the order cannot be determined

D. It will print the numbers 0 to 19, but the order cannot be determined

E. The code will not compile

Answer: B

Explanation: You have two different threads that share one reference to a common object. The updating and output takes place inside synchronized code. One thread will run to completion printing the numbers 1-10. The second thread will then run to completion printing the numbers 11-20.

Certification Objective:

Source Code:

See Also:

163 of 256

Page 164: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

132. What is the result of compiling and executing the following code? 01. public class ThreadTest extends Thread { 02. public void run() { 03. System.out.println("In run"); 04. yield(); 05. System.out.println("Leaving run"); 06. } 07. public static void main(String []argv) { 08. (new ThreadTest()).start(); 09. } 10. }

A. The code fails to compile in the main() method

B. The code fails to compile in the run() method

C. Only the text "In run" will be displayed

D. The text "In run" followed by "Leaving run" will be displayed

E. The code compiles correctly, but nothing is displayed

Answer: D

Explanation:

Certification Objective:

Source Code:

See Also:

164 of 256

Page 165: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

133. What will be the result of trying to compile and run the following code? 01. class MyThread extends Thread { 02. MyThread() {} 03. MyThread(Runnable r) {super(r); } 04. public void run() { System.out.print("Inside Thread ");} 05. } 06. class MyRunnable implements Runnable { 07. public void run() { 08. System.out.print(" Inside Runnable"); } 09. } 10. class Test { 11. public static void main(String[] args) { 12. new MyThread().start(); 13. new MyThread(new MyRunnable()).start(); 14. } 15. }

A. Prints "Inside Thread Inside Thread"

B. Prints "Inside Thread Inside Runnable"

C. Does not compile

D. Throws exception at runtime

E. None of the above

Answer: A

Explanation: If a Runnable object is passed to the Thread constructor, then the run method of the Thread class will invoke the run method of the Runnable object. In this case, however, the run method in the Thread class is overridden by the run method in MyThread class. Therefore the run() method in MyRunnable is never invoked. Both times, the run() method in MyThread is invoked instead.

Certification Objective:

Source Code: TestQ133.java

See Also:

165 of 256

Page 166: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

134. What happens when you compile/run this code? 01. public class Q1 implements Runnable 02. { 03. public void run(String s) 04. { 05. System.out.println("Before start of Thread: " + s); 06. System.out.println("After stop of Thread: " + s); 07. } 08. 09. public static void main(String[] args) 10. { 11. Q1 a = new Q1(); 12. Thread t = new Thread(a); 13. t.start(); 14. } 15. }

A. Compilation error at line 1

B. Runtime exception at line 13

C. Compilation error at line 14

D. Prints "Before start of Thread After Start of Thread”

E. None of the above

Answer: A

Explanation: The compiler complains with the error: Q1.java:1: Q1 should be declared abstract; it does not define run() in Q1 Because the Runnable interface defines a run() method with void return type and no parameters. The method given in the problem has a String parameter, so the compiler will complain that class Q1 does not define void run() from interface The run() method above has a String parameter, therefore it does not implement the run() method of the Runnable interface and because the Runnable interface is not fully implemented the Q1 class must be an abstract class. The following code works. The changes are in bold:

01. public class Q1 implements Runnable 02. { 03. public void run() 04. { 05. System.out.println("Before start of Thread"); 06. System.out.println("After stop of Thread"); 07. } 08. 09. public static void main(String[] args) 10. { 11. Q1 a = new Q1(); 12. Thread t=new Thread(a); 13. t.start(); 14. } 15. }

166 of 256

Page 167: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

135. Which method must be defined by a class implementing the java.lang.Runnable interface?

A. void run()

B. public void run()

C. public void start()

D. void run(int priority)

E public void run(int priority)

F. public void start(int priority)

Answer: B

Explanation: B is correct because in an interface all methods are abstract by default therefore they must be overridden by the implementing class. The Runnable interface only contains 1 method, the void run() method therefore it must be implemented. A and D are incorrect because they are narrowing the access privileges i.e. package(default) access is narrower than public access. D and E are incorrect because run() is an abstract method which takes no arguments there for the attempted overloading in D and E will fail C and F are not methods in the Runnable interface therefore are incorrect NOTE: the start() method is a part of the java.lang.Thread class

167 of 256

Page 168: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Summary Notes on Collections

Common collection activities include adding objects, removing objects, verifying object inclusion, retrieving objects, and iterating.

Three meanings for “collection”:

o Collection—Represents the data structure in which objects are stored

o Collection—java.util.Collection—Interface from which Set and List extend

o Collections—A class that holds static collection utility methods

Three basic flavors of collections include Lists, Sets, Maps:

o Lists of things: Ordered, duplicates allowed, with an index

o Sets of things: May or may not be ordered and/or sorted, duplicates not allowed

o Maps of things with keys: May or may not be ordered and/or sorted, duplicate keys not allowed

Four basic subflavors of collections include Sorted, Unsorted, Ordered, Unordered.

Ordered means iterating through a collection in a specific, nonrandom order.

Sorted means iterating through a collection in a natural sorted order.

Natural means alphabetic, numeric, or programmer-defined, whichever applies.

Key attributes of common collection classes:

o ArrayList: Fast iteration and fast random access

o Vector: Like a somewhat slower ArrayList, mainly due to its synchronized methods

o LinkedList: Good for adding elements to the ends, i.e., stacks and queues

o HashSet: Assures no duplicates, provides no ordering

o LinkedHashSet: No duplicates; iterates by insertion order or last accessed (new with 1.4)

o TreeSet: No duplicates; iterates in natural sorted order

o HashMap: Fastest updates (key/value pairs); allows one null key, many null values

o Hashtable: Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed

o LinkedHashMap: Faster iterations; iterates by insertion order or last accessed, allows one null key, many null values (new with 1.4)

o TreeMap: A sorted map, in natural order

168 of 256

Page 169: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

The collections class and interface hierarchy

Collection Interface Concrete Implementation Classes

169 of 256

Page 170: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Notes on the java.util Interface Iterator

An iterator is used to iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:

o Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.

o Method names have been improved. Method Summary:

o boolean hasNext() Returns true if the iteration has more elements. o Object next() Returns the next element in the iteration. o void remove() Removes from the underlying collection the last element returned by the iterator

(optional operation).

Notes on the java.util Interface ListIterator

Iterator is a superinterface of ListIterator. ListIterator is an iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). Note that the remove() and set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last element returned by a call to next() or previous(). Method Summary

o void add(Object o) Inserts the specified element into the list (optional operation). o boolean hasNext() Returns true if this list iterator has more elements when traversing the list

in the forward direction. o boolean hasPrevious() Returns true if this list iterator has more elements when traversing the

list in the reverse direction. o Object next() Returns the next element in the list. o int nextIndex() Returns the index of the element that would be returned by a subsequent call

to next. o Object previous() Returns the previous element in the list. o int previousIndex() Returns the index of the element that would be returned by a subsequent

call to previous. o void remove() Removes from the list the last element that was returned by next or previous

(optional operation). o void set(Object o) Replaces the last element returned by next or previous with the specified

element (optional operation).

170 of 256

Page 171: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

136. Given: 01. import java.util.*; 02. class I { 03. public static void main (String[] args) { 04. Object i = new ArrayList().iterator(); 05. System.out.print((i instanceof List)+","); 06. System.out.print((i instanceof Iterator)+","); 07. System.out.print(i instanceof ListIterator); 08. } 09}

What is the result of attempting to compile and run the program?

A. Prints: false,false,false

B. Prints: false,false,true

C. Prints: false,true,false

D. Prints: false,true,true

E. Prints: true,false,false

F. Prints: true,false,true

G. Prints: true,true,false

H. Prints: true,true,true

I. None of the above

Answer: C

Explanation: The iterator() method returns an iterator over the elements in the list in proper sequence, it doesn’t return a List or a ListIterator object. A ListIterator can be obtained by invoking the listIterator method.

Source code file:

Exam Objective/s:

171 of 256

Page 172: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

137. Given: 01. import java.util.*; 02. class J { 03. public static void main (String[] args) { 04. Object i = new ArrayList().listIterator(); 05. System.out.print((i instanceof List)+","); 06. System.out.print((i instanceof Iterator)+","); 07. System.out.print(i instanceof ListIterator); 08. } 09. }

What is the result of attempting to compile and run the program?

A. Prints: false,false,false

B. Prints: false,false,true

C. Prints: false,true,false

D. Prints: false,true,true

E. Prints: true,false,false

F. Prints: true,false,true

G. Prints: true,true,false

H. Prints: true,true,true

I. None of the above

Answer: D

Explanation: ListIterator extends Iterator.

Source code file:

Exam Objective/s:

172 of 256

Page 173: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

138. Given 01. import java.util.*; 02. class H { 03. public static void main (String[] args) { 04. Object x = new Vector().elements(); 05. System.out.print((x instanceof Enumeration)+","); 06. System.out.print((x instanceof Iterator)+","); 07. System.out.print(x instanceof ListIterator); 08. } 09. }

What is the result of attempting to compile and run the program?

A. Prints: false,false,false

B. Prints: false,false,true

C. Prints: false,true,false

D. Prints: false,true,true

E. Prints: true,false,false

F. Prints: true,false,true

G. Prints: true,true,false

H. Prints: true,true,true

I. None of the above

Answer: E

Explanation: The Vector.elements method returns an Enumeration over the elements of the vector. Vector implements the List interface and extends AbstractList so it is also possible to get an Iterator over a Vector by invoking the iterator or listIterator method.

Source code file:

Exam Objective/s:

173 of 256

Page 174: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

139. Which of the following are true statements?

A. The Iterator interface declares only two methods: hasMoreElement and nextElement.

B. The ListIterator interface extends both the List and Iterator interfaces.

C. The ListIterator interface was introduced with Java 1.2 to replace the older Iterator interface that was released with Java 1.0.

D. The ListIterator interface declares only three methods: hasNext, next, and remove.

E. None of the above.

Answer: E

Explanation: The Iterator interface declares three methods: hasNext, next and remove. The ListIterator interface was introduced in Java 1.2 along with the Iterator interface. The ListIterator interface extends the Iterator interface and declares additional methods to provide forward and backward iteration capabilities, List modification capabilities, and the ability to determine the position of the iterator in the List. The ListIterator interface does not extend the List interface.

Source code file:

Exam Objective/s:

174 of 256

Page 175: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

140. Which of the following are true statements?

A. The Iterator interface declares only three methods: hasNext, next and remove.

B. The ListIterator interface extends both the List and Iterator interfaces.

C. The ListIterator interface provides forward and backward iteration capabilities.

D. The ListIterator interface provides the ability to modify the List during iteration.

E. The ListIterator interface provides the ability to determine its position in the List.

F. None of the above.

Answer: A, C, D, E

Explanation: The ListIterator interface extends the Iterator interface and declares additional methods to provide forward and backward iteration capabilities, List modification capabilities, and the ability to determine the position of the iterator in the List.

Source code file:

Exam Objective/s:

175 of 256

Page 176: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

141. Which of the following are true statements?

A. The Enumeration interface was introduced with the collections framework with Java 1.2.

B. The Enumeration interface declares only two methods: hasMoreElements and nextElement.

C. The Iterator interface extends the Enumeration interface.

D. The Iterator interface declares a total of three methods.

E. None of the above.

Answer: B, D

Explanation: The Enumeration interface was introduced with Java 1.0 to provide an easy means of moving through the elements of a Vector or the key or values of a Hashtable. The Iterator interface was introduced with the collections framework with Java 1.2. The Iterator interface declares three methods: hasNext, next and remove. The first two methods, hasNext and next, are similar to the two methods declared in the Enumeration interface, hasMoreElements and nextElement. The third method of the Iterator interface, remove, provides new functionality relative to the Enumeration interface.

Source code file:

Exam Objective/s:

176 of 256

Page 177: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

142. Suppose that you would like to create an instance of a new Set that has an iteration order that is the same as the iteration order of an existing instance of a Set. Which concrete implementation of the Set interface should be used for the new instance?

A. The answer depends on the implementation of the existing instance.

B. HashSet

C. LinkedHashSet

D. TreeSet

E. None of the above.

Answer: C

Explanation: The iteration order of a Collection is the order in which an iterator moves through the elements of the Collection. The iteration order of a LinkedHashSet is determined by the order in which elements are inserted. When a new LinkedHashSet is created by passing a reference to an existing Collection to the constructor of a LinkedHashSet, the Collection.addAll method will ultimately be invoked. The addAll method uses an iterator to the existing Collection to iterate through the elements of the existing Collection and add each to the instance of the new LinkedHashSet. Since the iteration order of the LinkedHashSet is determined by the order of insertion, the iteration order of the new LinkedHashSet must be the same as the interation order of the old Collection.

Source code file:

Exam Objective/s:

177 of 256

Page 178: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

143. Examine the following list: a. Stores key/value pairs. b. Allows null elements, keys, and values. c. Duplicate entries replace old entries. d. Entries are not sorted using a comparator or the Comparable interface. e. The iteration order is unspecified. Which of these classes provides the specified features?

A. LinkedList

B. LinkedHashMap

C. LinkedHashSet

D. TreeMap

E. TreeSet

F. HashMap

G. HashSet

H. Hashtable

I. None of the above

Answer: F

Explanation: The requirement to store key/value pairs is directly satisfied by a concrete implementation of the Map interface. The List and Set interfaces recognize objects, but do not recognize keys and values. The requirement to allow null elements is not satisfied by a Hashtable. TreeMap and TreeSet store elements in a sorted order based on the key. The iteration order of LinkedHashMap and LinkedHashSet is not unspecified. By default, the interation order of LinkedHashMap and LinkedHashSet is based on the order in which elements were inserted. Optionally, the iteration order of the LinkedHashMap can be set to the order in which the elements were last accessed.

Source code file:

Exam Objective/s:

178 of 256

Page 179: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

144. Examine the following list: a. Each element must be unique. b. Duplicate elements must not replace old elements. c. Elements are not key/value pairs. d. Entries are not sorted using a comparator or the Comparable interface. e. The iteration order is determined by the insertion order. Which of these classes provides the specified features?

A. HashMap

B. HashSet

C. Hashtable

D. LinkedHashMap

E. LinkedHashSet

F. LinkedList

G. TreeMap

H. TreeSet

I. None of the above

Answer: E

Explanation: The elements of a Map are key/value pairs so a Map is not a good choice. A List generally accepts duplicate elements. A Set stores a collection of unique elements. Any attempt to store a duplicate element in a Set is rejected. TreeSet stores elements in a sorted order based on the key. HashSet does not sort the elements based on the key. The iteration order of LinkedHashMap and LinkedHashSet is clearly defined. By default, the interation order of LinkedHashMap and LinkedHashSet is based on the order in which elements were inserted. While a LinkedHashSet rejects duplicate entries, the LinkedHashMap allows duplicate entries to replace old entries.

Source code file:

Exam Objective/s:

179 of 256

Page 180: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

145. Suppose that you would like to create an instance of a new Map that has an iteration order that is the same as the iteration order of an existing instance of a Map. Which concrete implementation of the Map interface should be used for the new instance?

A. TreeMap

B. HashMap

C. LinkedHashMap

D. The answer depends on the implementation of the existing instance.

E. None of the above.

Answer: C

Explanation: The iteration order of a Collection is the order in which an iterator moves through the elements of the Collection. The iteration order of a LinkedHashMap is determined by the order in which elements are inserted. When a new LinkedHashMap is created by passing a reference to an existing Collection to the constructor of a LinkedHashMap the Collection.addAll method will ultimately be invoked. The addAll method uses an iterator to the existing Collection to iterate through the elements of the existing Collection and add each to the instance of the new LinkedHashMap. Since the iteration order of the LinkedHashMap is determined by the order of insertion, the iteration order of the new LinkedHashMap must be the same as the interation order of the old Collection.

Source code file:

Exam Objective/s:

180 of 256

Page 181: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

146. You need to store elements in a collection that guarantees that no duplicates are stored and all elements can be accessed in natural order. Which interface provides that capability?

A. java.util.Map

B. java.util.Set

C. java.util.List

D. java.util.Collection

Answer: B

Explanation: What does natural order mean? Does it mean the order in which elements are added to an array? Or, does it mean the order in which things occur naturally? For example, add the strings “John”, “Anne”, “Stephen” to an array. Is this the natural order or is “Anne”, John”, “Stephen” the natural order. I choose the second definition, the order in which things occur naturally. A is wrong. A map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order (ascending key order); others, like the HashMap class, do not (does not guarantee that the order will remain constant over time). B is correct. A set is a collection that contains no duplicate elements. The iterator returns the elements in no particular order (unless this set is an instance of some class that provides a guarantee). A map cannot contain duplicate keys but it may contain duplicate values. List and Collection allow duplicate elements. C is wrong. A list is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. D is wrong. A collection is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements.

Source code file:

Exam Objective/s:

181 of 256

Page 182: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

147. Which statement is true for the class java.util.HashSet?

A. The elements in the collection are ordered.

B. The collection is guaranteed to be immutable.

C. The elements in the collection are guaranteed to be unique.

D. The elements in the collection are accessed using a unique key.

E. The elements in the collections are guaranteed to be synchronized.

Answer: C

Explanation: A is wrong. HashSet makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. B is wrong. The set can be modified. C is correct. HashSet implements the Set interface and the Set interface specifies collection that contains no duplicate elements. D is wrong. This is a Set and not a Map. E is wrong. HashSet is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.

Source code file:

Exam Objective/s:

182 of 256

Page 183: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

148. Which statement is true for the class java.util.ArrayList?

A. The elements in the collection are ordered.

B. The collection is guaranteed to be immutable.

C. The elements in the collection are guaranteed to be unique.

D. The elements in the collection are accessed using a unique key.

E. The elements in the collections are guaranteed to be synchronized.

Answer: A

Explanation: A is correct. B is wrong. C is wrong. D is wrong. E is wrong.

Source code file:

Exam Objective/s:

183 of 256

Page 184: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

149. You need to store elements in a collection that guarantees that no duplicates are stored. Which two interfaces provide that capability? (Choose Two)

A. Java.util.Map

B. Java.util.Set

C. Java.util.List

D. Java.util.Collection

Answer: A, B

Explanation: A is correct. A map cannot contain duplicate keys. B is correct. A set is a collection that contains no duplicate elements. C is wrong. Lists typically allow duplicate elements. D is wrong. Collection allows duplicate elements.

Source code file:

Exam Objective/s:

184 of 256

Page 185: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

150. Which interface provides the capability to store objects using a key-value pair?

A. Java.util.Map.

B. Java.util.Set.

C. Java.util.List.

D. Java.util.Collection.

Answer: A

Explanation:

Source code file:

Exam Objective/s:

185 of 256

Page 186: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

151. Which interface does java.util.HashTable implement?

A. Java.util.Map.

B. Java.util.List.

C. Java.util.HashTable.

D. Java.util.Collection.

Answer: A

Explanation:

Source code file:

Exam Objective/s:

186 of 256

Page 187: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

152. The file MyNewVector.java is shown in the exhibit. What is the result? 01. package foo; 02. 03. import java.util.Vector; 04. 05. private class MyVector extends Vector { 06. int i = 1; 07. public MyVector() { 08. i = 2; 09. } 10. } 11. 12. public class MyNewVector extends MyVector { 13. public MyNewVector () { 14. i = 4; 15. } 16. public static void main (String args []) { 17. MyVector v = new MyNewVector(); 18. } 19. }

A. Compilation will succeed.

B. Compilation will fail at line 5.

C. Compilation will fail at line 6.

D. Compilation will fail at line 14.

E. Compilation will fail at line 17.

Answer: B

Explanation: B is correct. The compiler complains with the error “modifier private not allowed here”. The class is created private and is being used by another class on line 17.

Source code file: Test133.java

Exam Objective/s:

187 of 256

Page 188: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

153. Given: 11. ArrayList a = new ArrayList(); 12. a.add(“Alpha”); 13. a.add(“Bravo”); 14. a.add(“Charlie”); 14. a.add(“Delta”); 16. Iterator iter = a.iterator();

Which two, added at line 17, print the names in the ArrayList in alphabetical order? (Choose 2)

A. for(int i = 0; i < a.size(); i++) System.out.println(a.get(i)));

B. for(int i = 0; i < a.size(); i++) System.out.println(a[i]);

C. while(iter.hasNext()) System.out.println(iter.next[i]);

D. for(int i = 0; i < a.size(); i++) System.out.println(iter[i]);

E. for(int i = 0; i < a.size(); i++) System.out.println(iter.get(i)));

Answer: A, C

Explanation : A is correct because we are dealing with an ArrayList rather than an Array so the .get() method must be used retrieve a value from the Arraylist. C is correct because an Iterator allows the caller to remove elements from the underlying collection(in this case the Arraylist) during the iteration and the .next() method returns the next element in the iteration. B & D are wrong because they are trying to print values from an ArrayList without using the .get() method E is wrong because it is trying to use the .get() method of the ArrayList on the Iterator object (Iterator methods: .hasNext(), .next(), .remove();)

188 of 256

Page 189: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

154. Given: 01. // Point X 02. public class foo { 03. public static void main(String[]args)throws Exception{ 04. java.io.PrintWriter out = new java.io.PrintWriter(); 05. new java.io.OutputStreamWriter(System.out),true); 06. out.println(“Hello”); 07. } 08. }

What line of code should be inserted at Point X to make this program compile?

A. No statement required.

B. import java.io.*;

C. include java.io.*;

D. import java.io.PrintWriter;

E. import java.io.PrintWriter:

Answer: A

Explanation : The usual method for using/importing the java packages/classes is by using an import statement at the top of your code. However it is possible to explicitly import the specific class that you want to use as you use it which is shown in the code above. The disadvantage of this however is that every time u create a new object you will have to use the class path in the case “java.io” then the class name in the long run leading to a lot more typing.

189 of 256

Page 190: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

155 Which are valid declarations of a float?(Choose 2)

A. float f = 1F;

B. float f = 1.0;

C. float f = ‘1’;

D. float f = “1”;

E. float f = 1.0d;

Answer: A, C

Explanation : B is incorrect because any literal number with a decimal point u declare the computer will implicitly cast to double unless you include “F or f” D is incorrect because it is a String!! E is incorrect because “d” tells the computer it is a double so therefore you are trying to put a double value into a float variable i.e there might be a loss of precision.

190 of 256

Page 191: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

156. Given: 01. public class Test { 02. private static int[] x; 03. public static void main(String[] args) { 04. System.out.println(x[0]); 05. } 06. }

What is the result?

A. 0

B. null

C. Compile Error

D. NullPointException at runtime

E. ArrayIndexOutOfBoundsException at runtime

Answer: D

Explanation : In the above code the array reference variable x has been declared but it has not been instantiated i.e. the new statement is missing, for example: private static int[]x = new int[5]; private static int[x] declares a static i.e. class level array. the “new” keyword is the word that actually creates said array. int[5] in association with the new sets the size of the array. so since the above code contains no new or size decalarations when u try and access x[0] u are trying to access a member of an array that has been declared but not intialized hence you get a NullPointException at runtime.

191 of 256

Page 192: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

157. Given: 01. public class Test { 02. public static void main (String[] args) { 03. String foo = args[1]; 04. String bar = args[2]; 05. String baz = args[3]; 06. System.out.println(“baz = “ + baz); 07. } 08. }

And the command line invocation:

java Test red green blue

What is the result?

A. baz =

B. baz = null

C. baz = blue

D. Compile Error

E. Runtime Exception

Answer: E

Explanation : When running the program you entered 3 arguments “red”, “green” and “blue”. When dealing with arrays in java you must remember ALL ARRAYS IN JAVA ARE ZERO BASED therefore args[0] becomes “red”, args[1] becomes “green” and args[2] becomes “blue”. When the program entcounters line 6 above at runtime it looks for args[3] which has never been created therefore you get an ArrayIndexOutOfBoundsException at runtime.

192 of 256

Page 193: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

158. Given: 01. public static void main(String[] args) { 02. Object obj = new Object() { 03. public int hashCode() { 04. return 42; 05. }}; 06. System.out.println(obj.hashCode()); 07. };

What is the result?

A. 42

B. Runtime Exception

C. Compile Error at line 2

D. Compile Error at line 5

E. Compile Error at line 6

Answer: A

Explanation : This code is an example of an anonymous inner class. They can be declared to extend another class or implement a single interface. Since they have no name you can not use the “new” keyword on them. In this case the annoynous class is extending the Object class. Within the {} u place the methods you want for that class. After this class has been declared its methods can be used by that object in the usual way e.g. objectname.annoymousClassMethod() .

193 of 256

Page 194: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

159. Which of the following are Java reserved words?(Choose 2)

A. run

B. import

C. default

D. implement

Answer: B, C

Explanation : A - Is incorrect because although it is a method of Thread/Runnable it is not a keyword B - This is a Java keyword C - This is a Java keyword D - This is not a Java keyword the keyword is implements

194 of 256

Page 195: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

160. Which of the following statements are true regarding the return values of properly written hashCode() and equals() methods from two instances of the same class? (Choose 2)

A. If the hashCode values are different, the objects might be equal

B. If the hashCode values are the same, the objects must be equal

C. If the hashCode values are the same, the objects might be equal

D. The hashCode values are different, the objects must be unequal

Answer: C, D

Explanation: The follow excerpt from the Java Spec explains the correct answers: The general contract of hashCode is: (1) Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. (2) If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. (3) It is not required that if two objects are unequal according to the equals (java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

195 of 256

Page 196: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

161. Which of the following statements about the hashcode() method are incorrect? Select all incorrect statements.

A. The value returned by hashcode() is used in some collection classes to help locate objects.

B. The hashcode() method is required to return a positive int value.

C. The hashcode() method in the String class is the one inherited from Object.

D. Two new empty String objects will produce identical hashcodes.

Answer: B, C

Explanation: Answer B is an incorrect statement because there is no such requirement. Answer C is an incorrect statement and therefore a correct answer because the hashcode for a string is computed from the characters in the string. Answers A and D are correct statements and therefore incorrect.

196 of 256

Page 197: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

162. What is the numerical range or char?

A. 0…32767

B. 0…65535

C. –256…255

D. –32768…32767

E. Range is platform dependant

Answer: B

Explanation : The char type is integral but unsigned. The range of a variable of type char is from 0 to 216-1 or 0 to 65535. Java characters are Unicode, which is a 16-bit encoding capable of representing a wide range of international characters. If the most significant nine bits of a char are 0, then the encoding is the same as seven-bit ASCII.

197 of 256

Page 198: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

163. Given: 01. public class Test { 02. private static float[] f = new flaot[2]; 03. public static void main (String[] args) { 04. System.out.println(“f[0] = “ + f[0]); 05. } 06. }

What is the result?

A. f[0] = 0

B. f[0] = 0.0

C. Compile Error

D. Runtime Exception

Answer: B

Explanation : C is incorrect because this code will compile perfectly D is incorrect because this code will run perfectly The choices are between A and B, what this question is really testing is your knowledge of default values of an initialized array. This is an array type float i.e. it is a type that uses decimal point numbers therefore its initial value will be 0.0 and not 0

198 of 256

Page 199: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

164. Given: 01. public class Test { 02. public static void main (String args[]) { 03. String str = NULL; 04. System.out.println(str); 05. } 06. }

A. NULL

B. Compile Error

C. Code runs but no output

D. Runtime Exception

Answer: B

Explanation : This is correct because to set the value of a String variable to null you must use “null” and not “NULL”

199 of 256

Page 200: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

165. Which interface does java.util.Hashtable implement?

A. java.util.Map

B. java.util.List

C. java.util.Hashable

D. java.util.Collection

Answer: A

Explanation : java.util.Map is implemented by the following Classes: AbstractMap, Attributes, HashMap, Hashtable, IdentityHashMap, RenderingHints, TreeMap, WeakHashMap java.util.List is implemented by the following Classes: Accessible, ImageObserver, ItemSelectable, MenuContainer, Serializable java.util.Hashtable not an interface, it is a class. java.util.Collection is implemented by the following Classes: AbstractCollection, AbstractList, AbstractSet, ArrayList, BeanContextServicesSupport, BeanContextSupport, HashSet, LinkedHashSet, LinkedList, TreeSet, Vector

200 of 256

Page 201: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

166. Given: 01. System.out.println(Math.sqrt(-4D));

What is the result?

A. –2

B. NaN

C. Compile Error

D. Runtime Exception

Answer: B

Explanation: It is not possible in regular mathematics to get a value for the square-root of a negative number therefore a NaN will be returned because the code is valid.

201 of 256

Page 202: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

167. Given: 01. String a = “ABCD”; 02. String b = a.toLowerCase(); 03. b.replace(‘a’,’d’); 04. b.replace(‘b’,’c’); 05. System.out.println(b);

A. abcd

B. ABCD

C. dccd

D. dcba

E. Compile Error

F. Runtime Exception

Answer: A

Explanation: This question requires a good knowledge of the String methods and what they do. String objects are immutable, they cannot be changed, in this case we are talking about the replace method which returns a new String object resulting from replacing all occurrences of oldChar in this string with newChar. b.replace(char oldChar, char newChar); But since this is only a temporary String it must either be put to use straight away i.e. System.out.println(b.replace(‘a’,’d’)); Or a new variable must be assigned its value i.e. String c = b.replace(‘a’,’d’);

202 of 256

Page 203: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

168. Given: 01. String a = null; 02. a.concat(“abc”); 03. a.concat(“def”); 04. System.out.println(a);

A. abc

B. null

C. abcdef

D. Compile Error

E. Code runs with no output

F. Runtime Exception

Answer: F

Explanation: When the code is run you will get: ”Exception in Thread “main”java.lang.NullPointerException” The rules of NullPointerException ‘s are: Thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object. Taking the length of null as if it were an array. Accessing or modifying the slots of null as if it were an array. Throwing null as if it were a Throwable value. String objects are immutable. The method concat() returns a new String object, it does not modify the current object. In the question the code was trying to modify a String object but since this object was infact null it was breaking 1 of the rules > Accessing or modifying the field of a null object < therefore a NullPointerException was thrown

203 of 256

Page 204: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

169. Click the exhibit button: 01. public class Test138 { 02. public static void stringReplace (String text) { 03. text = text.replace ('j' , 'c'); 04. } 05. 06. public static void bufferReplace (StringBuffer text) { 07. text = text.append ("c"); 08. } 09. 10. public static void main (String args[]) { 11. String textString = new String ("java"); 12. StringBuffer textBuffer = new StringBuffer ("java"); 13. stringReplace(textString); 14. bufferReplace(textBuffer); 15. System.out.println (textString + textBuffer); 16. } 17. }

What is the output?

Answer: javajavac

Explanation: A string is immutable, it cannot be changed, that’s the reason for the StringBuffer class. The stringReplace method does not change the string declared on line 12, so this remains set to “java”. Method parameters are always passed by value – a copy is passed into the method – if the copy changes, the original remains intact, line 03 changes the reference i.e. text points to a new String object, however this is lost when the method completes. The textBuffer is a StringBuffer so it can be changed. This change is carried out on line 07, so “java” becomes “javac”, the text reference on line 07 remains unchanged. This gives us the output of “javajavac” on line 15.

Source code file: Test138.java

Exam Objective/s:

204 of 256

Page 205: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

170. Consider the following code sample: 01. class Tree { } 02. class Pine extends Tree { } 03. class Oak extends Tree { } 04. public class Forest { 05. public static void main (String [] args){ 06. Tree tree = new Pine(); 07. if( tree instanceof Pine ) 08. System.out.println ("Pine"); 09. if( tree instanceof Tree ) 10. System.out.println ("Tree"); 11. if( tree instanceof Oak ) 12. System.out.println ( "Oak" ); 13. else 14. System.out.println ("Oops "); 15. } 16. }

Select all choices that will be printed:

A. Pine

B. Tree

C. Forest

D. Oops

E. Nothing will be printed

Answer: A, B, D

Explanation:

Source code file: Forest.java

Exam Objective/s:

205 of 256

Page 206: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

171. Consider the following code sample: 01. class Tree { } 02. class Pine extends Tree { } 03. class Oak extends Tree { } 04. public class Forest1 { 05. public static void main (String [] args){ 06. Tree tree = new Pine(); 07. if( tree instanceof Pine ) 08. System.out.println ("Pine"); 09. else if( tree instanceof Tree ) 10. System.out.println ("Tree"); 11. else if( tree instanceof Oak ) 12. System.out.println ( "Oak" ); 13. else 14. System.out.println ("Oops "); 15. } 16. }

Select all choices that will be printed:

A. Pine

B. Tree

C. Forest

D. Oops

E. Nothing will be printed

Answer: A

Explanation:

Source code file: Forest1.java

Exam Objective/s:

206 of 256

Page 207: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

172. Given: 01. interface Foo141 { 02. int k = 0; 03. } 04. public class Test141 implements Foo141 { 05. public static void main(String args[]) { 06. int i; 07. Test141 test141 = new Test141(); 08. i = test141.k; 09. i = Test141.k; 10. i = Foo141.k; 11. } 12. }

What is the result?

A. Compilation fails.

B. Compiles and runs ok.

C. Compiles but throws an Exception at runtime.

C. Compiles but throws a RuntimeException at runtime.

Answer: B

Explanation: The variable k on line 02 is an interface constant, it is implicitly public, static, and final. Static variables can be referenced in two ways: Via a reference to any instance of the class (line 08). Via the class name (line 09).

Source code file: Test141.java

Exam Objective/s:

207 of 256

Page 208: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

173. Given: 11. int i = 1, j = 10; 12. do { 13. if(i++ > --j) { 14. continue; 15. } 16. } while (i < 5); 17. System.out.println("i = " + i + "and j = " + j);

What is the result?

A. i = 6 and j = 5

B. i = 5 and j = 5

C. i = 6and j = 5

D. i = 5 and j = 6

E. i = 6 and j = 6

Answer: D

Explanation: This question is not testing your knowledge of the continue statement. It is testing your knowledge of the order of evaluation of operands. Basically the prefix and postfix unary operators have a higher order of evaluation than the relational operators. So on line 13 the variable i is incremented and the variable j is decremented before the greater than comparison is made. As the loop executes the comparison on line 13 will be: if(i > j) if(2 > 9) if(3 > 8) if(4 > 7) if(5 > 6) at this point i is not less than 5, therefore the loop terminates and line 17 outputs the values of i and j as 5 and 6 respectively. The continue statement never gets to execute because i never reaches a value that is greater than j. Review the notes on the following page.

Certification Objective: 5.1

Source Code: Q142.java

See Also:

208 of 256

Page 209: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

Precedence and Associativity Rules for Operators Precedence and associativity rules are necessary for deterministic evaluation of expressions. The operators, together with their precedence and associativity, are summarized in the table below. The following remarks apply to the table below:

• The operators are shown with decreasing precedence from the top of the table. • Operators within the same row have the same precedence. • Parentheses, (), can be used to override precedence and associativity. • The unary postfix operators and all binary operators, except for the assignment operators, associate from left to

right. • All unary operators (except for unary postfix operators), all assignment operators, and the ternary conditional

operator (including object creation and cast) associate from right to left.

Table: Operator Precedence and Associativity Postfix Operators [ ] . (parameters) expression++ expression--

Prefix Unary Operators ++expression --expression +expression -expression ~ !

Object creation and cast new (type)

Multiplication * / %

Addition + -

Shift << >> >>>

Relational operators < <= > >= instanceof

Equality operators == ! =

bitwise/Boolean AND &

bitwise/Boolean XOR ^

bitwise/boolean OR I

logical AND &&

logical OR ||

Conditional operator ? :

Assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=

Precedence rules are used to determine which operator should be applied first if there are two operators with different precedence, and these follow each other in the expression. In such a case, the operator with the highest precedence is applied first. 2 + 3 * 4 is evaluated as 2 + (3 * 4) (with the result 14) since * has higher precedence than +. Associativity rules are used to determine which operator should be applied first if there are two operators with same precedence, and these follow each other in the expression.

• Left associativity implies grouping from left to right: 1 + 2 -3 is interpreted as ((1 + 2) -3) since the binary operators + and - both have same precedence and left associativity.

• Right associativity implies grouping from right to left: --4 is interpreted as (- (- 4)) (with result 4) since the unary operator - has right associativity.

209 of 256

Page 210: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

174. Given 01. class Test { 02. public static void main(String[] args) { 03. int i = 2; 04. int j = (i=3) * i; 05. System.out.println(j); 06. } 07. }

What is the result?

A. 4

B. 6

C. 9

D. ArithmeticError exception is thrown.

Answer: C

Explanation: If the left-hand operand contains an assignment to a variable and the right-hand operand contains a reference to that same variable, then the value produced by the reference will reflect the fact that the assignment occurred first (JLS 15.7.1 Evaluate Left-Hand Operand First).

Certification Objective: 5.1

Source Code: Q143.java

See Also: The notes on “Precedence and Associativity Rules for Operators” above.

Exam Objective/s:

210 of 256

Page 211: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

175. Given: 01. class Q144 { 02. public static void main(String[] args) { 03. int a = 9; 04. a += (a = 3); 05. System.out.println(a); 06. int b = 9; 07. b = b + (b = 3); 08. System.out.println(b); 09. } 10. }

What is the result?

A. 12 12

B. 6 12

C. 12 6

D. 6 6

Answer: A

Explanation: If the operator is a compound-assignment operator, then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied combining operation (JLS 15.7.1 Evaluate Left-Hand Operand First).

Certification Objective: 5.1

Source Code: Q144.java

See Also: The notes on “Precedence and Associativity Rules for Operators” above.

Exam Objective/s:

211 of 256

Page 212: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

176. Given 01. class Q145 { 02. public static void main(String[] args) { 03. int j = 1; 04. try { 05. int i = forgetIt() / (j = 2); 06. } catch (Exception e) { 07. System.out.println(e); 08. System.out.println("Now j = " + j); 09. } 10. } 11. static int forgetIt() throws Exception { 21. throw new Exception("I'm outta here!"); 13. } 14. }

What is the result?

A. Arithmetic.Exception

B. Compile error: no return value for forgetIt()

C. java.lang.Exception: I'm outta here! Now j = 2

D. java.lang.Exception: I'm outta here! Now j = 1

Answer: D

Explanation: If evaluation of the left-hand operand of a binary operator completes abruptly, no part of the right-hand operand will have been evaluated (JLS 15.7.1 Evaluate Left-Hand Operand First).

Certification Objective: 5.1

Source Code: Q145.java

See Also: The notes on “Precedence and Associativity Rules for Operators” above.

Exam Objective/s:

212 of 256

Page 213: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

177. Given: import java.util.*; public class City177 { public static void main(String[] args) { Set set = new LinkedHashSet(); set.add(new String("Chicago")); set.add(new String("Boston")); set.add(new String("Alabama")); set.add(new String("Chicago")); System.out.println(set); } }

What will be printed out?

A. Alabama Boston Chicago

B. Boston Alabama Chicago

C. Chicago Boston Alabama

D. Chicago Boston Alabama Chicago

Answer: C

Explanation: Can a set contain duplicate entries? No.

Source code file: City177.java

See also:

Exam Objective/s:

213 of 256

Page 214: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

178. Given: public class Test178 { public static void main(String[] args) { String s = "foo"; Object o = (Object)s; if (s.equals(o)) { System.out.print("AAA"); } else { System.out.print("BBB"); } if (o.equals(s)) { System.out.print("CCC"); } else { System.out.print("DDD"); } } }

What will be printed out?

A. AAACCC

B. AAADDD

C. BBBCCC

D. BBBDDD

Answer: A

Explanation:

Source code file: Test178.java

See also:

Exam Objective/s:

214 of 256

Page 215: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

179. Given: public class References { static void increment(int[] a) { a[1]++; } public static void main(String[] args) { int[] a = new int[5]; increment(a); System.out.println(a[1]); } }

What is the outcome:

A. 0

B. 1

C. Compiler error

D. Runtime error

Answer: B

Explanation:

Source code file: References.java

See also:

Exam Objective/s:

215 of 256

Page 216: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

180. Which of the following will produce an answer that is closest in value to a double, d, while not being greater than d?

A. (int)Math.min(d);

B. (int)Math.max(d);

C. (int)Math.abs(d);

D. (int)Math.ceil(d);

E. (int)Math.floor(d);

F. (int)Math.round(d);

Answer: E

Explanation: The casting to an int is a smokesceeen. Use a process of elimination to answer this question: A and B are wrong because both the min() and max() methods require 2 arguments whereas here they are passed only one parameter. C is wrong because it could return a value greater than d (if d was negative). D is wrong because ceil() returns an integetr value that is not less than the argument, so its return value is going to be greater than d. E is the correct answer, it is syntathecially correct and will consistently return a value less than d. F is wrong because it could return a value that is greater than d.

Source code file:

See also:

Exam Objective/s:

216 of 256

Page 217: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

181. Given: public class Test { public static void main(String[] args) { final StringBuffer a = new StringBuffer(); final StringBuffer b = new StringBuffer(); new Thread() { public void run() { System.out.print(a.append("A")); synchronized(b) { System.out.print(b.append("B")); } } }.start(); new Thread() { public void run() { System.out.print(b.append("C")); synchronized(a) { System.out.print(a.append("D")); } } }.start(); } }

What is the output?

A. ACCBAD

B. ABBCAD

C. CDDACB

D. Indeterminate output

Answer: D

Explanation: See question number 116.

Source code file:

See also:

Exam Objective/s:

217 of 256

Page 218: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

182. Given the following: 01. public class ExamQuestion1 { 02. public static void main(String[] args){ 03. try{ 04. badMethod(); 05. System.out.println("A"); 06. } 07. catch(Exception e){ 08. System.out.println("B"); 09. } 10. finally{ 11. System.out.println("C"); 12. } 13. System.out.println("D"); 14. } 15. 16. static void badMethod(){ 17. throw new Error(); 18. } 19. }

What is the result of compiling and executing this code?

A. The code will print out “B”, “C” & “D”

B. Compile Error

C. The code will print out “C” followed by an error message

D. The code will run with no output

Answer: C

Explanation: The important thing to note in this code is that badMethod() is throwing an Error rather but the catch statement on line 07 is only trying to catch an Exception. Both of these are subclasses of Throwable but not of each other. Therefore something trying to catch an Exception will fail to catch an Error. So the code goes something like this.

Call badMethod -> Error Thrown -> No matching catch -> do the “finally” block-> Output “C” -> Error released unhandled from “try” block-> No further errorhandling -> code crashes and error message is displayed.

Source code file: ExamQuestion1.java

See also:

Exam Objective/s:

218 of 256

Page 219: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

183. Given the following : interface I0{}

What lines of code would compile? (Choose two)

A. interface I1 implements I0{}

B. interface I1 extends I0{}

C. abstract class abs1 extends I0{}

D. abstract class abs2 implements I0{}

Answer: B & D

Explanation: - An interface extends another interface so A is wrong and B is right. -A class always implements an interface so C is wrong and D is right.

Source code file: ExamQuestion2.java

See also:

Exam Objective/s:

219 of 256

Page 220: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

184. Which of the following would compile without error?

A. int a = Math.abs(-5);

B. int b = Math.abs(5.0);

C. int c = Math.abs(5.5F);

D. int d = Math.abs(5L);

E. float e = Math.abs(5.1);

Answer: A

Explanation: The return value of the Math.abs() method is always the same as the type of the parameter passed into that method. In the case of A, an integer is passed in and so the result is also an integer which is fine for assignment to “int a”. The values used in B, C & D respectively are a double, a float and a long. The compiler will complain about a possible loss of precision if we try to assign the results to an “int”.

In E, a double is passed into Math.abs which returns a double which we then try to assign to a float. Again compiler complains about “possible loss of precision”!

Source code file: ExamQuestion3.java

See also:

Exam Objective/s:

220 of 256

Page 221: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

185. Which of the following would be suitable for use as keys in a HashMap? (choose two)

A. 3

B. ‘a’

C. new Object()

D. Integer(3)

E. Character(‘a’)

Answer: D & E

Explanation: The put method of the HashMap takes 2 parameters; the 1st is the object that is the key, the 2nd is the object to be added to the HashMap. If the HashMap requires an object as a key then since A & B (above) are primitives rather than objects, they are wrong and won’t compile. C can be used (it does compile and run) but it should be noted that in general keys probably should have meaningful values of some sort rather than just being empty, blank objects! So that leaves us with D & E, which are objects & which have a value. They’re the 2 most correct answers!

Source code file: ExamQuestion4.java

See also:

Exam Objective/s:

221 of 256

Page 222: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

186. What is the value of “d” after this line of code has been executed? double d = Math.round ( 2.5 + Math.random( )) ;

A. 2

B. 3

C. 4

D. 2.5

E. Impossible to say

Answer: B

Explanation: The Math.random() method returns a number greater than or equal to 0 and less than 1 . Since we can then be sure that the sum of that number and 2.5 will be greater than or equal to 2.5 and less than 3.5, we can be sure that Math.round() will round that number to 3. So B is the answer!

Source code file: ExamQuestion5.java

See also:

Exam Objective/s:

222 of 256

Page 223: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

187. Given 01. public class ExamQuestion6 { 02. static int x; 03. boolean catch(){ 04. x++; 05. return true; 06. } 07. public static void main(String[] args){ 08. x=0; 09. if ((catch() | catch()) || catch()) 10. x++; 11 System.out.println(x); 12. } 13. }

What is the result of compiling and executing this code?

A. 1

B. 2

C. 3

D. Compilation Fails

E. 4

Answer: D

Explanation: Initially this looks like a question about the logical and logical shortcut operators “|” and “||” but on closer inspection it should be noticed that the name of the boolean method in this code is “catch”. “catch” is a reserved keyword in the Java language and cannot be used as a method name. Compilation will fail!

Source code file: ExamQuestion6.java

See also:

Exam Objective/s:

223 of 256

Page 224: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

188. Given: 01. public class ExamQuestion7 { 02. static int j; 03. static void methodA(int i){ 04. boolean b; 05. do{ 06. b = i<10 | methodB(4); 07. b = i<10 || methodB(8); 08. }while (!b); 09. } 10. static boolean methodB(int i){ 11. j += i; 12. return true; 13. } 14. public static void main(String[] args){ 15. methodA(0); 16. System.out.println( “j = “ + j ); 17. } 18. }

What will be the result of compiling and running this code?

A. j = 0

B. j = 4

C. j = 8

D. The code will run with no output

E. Compilation fails

Answer: B

Explanation: The lines to watch here are lines 06 & 07. Line 06 features the non-shortcut version of the OR operator so both of its operands will be evaluated and therefore methodB(4) is executed. However line 07 has the shortcut version of the OR operator and if the 1st of its operands evaluates to true (which in this case is true), then the 2nd operand isn’t evaluated, so methodB(8) never gets called. The loop is only executed once, b is initialized to false and is assigned true on line 6. Thus j = 4.

Source code file: ExamQuestion7.java

See also:

Exam Objective/s:

224 of 256

Page 225: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

189. Given: 01. public class ExamQuestion8 { 02. public static void main(String[] args){ 03. try{ 04. int i = 5, j = 0; 05. int k = i/j; 06. } 07. catch(Exception e){ 08. System.out.println("Exception"); 09. } 10. catch(ArithmeticException e){ 11. System.out.println("ArithmeticException"); 12. } 13. System.out.println("Finished"); 14. } 15. }

What is the output as a result of compiling and executing this code? (Choose best answer)

A. Exception

B. ArithmeticException

C. Compilation Fails

D. Finished

Answer: C

Explanation: If we try to compile the code as is, we get a message from the compiler stating “java:10: exception java.lang.ArithmeticException has already been caught”. As we’ve already covered any ArithmeticException (or in fact any other subclass of Exception) that may arise by initially catching an Exception on line 07, any subsequent “catch” statements are redundant and cause compilation to fail! If we reversed the order in which the exceptions are caught, then the code would compile, and output “Exception” followed by “Finished”!

Source code file: ExamQuestion8.java

See also: Q64

Exam Objective/s:

225 of 256

Page 226: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

190. A train system is being built, part of which is a tunnel with only one rail track. Trains will travel in both directions through the tunnel. The system’s designers came up with a model of this with the code below. 01. final class Tunnel{ 02. void accessTunnel(){ 03. Thread.yield(); //let other trains run 04. } 05. } 06. class Train extends Thread{ 07. Tunnel tun; 08. Train(Tunnel t){ 09. super(); 10. tun=t; 11. } 12. public void run(){ 13. tun.accessTunnel(); 14. } 15. } 16. public class ExamQuestion9 { 17. public static void main(String[] args){ 18. Tunnel tunnel=new Tunnel(); 19. while (true){ 20. new Train(tunnel).start(); //make new trains 21. } 22. } 23. }

How can this code be best modified to ensure that only one train is accessing the tunnel at any one time? (Choose one)

A. Put a call to wait() in the accessTunnel() method

B. Put a call to notify() or notifyAll() in the accessTunnel() method

C. Synchronize the call to accessTunnel (on line 13) from the train class with this block of code: sycnhronized(this){ tun.accessTunnel( );}

D. Replace the “Thread.yield();” call on line 03 with try {Thread.sleep(5000);} catch(InterruptedException e){}

E. Synchronize the accessTunnel method in the Tunnel class.

Answer: E

Explanation: Think about synchronizing threads and code locks. Only one train at a time can use the tunnel (only one thread at a time can use a specific piece of code at a time). Thinking this way should reveal the answer to: “What piece of code must be synchronized?” The answer is the code for accessing the tunnel. A & B are wrong. AccessMethod is not synchronized and so wait, notify and notifyAll cannot be used. Furthermore, they are useless on their own. C is wrong. It synchronizes on the Train objects rather than the tunnel so crashes still happen (it is synchronizing a block of code using the lock of the this object i.e. train). D is wrong. It is also no good as crashes could still occur. E is correct. Access is synchronized on the Tunnel object and this prevents crashes!

Source code file: ExamQuestion9.java

226 of 256

Page 227: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

191. Given 11. String s = "ABC"; 12. s.toLowerCase(); 13. s += "def"; 14. System.out.println(s);

What is output after compiling and running this code?

A. ABC

B. abc

C. ABCdef

D. Compile Error

Answer: C

Explanation: String objects are immutable. The object s above is set to “ABC”. Now ask yourself if this object is changed and if so where – remember strings are immutable. Line 12 returns a string object but does not change the originag string object s, so after line 12 s is still “ABC”. So what’s happening on line 13? Java will treat line 13 like the following: s = new StringBuffer().append(s).append("def").toString(); This effectively creates a new string object and stores its reference in the variable s, the old string object containing “ABC” is no longer referenced by a live thread and becomes available for garbage collection.

Source code file: Q191.java

See also:

Exam Objective/s:

227 of 256

Page 228: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

192. Given 11. int i = 0; int j = 1; 12. if ((i++ == 0 ) || (j++ == 1) ) { 13. i = 42; 14. } 15. System.out.println(" i = " + i + " j = " + j);

What is the output?

A i = 0 j = 1

B i = 1 j = 2

C i = 42 j = 1

D i = 42 j = 2

E Compilation failure

Answer: C

Explanation: The short circuit OR operator “||” returns true for the first condition so “i = =42” and the (j++ == 1) never gets evaluated leaving “j = =1“

See also: Q204

Exam Objective/s:

228 of 256

Page 229: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

193. Which words below are Java keywords/reserved words ( Choose two)

A. run

B. default

C. import

D. implement

Answer: B & C

Explanation:

See also:

Exam Objective/s:

229 of 256

Page 230: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

194. Which statement is true given the following (choose one). Double d = Math.random()

A. 0.0 < d <= 1.0

B. 0.0 <= d < 1.0

C. Compilation failure

D. Cannot say.

Answer: B

Explanation: The Math.random() method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 (ref. Java API)

See also:

Exam Objective/s:

230 of 256

Page 231: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

195. Given 01. for (int x = 0; x < 3; x++) { 02. switch(x) { 03. case 0: break; 04. case 1: System.out.print("one"); 05. case 2: System.out.print("two"); 06. case 3: System.out.print("three"); 07. } 08. } 09. System.out.println(x);

What is output?

A one two three one two three 3

B Compilation fails

C one two three two three 3

D Code compiles, but throws a run time exception

Answer: B

Explanation: As variable x is only defined within the for loop the reference to x at line 09 causes compilation failure

Example of compilation out put : “java:11: cannot resolve symbol symbol : variable x location: programname System.out.println(x);

See also: Q54

Exam Objective/s:

231 of 256

Page 232: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

196. Given 01. String s = "hello"; 02. Object o = s; 03. if( o.equals(s) ){ 04. System.out.println("A"); 05. } 06. else{ 07. System.out.println("B"); 08. } 09. if( s.equals(o) ){ 10. System.out.println("C"); 11. } 12. else{ 13. System.out.println("D"); 14. }

What is the output? (Choose two)

A. “A”

B. “B”

C. “C”

D. “D”

Answer: A & C

Explanation:

See also:

Exam Objective/s:

232 of 256

Page 233: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

197. Given: 01. class A { 02. public A(int x){} 03. } 04. class B extends A { 05. } 06. public class test { 07. public static void main (String args []) { 08. A a = new B(); 09. System.out.println(“complete”); 10. } 11. }

What happens when you attempt to compile and run this code?

A. It compiles and runs printing nothing

B. Compiles but fails at runtime

C. Compile Error

D. Prints “complete”

Answer: C

Explanation: No constructor has been defined for class B therefore it will make a call to the default constructor but since class B extends class A it will also call the Super() default constructor. Since a constructor has been defined in class A java will no longer supply a default constructor for class A therefore when class B calls class A’s default constructor it will result in a compile error.

See also:

Exam Objective/s:

233 of 256

Page 234: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

198. Given: 01. interface inter { 02. int floot = 42; 03. } 04. public class test implements inter { 05. public static void main(String args[]) { 06. System.out.println(++floot); 07. } 08. }

What happens when you attempt to compile and run this code?

A. 0

B. 42

C. 43

D. Compile Error

E. Runtime Exception

Answer: D

Explanation: When you declare a variable in an interface it implicitly becomes “public static final” therefore it becomes unchangeable. So when the compiler see’s the ++ in-front of floot on line 6 it will throw a compiler error.

See also:

Exam Objective/s:

234 of 256

Page 235: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

199. Which 2 have the same value?

A. 3 / 4

B. 3 >> 2

C. 3 * 4

D. 3 << 2

E. 3 <<< 2

F. 3 >>> 2

G. 3 + 4

Answer: C and D

Explanation: When you examine the following, the only two that have the same value are C and D A. 3/4 = 0 – Integer division B. 3>>2 = 0 C. 3*4 = 12 D. 3<<2 = 12 (0011(binary) << 2) = 1100 = 12 (3*2*2) E. Compiler error, there is no unsigned left-shift operator. F. 3>>>2 = 0 G. 3+4 = 7

Source code file:

See also: Q97 and the notes on pages 119-120.

Exam Objective/s:

235 of 256

Page 236: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

200. Given: 01. public class Ques { 02. public static void main(String args []) { 03. int x = 0; 04. int y = 0; 05. switch case (x) { 06. case 1: y += 2 07. case 2: y += 3 08. default: y += 4 09. case 3: y += 5 10. } 11. } 12. }

What is the value of y after running the switch statement?

A. 2

B. 3

C. 9

D. 14

E. 0

Answer: C

Explanation: Since there are no break statements within the switch statement when the case hits the default it will set y += 4 and then carry out all the statements following it in the switch statement due to the fact that there are no breaks after it.

Source code file:

See also:

Exam Objective/s:

236 of 256

Page 237: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

201. Given 01. class aTest { 02. int methodA() { 03. return 5; 04. } 05. } 06. 07. class bTest extends aTest { 08. int methodA() { 09. return 10; 10. } 11. } 12. 13. 0public class Q201 { 14. public static void main(String[] args) { 15. bTest t = new bTest(); 16. int a = ((aTest) t).methodA(); 17. System.out.println("Runtime output is: " + a); 18. } 19. }

What is output?

A. Compiler error at line 16

B. Runtime exception is thrown

C. 5

D. 10

Answer: D

Explanation: bTest is a sub class of aTest and it overrides methodA. bTest is instantiated on line 15 and explicitly cast to aTest on line 16, now the question is “Which methodA will be executed?”. The answer is, the methodA in the subclass.

Source code file: Q201.java

See also:

Exam Objective/s:

237 of 256

Page 238: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

202. Given 01. class MyThread extends Thread { 02. public void run() { 03. System.out.println("Running"); 04. } 05. public void start() { 06. System.out.println("Starting"); 07. } 08. } 09. 10. class Q202 { 11. public static void main(String[] args) { 12. MyThread t = new MyThread(); 13. t.start(); 14. } 15. }

What is output?

A. Running

B. Starting

C. Running Starting

D. Starting Running

Answer:B

Explanation: Remember that the start() method of a thread causes that thread to begin execution; the Java Virtual Machine calls the run() method of this thread. In this example the start() method in MyThread overrides the start() method in Thread and it doesn’t make a call to the run() method – the thread never runs.

Source Code: Q202.java

See Also:

Exam Objective/s: 6.1, 7.1, 7.2

238 of 256

Page 239: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

203. Given: class Q203 { public static void main(String[] args) { Integer a1 = new Integer(10); Integer a2 = new Integer(10); Integer a3 = a1; int b1 = 10; int b2 = 10; } }

Which of the following evaluate to true?

A. (a1 == a2)

B. (a1 == a3)

C. (a2 == a3)

D. (b1 == a1)

E. (b1 == b2)

Answer: B, E

Explanation: A is wrong. Both a1 and a2 store references to objects, but the references that they store point to different objects so the reference a1 is not equal to the reference a2. B is correct. Both a1 and a3 store references to objects, in this case both references point to the same object, therefore reference a1 is equal to the reference a3. C is wrong. Both a2 and a3 store references to objects, but the references that they store point to different objects so the reference a2 is not equal to the reference a3. D is wrong. It produces a compile time error “operator == cannot be applied to int,java.lang.Integer” because you are not allowed to test a primitive data type and a reference data type for equality using the == operator. E is correct. b1 and b2 are both primitive data type. They each store the integer value 10, so in this case the test for equality will return true.

Source Code: Q203.java

See Also:

Exam Objective/s:

239 of 256

Page 240: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

204. Given 01. class Q204 { 02. public static void main(String[] args) { 03. int i = 0, j = 0; 04. if (i++ == 0 || j++ == 0) 05. i = 42; 06. System.out.println("i is " + i + ", j is " + j); 07. } 08. }

What is output?

A. i = 1, j = 0

B. i = 0, j = 0

C. i = 42, j = 1

D. i = 42, j = 0

Answer: D

Explanation: The postfix incrementor operator is used here which means that the == comparison with 0 evaluates to true first, then secondly i is incremented to one. Notice that the short-circuit logical operator || is used, now because the first part of the expression evaluated to true, the second part is short-circuited and not evaluated – the value of j remains at zero.

Source Code: Q204.java

See Also: Q192

Exam Objective/s:

240 of 256

Page 241: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

205. Given: 01. class Q205 { 02. public static void main(String[] args) { 03. int x = 6^3; 04. System.out.println("x: " + x); 05. } 06. }

What is output?

A. 216

B. 18

C. 5

D. Compile Error

Answer: C

Explanation: The ^ operator used on line 6 is the Bitwise XOR (eXclusive OR), it’s effect on the bits is to return 1 if and only if one of the bits is 1, otherwise it returns 0.

Operator Decimal Binary

6 0110

^ 3 0011

Result: 5 0101

Source Code: Q205.java

See Also:

Exam Objective/s:

241 of 256

Page 242: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

206. Given: 01. class Q206 { 02. public static void main(String[] args) { 03. if (args.length == 2) { 04. if (args[0] == "-1") { 05. System.out.println(args[1] == "TRUE"); 06. } 07. } 08. } 09. }

What is the output when this program is run with the following command line: java Q206 -1 TRUE

A. true

B. false

C. Runs without exception, but outputs nothing

D. Compile error

E. An ArrayIndexOutOfBoundsException is thrown at runtime

Answer: C

Explanation: Be careful with this question, it is testing your knowledge of both command line arguments and object comparisons (specifically strings). The code is fine, it compiles and runs without any problems. So why doesn’t something print? The answer lies with objects and specifically with comparing two different string objects using the == operator. The == operator will only return true when comparing references that both point to the same object (i.e. the reference variable both contain the same value). In the code above this is clearly not the case. What modifications could be made to the code to make it output something? When the following code is run with this command line java Q206a -1 TRUE the output is true 01. class Q206a { 02. public static void main(String[] args) { 03. if (args.length == 2) { 04. if (args[0].compareTo("-1") == 0) { 05. System.out.println(args[1].compareTo("TRUE") == 0); 06. } 07. } 08. } 09. }

Source Code: Q206.java Q206a.java

See Also:

Exam Objective/s:

242 of 256

Page 243: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

207. Given: 01. class Q207 { 02. public static void main(String[] args) { 03. int i1 = 5; 04. int i2 = 6; 05. String s1 = "7"; 06. System.out.println(i1 + i2 + s1); 07. } 08. }

What is output?

A. 18

B. 117

C. 567

D. Compiler error

E. Runtime exception

Answer: B

Explanation: This question is about the + (plus) operator and the overriden + (string cocatanation) operator. The rules that apply when you have a mixed expression of numbers and strings are: ● If either operand is a String, the + operator concatenates the operands. ● If both operands are numeric, the + operator adds the operands. The expression on line 6 above can be read as “Add the values i1 and i2 together, then take the sum and convert it to a string and concatenate it with the String from the variable s1”. In code, the compiler probably interprets the expression on line 6 above as: System.out.println( new StringBuffer() .append(new Integer(i1 + i2).toString()) .append(s1) .toString() );

Source Code: Q207.java

See Also: Q208

Exam Objective/s: 5.1

243 of 256

Page 244: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

208. Given: 01. class Q208 { 02. public static void main(String[] args) { 03. int i1 = 5; 04. int i2 = 6; 05. String s1 = "7"; 06. // insert code here 07. } 08. }

Which of the following lines of code, independantly inserted at line 6 above, will produce the same output? (Choose 2)

A. System.out.println(s1 + i1 + i2);

B. System.out.println(i1 + s1 + i2);

C. System.out.println(i1 + i2 + s1);

D. System.out.println((s1 + i1) + i2);

E. System.out.println(s1 + (i1 + i2));

F. System.out.println("The answer is: " + i1 + i2 + s1);

Answer: A and D

Explanation: See the explanation for Q207 The output from A is “756” The output from B is “576” The output from C is “117” The output from D is “756” The output from E is “711” The output from F is “The answer is: 567”

Source Code:

See Also: Q207

Exam Objective/s: 5.1

244 of 256

Page 245: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

209. Given: String s = "Hello"; Object o = (Object)s;

Select the statements that are true:

A. s == o returns true

B. s.equals(o) returns true

C. o.equals(s) returns false

D. o.equals(s) trurns true

Answer: A B D

Explanation:

A is true because o and s both refer to the same String in the pool.

B is true as the equals(Object) method returns true if o instanceof String and the string encapsulated by o matches the string encapsulated by the executing object.

C is false because o.equals(s) is true.

OO

Hello Hello SS

Source Code:

public class EqualsTest { public static void main (String[] args) { String s = "Hello"; Object o=(Object)s; System.out.println("A "+(s==o)); System.out.println("B "+(s.equals(o))); System.out.println("C "+!(o.equals(s))); System.out.println("D "+(o.equals(s))); } }

See Also:

Exam Objective/s: 5.2

245 of 256

Page 246: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

210. Given: 01. interface MyInterface { 02. int x; 03. }

Select 3 ways in which x can be declared:

A. public int x;

B. final int x;

C. static int x;

D. volatile int x;

E. transient int x;

Answer: A B C

Explanation: Interface variables are public static and final.

See Also:

Exam Objective/s: 5.2

246 of 256

Page 247: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

211. Given 01. public class Myfile { 02. public static void main (String[] args) { 03. 04. String biz = args[1]; 05. String baz = args[2]; 06. String rip = args[3]; 07. System.out.println("Arg is “ + rip); 08. } 09. }

Select how you would start the program to cause it to print: Arg is 2

A. java Myfile 222

B. java Myfile 1 2 2 3 4

C. java Myfile 1 3 2 2

D. java Myfile 0 1 2 3

Answer: C

Explanation: Arguments start at array element 0 so the fourth arguement must be 2 to produce the correct output.

247 of 256

Page 248: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

212. Given int i = (int) Math.random();

Select the correct answer:

A. i = 0

B. i =1

C. value of i is undetermined

D. Statement causes a compile error

Answer: A

Explanation: Math.random() returns a double value greater than or equal to 0 and less than 1. Its value is stored to an int but as this is a narrowing conversion, a cast is needed to tell the compiler that you are aware that there may be a loss of precision. The value after the decimal point is lost when you cast a double to int and you are left with 0.

248 of 256

Page 249: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

213. Given String str = “3.14235”;

Select two correct ways to declare a float value:

A. float f = 1f

B. float f = 1.0

C. float f =new Float(str)

D. float f =Float.parseFloat(str)

E. float f =Float.valueOf(str)

F. float f =str.floatValue()

Answer: A D

Explanation:

Not B as 1.0 is a double so the compiler would complain about a possible loss of precision

Not C as a Float is a wrapper class and you cannot assign it to the primitive type float.

D works, as parseFloat returns a new float initialized to the value represented by the

String str

Not E as valueOf returns a Float wrapper class

Not F as floatvalue is a method of the Float class, not String class

249 of 256

Page 250: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

214. Given 01. class B { 02. public A a; 03. } 04. 05. class A { 06. public B b; 07. } 08. 09. class Test214 { 10. public static void main (String[] args) { 11. Test214 t = new Test214(); 12. t.makeStuff(); 13. } 14. public void makeStuff() { 15. A a = new A(); 16. B b = new B(); 17. a.b = b; 18. b.a = a; 19. } 20. }

When are objects A and B ready for garbage collection?

A. At the end of main method.

B. At the end of the makeStuff() method.

C. When the program terminates.

D. They will never be garbage collected because of the recursive references in classes A and B.

Answer: B

Explanation: Islands of Isolation There is a way in which objects can become eligible for garbage collection, even if they still have valid references! We think of this scenario as islands of isolation. A simple example is a class that has an instance variable that is a reference variable to another instance of the same class. Now imagine that two such instances exist and that they refer to each other. If all other references to these two objects are removed, then even though each object still has a valid reference, there will be no way for any live thread to access either object. When the garbage collector runs, it will discover any such islands of objects and will remove them.

Source Code: Test214.java

See Also: Islands of Isolation on page 97.

Exam Objective/s:

250 of 256

Page 251: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

215. Which of the following statements are true of Anonymous classes:

A. They can implement many interfaces

B. They can be declared public

C. They can be declared final

D. They can extend other classes.

Answer: C

Explanation: Read through the details below.

A cannot be true (point 10 below).

I suspect that B is false, but I cannot prove this. The class does not take an access modifier. How could you have a public inner class inside a private method?

C I think is correct because of point 5 below.

I think D is false because the anonymous class can extend one class and not several classes (point 10 below).

Some facts about anonymous classes: 1. An anonymous class cannot have an explicitly declared constructor. Instead, the

compiler must automatically provide an anonymous constructor for the anonymous class.

2. An anonymous class is never abstract. 3. An anonymous class is always an inner class. 4. An anonymous class is never static. 5. An anonymous class is always implicitly final. 6. An anonymous class cannot have an explicitly declared constructor. Instead, the

compiler must automatically provide an anonymous constructor for the anonymous class.

7. Anonymous inner classes have no name. 8. An anonymous inner class is always created as part of a statement, so don’t

forget to close the statement after the class definition, with a curly brace. This is one of the rare times you’ll see a curly brace followed by a semicolon in Java.

9. Because of polymorphism, the only methods you can call on an anonymous inner class reference are those defined in the reference variable class (or interface), even though the anonymous class is really a subclass or implementer of the reference variable type.

10. An anonymous inner class can extend one subclass, or implement one interface. Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface.

Source Code:

See Also:

Exam Objective/s:

251 of 256

Page 252: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

995. If the following code block was within an appropriate try/catch block, would it compile without error? FileInputStream fis = new FileInputStream("inputfile"); ObjectInputStream ois = new ObjectInputStream(fis); Point p = ois.readObject();

A. True

B. False

Answer B:

Explanation: The readObject method of ObjectInputStream returns an Object. You must add a cast to the appropriate type (here a Point) for this to compile e.g.: Point p = (Point)ois.readObject();

Source Code:

See Also:

Certification Objective:

252 of 256

Page 253: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

996. Which method(s) must a serializable class implement?

A. It must always implement both readObject and writeObject

B. It must implement either readObject or writeObject, or both, depending upon the desired behavior

C. No methods

Answer: C

Explanation: The Serializable interface includes no methods. It only serves to tag a class as serializable.

Certification Objective:

Source Code:

See Also:

Certification Objective:

253 of 256

Page 254: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

997. What is the most complete set of exceptions that can be thrown when reading a serialized object?

A. IOException

B. ClassNotFoundException, SerialziableException

C. SerialziableException

D. ClassNotFoundException, InvalidClassException, StreamCorruptedException, OptionalDataException, and IOException

E. IOException, SerializableException

Answer: D

Explanation: InvalidClassException, StreamCorruptedException, and OptionalDataException are subclasses of IOException that may be thrown. There is no such thing as a SerializableException.

Source Code:

See Also:

Certification Objective:

254 of 256

Page 255: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

998. What is the most complete set of exceptions that can be thrown when serializing an object?

A. IOException

B. ClassNotFoundException, NotSerializableException

C. NotSerializableException

D. ClassNotFoundException, InvalidClassException, NotSerializableException, OptionalDataException, and IOException

E. InvalidClassException, IOException, NotSerializableException

Answer: E

Explanation: NotSerializableException is the most commonly thrown exception, but InvalidClassException and IOException are also possible.

Source Code:

See Also:

Exam Objective/s:

255 of 256

Page 256: 999 Questions From Cramming for Sun Java

Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)

999. Given that you have an object with references to several data members, and those data members share multiple references to themselves, what must be done when you serialize the object, such that when you deserialize the object, all the original references are restored?

A. Mark any data member with multiple references to be transient

B. Call the checkForMultipleReferences method of ObjectOutputStream before serializing the class

C. Nothing, handling of multiple and circular references are automatic

D. You cannot save and restore an object with multiple references to the same object

Answer: C

Explanation: The serialization mechanism handles saving object trees with multiple and circular references such that restoring the tree will keep the original references intact.

Source Code:

See Also:

Exam Objective/s:

256 of 256