KEY JAVA ( CODE )

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

F

15. Which of the following are legal loop definitions? (Choose all that apply.) A. while (int a = 0) { /* whatever */ } B. while (int a == 0) { /* whatever */ } C. do { /* whatever */ } while (int a = 0) D. do { /* whatever */ } while (int a == 0) E. for (int a==0; a<100; a++) { /* whatever */ } F. None of them are legal.

E

15. Which of the following are methods of the java.util.SortedSet interface? A. first, last B. headSet C. tailSet D. subSet E. All of the above

E

15. Which of the following are true? (Choose all that apply.) A. When an application begins running, there is one daemon thread, whose job is to execute main(). B. When an application begins running, there is one non-daemon thread, whose job is to execute main(). C. A thread created by a daemon thread is initially also a daemon thread. D. A thread created by a non-daemon thread is initially also a non-daemon thread. E. B, C, D

E

15. Which of the following may follow the static keyword? (Choose all that apply.) A. Class definitions B. Data C. Methods D. Code blocks enclosed in curly brackets E. B, C, D

D

15. Which of the following operations might throw an ArithmeticException? A. >> B. >>> C. << D. None of these

A

15. Which of the following restrictions apply to anonymous inner classes? A. They must be defined inside a code block. B. They may only read and write final variables of the enclosing class. C. They may only call final methods of the enclosing class. D. They may not call the enclosing class' synchronized methods.

C

10. Given the following code, what will be the outcome? public class Funcs extends java.lang.Math { public int add(int x, int y) { return x + y; } public int sub(int x, int y) { return x - y; } public static void main(String [] a) { Funcs f = new Funcs(); System.out.println("" + f.add(1, 2)); } } A. The code compiles but does not output anything. B. "3" is printed out to the console. C. The code does not compile. D. None of the above.

E

10. Given the following: int[] ages = { 9, 41, 49 }; int sum = 0; Which of the following are legal ways to add the elements of the array? A. for (int i=0; i<ages.length; i++) sum += ages[i]; B. for (int i=0; i<=ages.length; i++) sum += ages[i]; C. for (int i:ages) sum += i; D. sum += ages[int i:ages]; E. A, C

A

10. Is it possible to define a class called Thing so that the following method can return true under certain circumstances? boolean weird(Thing s) { Integer x = new Integer(5); return s.equals(x); } A. Yes B. No

E

10. Suppose prim is an int and wrapped is an Integer. Which of the following are legal Java statements? (Choose all that apply.) A. prim = wrapped; B. wrapped = prim; C. prim = new Integer(9); D. wrapped = 9; E. All of the above.

D

10. What is the range of values that can be assigned to a variable of type byte? A. Depends on the underlying hardware B. 0 through 2^8 − 1 C. 0 through 2^16 − 1 D. −2^7 through 2^7 − 1 E. −2^15 through 2^15 − 1

A, B, E

15. Given the following class: public class Xyz implements java.io.Serializable { public int iAmPublic; private int iAmPrivate; static int iAmStatic; transient int iAmTransient; volatile int iAmVolatile; . . . } Assuming the class does not perform custom serialization, which fields are written when an instance of Xyz is serialized? (Choose all that apply.) A. iAmPublic B. iAmPrivate C. iAmStatic D. iAmTransient E. iAmVolatile

E

12. Which of the following are true? (Choose all that apply.) A. An enum definition should declare that it extends java.lang.Enum. B. An enum may be subclassed. C. An enum may contain public method definitions. D. An enum may contain private data. E. C, D

E

12. Which of the following calls may be made from a non-static synchronized method? A. A call to the same method of the current object. B. A call to the same method of a different instance of the current class. C. A call to a different synchronized method of the current object. D. A call to a static synchronized method of the current class. E. All of the above.

D

12. Which of the following may legally appear as the new type (between the parentheses) in a cast operation? A. Abstract classes B. Final classes C. Primitives D. All of the above

F

12. Which of the following statements are true? A. An abstract class may be instantiated. B. An abstract class must contain at least one abstract method. C. An abstract class must contain at least one abstract data field. D. An abstract class must be overridden. E. An abstract class must declare that it implements an interface. F. None of the above.

A

15. Given the following code, which of the results that follow would you expect? 1. package mail; 2. 3. interface Box { 4. protected void open(); 5. void close(); 6. public void empty(); 7. } A. The code will not compile because of line 4. B. The code will not compile because of line 5. C. The code will not compile because of line 6. D. The code will compile.

C

15. What happens when you try to compile and run the following code? public class Q15 { static String s; public static void main(String[] args) { System.out.println(">>" + s + "<<"); } } A. The code does not compile B. The code compiles, and prints out >><< C. The code compiles, and prints out >>null<<

B

15. When is x & y an int? (Choose one). A. Always B. Sometimes C. When neither x nor y is a float, a long, or a double

C

18. What happens when you try to compile and run this application? 1. import java.util.*; 2. 3. public class Apple { 4. public static void main(String[] a) { 5. Set<Apple> set = new TreeSet<Apple>(); 6. set.add(new Apple()); 7. set.add(new Apple()); 8. set.add(new Apple()); 9. } 10. } A. Compiler error. B. An exception is thrown at line 6. C. An exception is thrown at line 7. D. An exception is thrown at line 8. E. No exception is thrown.

C

18. When a negative byte is cast to a long, what are the possible values of the result? A. Positive B. Zero C. Negative

B, C

18. Which methods return an enum constant's name? A. getName() B. name() C. toString() D. nameString() E. getNameString()

C

18. Which of the following are legal? A. char c = 0x1234; B. char c = \u1234; C. char c = '\u1234';

A

18. Which of the following may appear on the left-hand side of an instanceof operator? A. A reference B. A class C. An interface D. A variable of primitive type

B

18. Which of the following should always be caught? A. Runtime exceptions B. Checked exceptions C. Assertion errors D. Errors other than assertion errors

D

18. Which of the following statements are true? A. A final class must be instantiated. B. A final class must contain at least one final method. C. A final class must contain at least one final data field. D. A final class may not be extended. E. None of the above.

E

18. Which of the following statements are true? (Choose all correct options.) A. StringBuilder encapsulates a mutable string. B. StringBuilder is threadsafe. C. StringBuffer is threadsafe. D. StringBuffer is generally faster than StringBuilder E. A, C

C

Consider the following application: 1. class Q7 { 2. public static void main(String args[]) { 3. double d = 12.3; 4. Decrementer dec = new Decrementer(); 5. dec.decrement(d); 6. System.out.println(d); 7. } 8. } 9. 10. class Decrementer { 11. public void decrement(double decMe) { 12. decMe = decMe - 1.0; 13. } 14. } What value is printed out at line 6? A. 0.0 B. 1.0 C. 12.3 D. 11.3

C

19. Consider the following code: 1. StringBuffer sbuf = new StringBuffer(); 2. sbuf = null; 3. System.gc(); Choose all true statements: A. After line 2 executes, the StringBuffer object is garbage collected. B. After line 3 executes, the StringBuffer object is garbage collected. C. After line 2 executes, the StringBuffer object is eligible for garbage collection. D. After line 3 executes, the StringBuffer object is eligible for garbage collection.

A

19. Given arrays a1 and a2, which call returns true if a1 and a2 have the same length, and a1[i].equals(a2[i]) for every legal index i? A. java.util.Arrays.equals(a1, a2); B. java.util.Arrays.compare(a1, a2); C. java.util.List.compare(a1, a2); D. java.util.List.compare(a1, a2);

D

19. How many bits does a float contain? A. 1 B. 8 C. 16 D. 32 E. 64

A

19. Suppose class X contains the following method: void doSomething(int a, float b) { ... } Which of the following methods may appear in class Y, which extends X? A. public void doSomething(int a, float b) { ... } B. private void doSomething(int a, float b) { ... } C. public void doSomething(int a, float b) throws java.io.IOException { ... } D. private void doSomething(int a, float b) throws java.io.IOException { ... }

A

19. When does an exception's stack trace get recorded in the exception object? A. When the exception is constructed B. When the exception is thrown C. When the exception is caught D. When the exception's printStackTrace() method is called

D

3. Which of the statements below are true? A. To change the current working directory, call the setWorkingDirectory() method of the File class. B. To change the current working directory, call the cd() method of the File class. C. To change the current working directory, call the changeWorkingDirectory() method of the File class. D. None of the above.

A, E

4. Given the following code: class Xxx { int[] ages; int[] heights = new int[10]; } A. Which statements are true? B. ages is initialized to null. C. ages is initialized to a reference to an array with zero elements. D. heights is initialized to null. E. heights is initialized to a reference to an array with zero elements. F. heights is initialized to a reference to an array with 10 elements.

A

4. How do you use the File class to list the contents of a directory? A. String[] contents = myFile.list(); B. File[] contents = myFile.list(); C. StringBuilder[] contents = myFile.list(); D. The File class does not provide a way to list the contents of a directory.

D

4. If all three top-level elements occur in a source file, they must appear in which order? A. Imports, package declarations, classes/interfaces/enums B. Classes/interfaces/enums, imports, package declarations C. Package declaration must come first; order for imports and class/interfaces/enum definitions is not significant D. Package declaration, imports, class/interface/enum definitions. E. Imports

E

4. In the following code, what are the possible types for variable result? (Choose the most complete true answer.) 1. byte b = 11; 2. short s = 13; 3. result = b * ++s; A. byte, short, int, long, float, double B. boolean, byte, short, char, int, long, float, double C. byte, short, char, int, long, float, double D. byte, short, char E. int, long, float, double

D

4. What would be the output from this code fragment? 1. int x = 0, y = 4, z = 5; 2. if (x > 2) { 3. if (y < 5) { 4. System.out.println("message one"); 5. } 6. else { 7. System.out.println("message two"); 8. } 9. } 10. else if (z > 5) { 11. System.out.println("message three"); 12. } 13. else { 14. System.out.println("message four"); 15. } A. message one B. message two C. message three D. message four

A, C

4. Which of the following expressions are legal? (Choose all that apply.) A. String x = "Hello"; int y = 9; x += y; B. String x = "Hello"; int y = 9; if (x == y) {} C. String x = "Hello"; int y = 9; x = x + y; D. String x = "Hello"; int y = 9; y = y + x;

E

4. Which of the following statements is true? A. Transient methods may not be overridden. B. Transient methods must be overridden. C. Transient classes may not be serialized. D. Transient variables must be static. E. Transient variables are not serialized.

A

8. How can you force garbage collection of an object? A. Garbage collection cannot be forced. B. Call System.gc(). C. Call System.gc(), passing in a reference to the object to be garbage-collected. D. Call Runtime.gc(). E. Set all references to the object to new values (null, for example).

A

8. In the following code fragment, line 4 is executed. 1. String s1 = "xyz"; 2. String s2 = "xyz"; 3. if (s1 == s2) 4. System.out.println("Line 4"); A. True B. False

A

8. The keyword extends refers to what type of relationship? A. "is a" B. "has a" C. "was a" D. "will be a" E. None of the above

C

8. What results from attempting to compile and run the following code? 1. public class Conditional { 2. public static void main(String args[]) { 3. int x = 4; 4. System.out.println("value is " + 5. ((x > 4) ? 99.99 : 9)); 6. } 7. } A. The output: value is 99.99 B. The output: value is 9 C. The output: value is 9.0 D. A compiler error at line 5

D

8. Which modifier or modifiers should be used to denote a variable that should not be written out as part of its class's persistent state? (Choose the shortest possible answer.) A. private B. protected C. private protected D. transient E. volatile

E

8. Which of the following is true? A. Readers have methods that can read and return floats and doubles. B. Readers have methods that can read and return floats. C. Readers have methods that can read and return doubles. D. Readers have methods that can read and return ints. E. None of the above.

A

8. Which of the following methods in the Thread class are deprecated? A. suspend() and resume() B. wait() and notify() C. start() and stop() D. sleep() and yield()

B

9. In the following code fragment, line 4 is executed. 1. String s1 = "xyz"; 2. String s2 = new String(s1); 3. if (s1 == s2) 4. System.out.println("Line 4"); A. True B. False

D

Suppose you are writing a class that will provide custom deserialization. The class implements java.io.Serializable (not java.io.Externalizable). What access mode should the readObject() method have? A. public B. protected C. default D. private

E

iven the following class: class A extends java.util.Vector { private A(int x) { super(x); } } Which statements are true? A. The compiler creates a default constructor with public access. B. The compiler creates a default constructor with protected access. C. The compiler creates a default constructor with default access. D. The compiler creates a default constructor with private access. E. The compiler does not create a default constructor.

E

uppose class A has a method called doSomething(), with default access. Suppose class B extends A and overrides doSomething(). Which access modes may apply to B's version of doSomething()? (Choose all that apply.) A. public B. private C. protected D. Default E. A, C, D

E

12. Which are appropriate uses of assertions? A. Checking preconditions in a private method B. Checking postconditions in a private method C. Checking preconditions in a public method D. Checking postconditions in a public method E. A, B, D

A

14. Which statement is true about the following method? int selfXor(int i) { return i ^ i; } A. It always returns 0. B. It always returns 1. C. It always an int where every bit is 1. D. The returned value varies depending on the argument

A

3. Which of the following expressions results in a positive value in x? A. int x = -1; x = x >>> 5; B. int x = -1; x = x >>> 32; C. byte x = -1; x = x >>> 5; D. int x = -1; x = x >> 5;

B

1. A signed data type has an equal number of non-zero positive and negative values available. A. True B. False

C

1. After execution of the following code fragment, what are the values of the variables x, a, and b? 1. int x, a = 6, b = 7; 2. x = a++ + b++; A. x = 15, a = 7, b = 8 B. x = 15, a = 6, b = 7 C. x = 13, a = 7, b = 8 D. x = 13, a = 6, b = 7

F

1. Given a string constructed by calling s = new String("xyzzy"), which of the calls modifies the string? A. s.append("aaa"); B. s.trim(); C. s.substring(3); D. s.replace('z', 'a'); E. s.concat(s); F. None of the above

B, D, E

1. Given the following: public enum Wallpaper { BROWN, BLUE, YELLOW; } Which of the following are legal? A. enum PatternedWallpaper extends Wallpaper { STRIPES, DOTS, PLAIN; } B. Wallpaper wp = Wallpaper.BLUE; C. Wallpaper wp = new Wallpaper(Wallpaper.BLUE); D. void aMethod(Wallpaper wp) { System.out.println(wp); } E. int hcode = Wallpaper.BLUE.hashCode();

A, D, E

1. Which of the following declarations are illegal? (Choose all that apply.) A. default String s; B. transient int i = 41; C. public final static native int w(); D. abstract double d; E. abstract final double hyperbolicCosine();

D

1. Which of the following statements is correct? A. Only primitives are converted automatically; to change the type of an object reference, you have to do a cast. B. Only object references are converted automatically; to change the type of a primitive, you have to do a cast. C. Arithmetic promotion of object references requires explicit casting. D. Both primitives and object references can be both converted and cast. E. Casting of numeric types may require a runtime check.

D

1. Which of the statements below are true? A. UTF characters are all 8 bits. B. UTF characters are all 16 bits. C. UTF characters are all 24 bits. D. Unicode characters are all 16 bits. E. Bytecode characters are all 16 bits. F. None of the above.

A

1. Which one statement is true concerning the following code? 1. class Greebo extends java.util.Vector 2. implements Runnable { 3. public void run(String message) { 4. System.out.println("in run() method: " + 5. message); 6. } 7. } 8. 9. class GreeboTest { 10. public static void main(String args[]) { 12. Greebo g = new Greebo(); 13. Thread t = new Thread(g); 14. t.start(); 15. } 16. } A. There will be a compiler error, because class Greebo does not correctly implement the Runnable interface. B. There will be a compiler error at line 13, because you cannot pass a parameter to the constructor of a Thread. C. The code will compile correctly but will crash with an exception at line 13. D. The code will compile correctly but will crash with an exception at line 14. E. The code will compile correctly and will execute without throwing any exceptions.

B

10. Consider the following code: 1. Raccoon rocky; 2. SwampThing pogo; 3. Washer w; 4. 5. rocky = new Raccoon(); 6. w = rocky; 7. pogo = w; Which of the following statements is true? (Choose one.) A. Line 6 will not compile; an explicit cast is required to convert a Raccoon to a Washer. B. Line 7 will not compile; an explicit cast is required to convert a Washer to a SwampThing. C. The code will compile and run. D. The code will compile but will throw an exception at line 7, because runtime conversion from an interface to a class is not permitted. E. The code will compile but will throw an exception at line 7, because the runtime class of w cannot be converted to type SwampThing.

E

10. Consider the following code: 1. public class Assertification { 2. public static void main(String[] args) { 3. assert args.length == 0; 4 } 5. } Which of the following conditions must be true in order for the code to throw an AssertionError? Assume you are using release 5.0. (Choose all that apply.) A. The source code must be compiled with the -source 1.5 flag. B. The application must be run with the -enableassertions flag or another assertion- enabling flag. C. The args array must have exactly zero elements. D. The args array must have one or more elements. E. A, B, D

A

10. What is the result of attempting to compile and execute the following code fragment? Assume that the code fragment is part of an application that has write permission in the current working directory. Also assume that before execution, the current working directory does not contain a file called datafile. 1. try { 2. RandomAccessFile raf = new 3. RandomAccessFile("datafile" ,"rw"); 4. BufferedOutputStream bos = new 5. BufferedOutputStream(raf); 6. DataOutputStream dos = new 7. DataOutputStream(bos); 8. dos.writeDouble(Math.PI); 9. dos.close(); 10. bos.close(); 11. raf.close(); 12. } 13. catch (IOException e) { } A. The code fails to compile. B. The code compiles but throws an exception at line 4. C. The code compiles and executes but has no effect on the local file system. D. The code compiles and executes; afterward, the current working directory contains a file called datafile

C, E

10. Which of the following are legal enums? A. enum Animals { LION, TIGER, BEAR } B. enum Animals { int age; LION, TIGER, BEAR; } C. enum Animals { LION, TIGER, BEAR; int weight; } D. enum Animals { LION(450), TIGER(450), BEAR; int weight; Animals(int w) { weight = w; } } E. enum Animals { LION(450), TIGER(450), BEAR; int weight; Animals() { } Animals(int w) { weight = w; } }

C

10. Which of the following statements about the wait() and notify() methods is true? A. The wait() and notify() methods can be called outside synchronized code. B. The programmer can specify which thread should be notified in a notify() method call. C. The thread that calls wait() goes into the monitor's pool of waiting threads. D. The thread that calls notify() gives up the lock

D

11. Given the following code, what is the expected outcome? public class Test { public static void main(String [] a) { int [] b = [1,2,3,4,5,6,7,8,9,0]; System.out.println("a[2]=" + a[2]); } } A. The code compiles but does not output anything. B. "a[2]=3" is printed out to the console. C. "a[2]=2" is printed out to the console. D. The code does not compile. E. None of the above.

B

11. Suppose a source file contains a large number of import statements. How do the imports affect the time required to compile the source file? A. Compilation takes no additional time. B. Compilation takes slightly more time. C. Compilation takes significantly more time.

A, B

11. Suppose class Supe, in package packagea, has a method called doSomething(). Suppose class Subby, in package packageb, overrides doSomething(). What access modes may Subby's version of the method have? (Choose all that apply.) A. public B. protected C. Default D. private

B

11. Suppose ob1 and ob2 are references to instances of java.lang.Object. If (ob1 == ob2) is false, can ob1.equals(ob2) ever be true? A. Yes B. No

D

11. Suppose you are writing a class that will provide custom serialization. The class implements java.io.Serializable (not java.io.Externalizable). What access mode should the writeObject() method have? A. public B. protected C. default D. private

E

11. Which lines check that x is equal to four? Assume assertions are enabled at compile time and runtime. A. assert x == 4; B. assert x != 4; C. assert x == 4 : "x is not 4"; D. assert x != 4 : "x is not 4"; E. A, C

B, D

11. Which of the following are legal? (Choose all that apply.) A. List<String> theList = new Vector<String>; B. List<String> theList = new Vector<String>(); C. Vector <String> theVec = new Vector<String>; D. Vector <String> theVec = new Vector<String>();

B

11. Which of the following is the most appropriate way to handle invalid arguments in a public method? A. Throw java.lang.InvalidArgumentException. B. Throw java.lang.IllegalArgumentException. C. Check for argument validity in an assert statement, which throws AssertionError when the arguments are invalid. D. Use non-assert code to check for argument validity. If invalid arguments are detected, explicitly throw AssertionError

E

11. Which of the following may legally appear as the new type (between the parentheses) in a cast operation? A. Classes B. Interfaces C. Arrays of classes D. Arrays of interfaces E. All of the above

D

11. Which of the following may not be synchronized? A. Blocks within methods B. Static methods C. Blocks within static methods D. Classes

A, B

11. Which of the following may override a method whose signature is void xyz(float f)? A. void xyz(float f) B. public void xyz(float f) C. private void xyz(float f) D. public int xyz(float f) E. private int xyz(float f)

D

12. Given the following, Map<String> names = new HashMap<String>(); which of the following are legal? (Choose all that apply.) A. Iterator<String> iter = names.iterator(); B. for (String s:names) C. while (String s:names) D. A, B

A

12. Suppose a source file contains a large number of import statements and one class definition. How do the imports affect the time required to load the class? A. Class loading takes no additional time. B. Class loading takes slightly more time. C. Class loading takes significantly more time.

A

12. Suppose salaries is an array containing floats. Which of the following are valid loop control statements for processing each element of salaries? A. for (float f:salaries) B. for (int i:salaries) C. for (float f::salaries) D. for (int i::salaries)

D

12. What is the value of x after the following operation is performed? x = 23 % 4; A. 23 B. 4 C. 5.3 D. 3 E. 5

C

12. When a byte is added to a char, what is the type of the result? A. byte B. char C. int D. short E. You can't add a byte to a char.

E

13. EOFException and ObjectStreamException both extend IOException. NotSerializable- Exception extends ObjectStreamException. AWTException does not extend any of these. All are checked exceptions. Suppose class AClass has a method callMe() whose declaration is void callMe() throws ObjectStreamException Which of the following may appear in a subclass of AClass? A. void callMe() B. void callMe() throws IOException C. void callMe() throws NotSerializableException D. void callMe() throws ObjectStreamException, AWTException E. A, C

C

13. Given the following code, what keyword must be used at line 4 in order to stop execution of the for loop? 1. boolean b = true; 2. for (;;) { 3. if (b) { 4. <insert code> 5. } 6. // do something 7. } A. stop B. continue C. break D. None of the above

A

13. How many locks does an object have? A. One B. One for each method C. One for each synchronized method D. One for each non-static synchronized method

B

13. Suppose class A extends Object; class B extends A; and class C extends B. Of these, only class C implements java.io.Serializable. Which of the following must be true in order to avoid an exception during deserialization of an instance of C? A. A must have a no-args constructor. B. B must have a no-args constructor. C. C must have a no-args constructor. D. There are no restrictions regarding no-args constructors.

C, D

13. Suppose interface Inty defines five methods. Suppose class Classy declares that it implements Inty but does not provide implementations for any of the five interface methods. Which is/are true? A. The class will not compile. B. The class will compile if it is declared public. C. The class will compile if it is declared abstract. D. The class may not be instantiated.

A

13. Suppose the declared type of x is a class, and the declared type of y is an interface. When is the assignment x = y; legal? A. When the type of x is Object B. When the type of x is an array C. Always D. Never

C

13. When a short is added to a float, what is the type of the result? A. short B. int C. float D. You can't add a short to a float.

C

13. When a short is added to a float, what is the type of the result? A. short B. int C. float D. You can't add a short to a float.

E

13. Which of the following are legal clone() methods in a class called Q13 that extends Object? A. public Object clone() { return super.clone(); } B. public Object clone() throws CloneNotSupportedException { return super.clone(); } C. public Q13 clone() { return (Q13)super.clone(); } D. public Q13 clone() throws CloneNotSupportedException { return (Q13)super.clone(); } E. B, D

A, C

13. Which of the following are legal import statements? A. import java.util.Vector; B. static import java.util.Vector.*; C. import static java.util.Vector.*; D. import java.util.Vector static;

E

13. Which of the following are legal? (Choose all that apply.) A. for (int i=0, j=1; i<10; i++, j++) B. for (int i=0, j=1;; i++, j++) C. for (int i=0, float j=1; ; i++, j++) D. for (String s = ""; s.length()<10; s += '!') E. A, B, D

E

13. Which of the following are true? A. An enum definition may contain the main() method of an application. B. You can call an enum's toString() method. C. You can call an enum's wait() method. D. You can call an enum's notify() method. E. All of the above

A

14. Is it possible to write code that can execute only if the current thread owns multiple locks? A. Yes. B. No.

B, E

14. ObjectStreamException extends IOException. NotSerializableException extends ObjectStreamException. AWTException does not extend any of these. All are checked exceptions. The callMe() method throws NotSerializableException.What does the following code print out? Choose all lines that are printed. try { callMe(); System.out.println("I threw"); } catch (ObjectStreamException x) { System.out.println("Object stream"); } catch (IOException x) { System.out.println("IO"); } catch (Exception x) { System.out.println("Exception"); } finally { System.out.println("Finally"); } A. I threw B. Object Stream C. IO D. Exception E. Finally

D

14. Suppose a method called finallyTest() consists of a try block, followed by a catch block, followed by a finally block. Assuming the JVM doesn't crash and the code does not execute a System.exit() call, under what circumstances will the finally block not begin to execute? A. The try block throws an exception, and the catch block also throws an exception. B. The try block throws an exception that is not handled by the catch block. C. The try block throws an exception, and the catch block calls finallyTest() in a way that causes another exception to be thrown. D. If the JVM doesn't crash and the code does not execute a System.exit() call, the finally block will always exec

C

14. Suppose class A extends Object; Class B extends A; and class C extends B. Of these, only class C implements java.io.Externalizable. Which of the following must be true in order to avoid an exception during deserialization of an instance of C? A. A must have a no-args constructor. B. B must have a no-args constructor. C. C must have a no-args constructor. D. There are no restrictions regarding no-args constructors.

A

14. Suppose the type of xarr is an array of XXX, and the type of yarr is an array of YYY. When is the assignment xarr = yarr; legal? A. Sometimes B. Always C. Never

A

14. Suppose x and y are of type TrafficLightState, which is an enum. What is the best way to test whether x and y refer to the same constant? A. if (x == y) B. if (x.equals(y)) C. if (x.toString().equals(y.toString())) D. if (x.hashCode() == y.hashCode())

B

14. What method call is used to tell a thread that it has the opportunity to run? A. wait() B. notify() C. start() D. run()

E

14. Which of the following classes implement java.util.List? A. java.util.ArrayList B. java.util.HashList C. java.util.StackList D. java.util.Stack E. A, D

D

14. Which of the following may be declared final? (Choose all that apply.) A. Classes B. Data C. Methods D. All of above

B, C

14. Which of the following may be statically imported? (Choose all that apply.) A. Package names B. Static method names C. Static field names D. Method-local variable names

D

15. While testing some code that you are developing, you notice that an ArrayIndexOutOf- BoundsException is thrown. What is the appropriate reaction? A. Enclose the offending code in a try block, with a catch block for ArrayIndexOutOfBoundsException that does nothing. B. Enclose the offending code in a try block, with a catch block for ArrayIndexOutOfBoundsException that prints out a descriptive message. C. Declare that the method that contains the offending code throws ArrayIndexOutOfBoundsException. D. None of the above.

C

16. Assertions are used to enforce all but which of the following? A. Preconditions B. Postconditions C. Exceptions D. Class invariants

E

16. Given the following code, which of the following will compile? enum Spice { NUTMEG, CINNAMON, CORIANDER, ROSEMARY; } A. Spice sp = Spice.NUTMEG; Object ob = sp; B. Spice sp = Spice.NUTMEG; Object ob = (Object)sp; C. Object ob = new Object(); Spice sp = object; D. Object ob = new Object(); Spice sp = (Spice)object; E. A, B, D

C, D

16. How is IllegalArgumentException used? A. It is thrown by the JVM when a method is called with incompatible argument types. B. It is thrown by the JVM to indicate arithmetic overflow. C. It is thrown by certain methods of certain core Java classes to indicate that preconditions have been violated. D. It should be used by programmers to indicate that preconditions of public methods have been violated. E. It should be used by programmers to indicate that preconditions of nonpublic methods have been violated.

C

16. What are the legal types for whatsMyType? short s = 10; whatsMyType = !s; A. short B. int C. There are no possible legal types.

E

16. What method of the java.io.File class can create a file on the hard drive? A. newFile() B. makeFile() C. makeNewFile() D. createFile() E. createNewFile()

A, B, E

16. Which of the following are legal argument types for a switch statement? A. byte B. int C. long D. float E. char F. String

C

16. Which of the following are legal? (Choose all that apply.) A. int a = abcd; B. int b = ABCD; C. int c = 0xabcd; - int d = 0XABCD; D. int e = 0abcd; E. int f = 0ABCD;

C, D, E

16. Which of the following are methods of the java.util.SortedMap interface? A. first B. last C. headMap D. tailMap E. subMap

D

16. Which of the following are true? A. The JVM runs until there is only one daemon thread. B. The JVM runs until there are no daemon threads. C. The JVM runs until there is only one non-daemon thread. D. The JVM runs until there are no non-daemon threads.

D

16. Which of the following operations might throw an ArithmeticException? A. + B. - C. * D. / E. None of these

D

17. How do you prevent shared data from being corrupted in a multithreaded environment? A. Mark all variables as synchronized. B. Mark all variables as volatile. C. Use only static variables. D. Access the variables only via synchronized methods.

E

17. Suppose shorty is a short and wrapped is a Short. Which of the following are legal Java state- ments? (Choose all correct options.) A. shorty = wrapped; B. wrapped = shorty; C. shorty = new Short((short)9); D. shorty = 9; E. All of the above

B

17. The developer can force garbage collection by calling System.gc(). A. True B. False

B

17. True or false: If class Y extends class X, the two classes are in different packages, and class X has a protected method called abby(), then any instance of Y may call the abby() method of any other instance of Y. A. True B. False

D

17. What is the return type of the instanceof operator? A. A reference B. A class C. An int D. A boolean

D

17. When a negative long is cast to a byte, what are the possible values of the result? A. Positive B. Zero C. Negative D. All of the above

B

17. When is it appropriate to pass a cause to an exception's constructor? A. Always B. When the exception is being thrown in response to catching of a different exception type C. When the exception is being thrown from a public method D. When the exception is being thrown from a private method

C

17. Which line of code tells a scanner called sc to use a single digit as a delimiter? A. sc.useDelimiter("d"); B. sc.useDelimiter("\d"); C. sc.useDelimiter("\\d"); D. sc.useDelimiter("d+"); E. sc.useDelimiter("\d+"); F. sc.useDelimiter("\\d+");

A, B

17. Which of the following are legal? (Choose all that apply.) A. double d = 1.2d; B. double d = 1.2D; C. double d = 1.2d5; D. double d = 1.2D5;

A, C

17. Which of the following are true? A. An anonymous inner class may implement at most one interface. B. An anonymous inner class may implement arbitrarily many interfaces. C. An anonymous inner class may extend a parent class other than Object. D. An anonymous inner class that implements one interface may extend a parent class other than Object. E. An anonymous inner class that implements several interfaces may extend a parent class other than Object.

E

17. Which of the following are true? (Choose all that apply.) A. System.out has a println() method. B. System.out has a format() method. C. System.err has a println() method. D. System.err has a format () method. E. All of the above

D

18. How can you ensure that multithreaded code does not deadlock? A. Synchronize access to all shared variables. B. Make sure all threads yield from time to time. C. Vary the priorities of your threads. D. A, B, and C do not ensure that multithreaded code does not deadlock.

A, C, D

18. Select the valid primitive data types. A. boolean B. bit C. char D. float E. All of the above

B

18. What happens when you try to compile and run the following application? 1. import java.io.*; 2. 3. public class Xxx { 4. public static void main(String[] args) { 5. try { 6. File f = new File("xxx.ser"); 7. FileOutputStream fos = new FileOutputStream(f); 8. ObjectOutputStream oos = new ObjectOutputStream(fos); 9. oos.writeObject(new Object()); 10. oos.close(); 11. fos.close(); 12. } 13. catch (Exception x) { } 14. } 15. } A. Compiler error at line 9. B. An exception is thrown at line 9. C. An exception is thrown at line 10. D. No compiler error and no exception.

E

19. Which of the following are true? (Choose all that apply.) A. When you declare a method to be synchronized, the method always synchronizes on the lock of the current object. B. When you declare a method to be synchronized, you can specify the object on whose lock the method should synchronize. C. When you declare a block of code inside a method to be synchronized, the block always synchronizes on the lock of the current object. D. When you declare a block of code inside a method to be synchronized, you can specify the object on whose lock the block should synchronize. E. A, D

A, C, D, E

19. Which of the following are valid mode strings for the RandomAccessFile constructor? (Choose all that apply.) A. "r" B. "ro" C. "rw" D. "rws" E. "rwd"

B, C

19. Which of the following may appear on the right-hand side of an instanceof operator? (Choose all that apply.) A. A reference B. A class C. An interface D. A variable of primitive type E. The name of a primitive type

A, B, E

19. Which of the following operators can perform promotion on their operands? (Choose all that apply.) A. + B. - C. ++ D. -- E. ~ F. !

E

2. Choose the valid identifiers from those listed here. (Choose all that apply.) A. BigOlLongStringWithMeaninglessName B. $int C. bytes, finalist D. $1 E. All of them

D

2. Consider the following code: 1. outer: for (int i = 0; i < 2; i++) { 2. for (int j = 0; j < 3; j++) { 3. if (i == j) { 4. continue outer; 5. } 6. System.out.println("i = " + i + " j = " + j); 7. } 8. } Which lines would be part of the output? (Choose all that apply.) A. i = 0 j = 0 B. i = 0 j = 1 C. i = 0 j = 2 D. i = 1 j = 0 E. i = 1 j = 1 F. i = 1 j = 2

E

2. Consider these classes, defined in separate source files: 1. public class Test1 { 2. public float aMethod(float a, float b) 3. throws IOException {... 4. } 5. } 1. public class Test2 extends Test1 { 2. 3. } Which of the following methods would be legal (individually) at line 2 in class Test2? (Choose all that apply.) A. float aMethod(float a, float b) {...} B. public int aMethod(int a, int b) throws Exception {...} C. public float aMethod(float a, float b) throws Exception {...} D. public float aMethod(float p, float q) {...} E. B, D

B, D, F

2. Given the following: package pack; class Sploo { public int a; public static int b; int c; static int d; public void eee() { } public static void fff() { } } Which of the following features of class Sploo may be accessed by a class, in package pack, as a result of the following import? import static pack.Sploo.*; A. a B. b C. c D. d E. eee() F. fff()

B, C

2. Which of the following expressions are legal? (Choose all that apply.) A. int x = 6; x = !x; B. int x = 6; if (!(x > 3)) {} C. int x = 6; x = ~x;

B

2. Which of the following statements is true? A. An abstract class may not have any final methods. B. A final class may not have any abstract methods

D

2. Which of the statements below are true? A. When you construct an instance of File, if you do not use the file-naming semantics of the local machine, the constructor will throw an IOException. B. When you construct an instance of File, if the corresponding file does not exist on the local file system, one will be created. C. When an instance of File is garbage collected, the corresponding file on the local file system is deleted. D. None of the above.

E

2. Which one line in the following code will not compile? 1. byte b = 5; 2. char c = '5'; 3. short s = 55; 4. int i = 555; 5. float f = 555.5f; 6. b = s; 7. i = c; 8. if (f > b) 9. f = i; A. Line 1 B. Line 2 C. Line 3 D. Line 4 E. Line 6 F. Line 5 G. Line 7 H. Line 8 I. Line 9

C

2. Which one statement is always true about the following application? 1. class HiPri extends Thread { 2. HiPri() { 3. setPriority(10); 4. } 5. 6. public void run() { 7. System.out.println( 8. "Another thread starting up."); 9. while (true) { } 10. } 11. 12. public static void main(String args[]) { 13. HiPri hp1 = new HiPri(); 14. HiPri hp2 = new HiPri(); 15. HiPri hp3 = new HiPri(); 16. hp1.start(); 17. hp2.start(); 18. hp3.start(); 19. } 20. } A. When the application is run, thread hp1 will execute; threads hp2 and hp3 will never get the CPU. B. When the application is run, thread hp1 will execute to completion, thread hp2 will execute to completion, then thread hp3 will execute to completion. C. When the application is run, all three threads (hp1, hp2, and hp3) will execute concurrently, taking time-sliced turns in the CPU. D. None of the above scenarios can be guaranteed to happen in all cases.

C

2. Which one statement is true about the following code? 1. String s1 = "abc" + "def"; 2. String s2 = new String(s1); 3. if (s1 == s2) 4. System.out.println("== succeeded"); 5. if (s1.equals(s2)) 6. System.out.println(".equals() succeeded"); A. Lines 4 and 6 both execute. B. Line 4 executes and line 6 does not. C. Line 6 executes and line 4 does not. D. Neither line 4 nor line 6 executes.

B

20. Suppose you want to create a custom thread class by extending java.lang.Thread in order to provide some special functionality. Which of the following must you do? A. Declare that your class implements java.lang.Runnable. B. Override run(). C. Override start(). D. Make sure that all access to all data is via synchronized methods.

C

20. Suppose you want to read a file that was not created by a Java program. The file contains lines of 8-bit text, and the 8-bit encoding represents the local character set, as represented by the cur- rent default locale. The lines are separated by newline characters. Which strategy reads the file and produces Java strings? A. Create a RandomAccessFile instance and use its readText() method. B. Create a RandomAccessFile instance and use its readUTF() method. C. Create a FileReader instance. Pass it into the constructor of LineNumberReader. Use LineNumberReader's readLine() method. D. Create a FileInputStream instance. Pass it into the constructor of LineNumberReader. Use LineNumberReader's readLine() method. E. Create a FileInputStream instance. Pass it into the constructor of DataInputStream. Use DataInputStream's readLine() method.

E

20. This question involves IOException, AWTException, and EOFException. They are all checked exception types. IOException and AWTException extend Exception, and EOFException extends IOException. Suppose class X contains the following method: void doSomething() throws IOException{ ... } Which of the following methods may appear in class Y, which extends X? A. void doSomething() { ... } B. void doSomething() throws AWTException { ... } C. void doSomething() throws EOFException { ... } D. void doSomething() throws IOException, EOFException { ... } E. A, C, D

D

20. What does the following code print? public class A { static int x; public static void main(String[] args) { A that1 = new A(); A that2 = new A(); that1.x = 5; that2.x = 1000; x = -1; System.out.println(x); } } A. 0 B. 5 C. 1000 D. -1

D

20. What is -50 >> 1? A. A negative number with very large magnitude. B. A positive number with very large magnitude. C. -100 D. -25 E. 100 F. 25

A

20. What is the difference between the rules for method-call conversion and the rules for assignment conversion? A. There is no difference; the rules are the same. B. Method-call conversion supports narrowing, assignment conversion does not. C. Assignment conversion supports narrowing, method-call conversion does not. D. Method-call conversion supports narrowing if the method declares that it throws ClassCastException.

A

20. What is the value of x after the following line is executed? x = 32 * (31 - 10 * 3); A. 32 B. 31 C. 3 D. 704 E. None of the above

E

20. When is it appropriate to write code that constructs and throws an error? A. When a public method's preconditions are violated B. When a public method's postconditions are violated C. When a nonpublic method's preconditions are violated D. When a nonpublic method's postconditions are violated E. Never

B, D

20. Which of the following are true? (Choose all that apply.) A. Primitives are passed by reference. B. Primitives are passed by value. C. References are passed by reference. D. References are passed by value.

C

20. Which of the following are valid arguments to the DataInputStream constructor? A. File B. FileReader C. FileInputStream D. RandomAccessFile

E

20. Which of the following statements are true? A. StringBuilder is generally faster than StringBuffer. B. StringBuffer is generally faster than StringBuilder. C. StringBuilder is threadsafe; StringBuffer is not. D. StringBuffer is threadsafe; StringBuilder is not. E. A, D

A

21. A StringBuffer is slower than a StringBuilder, but a StringBuffer is threadsafe. A. True B. False

B, E

21. What interfaces can be implemented in order to create a class that can be serialized? (Choose all that apply.) A. No interfaces need to be implemented. All classes can be serialized. B. Have the class declare that it implements java.io.Serializable. There are no methods in the interface. C. Have the class declare that it implements java.io.Serializable, which defines two methods: readObject and writeObject. D. Have the class declare that it implements java.io.Externalizable, which defines two methods: readObject and writeObject. E. Have the class declare that it implements java.io.Externalizable, which defines two methods: readExternal and writeExternal

D

22. Select the list of primitives ordered in smallest to largest bit size representation. A. boolean, char, byte, double B. byte, int, float, char C. char, short, long, float D. char, int, float, long E. None of the above

D

22. Suppose you are writing a class that will provide custom deserialization. The class implements java.io.Serializable (not java.io.Externalizable). What access mode should the readObject() method have? A. public B. protected C. default D. private

E

23. Suppose you want to create a class that compiles and can be serialized and deserialized without causing an exception to be thrown. Which statements are true regarding the class? (Choose all correct options.) A. If the class implements java.io.Serializable and does not implement java.io.Externalizable, it must have a no-args constructor. B. If the class implements java.io.Externalizable, it must have a no-args constructor. C. If the class implements java.io.Serializable and does not implement java.io.Externalizable, its nearest superclass that doesn't implement Serializable must have a no-args constructor. D. If the class implements java.io.Externalizable, its nearest superclass that doesn't implement Externalizable must have a no-args constructor. E. B, C

D

23. Which class provides locale-sensitive text formatting for date and time information? A. java.util.TimeFormat B. java.util.DateFormat C. java.text.TimeFormat D. java.text.DateFormat

B, D

3. Which of the following signatures are valid for the main() method entry point of an application? A. public static void main() B. public static void main(String arg[]) C. public void main(String [] arg) D. public static void main(String[] args) E. public static int main(String [] arg)

E

24. Suppose you want to use a DateFormat to format an instance of Date. What factors influence the string returned by DateFormat's format() method? A. The operating system B. The style, which is one of SHORT, MEDIUM, or LONG C. The style, which is one of SHORT, MEDIUM, LONG, or FULL D. The locale E. C, D

B

24. The following line of code is valid. int x = 9; byte b = x; A. True B. False

A

25. How do you generate a string representing the value of a float f in a format appropriate for a locale loc? A. NumberFormat nf = NumberFormat.getInstance(loc); String s = nf.format(f); B. NumberFormat nf = new NumberFormat(loc); String s = nf.format(f); C. NumberFormat nf = NumberFormat.getInstance(); String s = nf.format(f, loc); D. NumberFormat nf = new NumberFormat(loc); String s = nf.format(f, loc);

A, B, C

25. Which of the following code snippets compile? A. Integer i = 7; B. Integer i = new Integer(5); int j = i; C. byte b = 7; D. int i = 7; byte b = i; E. None of the above

C

26. Given the following code: 1. String scanMe = "aeiou9876543210AEIOU"; 2. Scanner scanner = new Scanner(scanMe); 3. String delim = ?????; // WHAT GOES HERE? 4. scanner.useDelimiter(delim); 5. while (scanner.hasNext()) 6. System.out.println(scanner.next()); What code at line 3 produces the following output? aeiou AEIOU A. String delim = "d+"; B. String delim = "\d+"; C. String delim = "\\d+"; D. String delim = "d*"; E. String delim = "\d*"; F. String delim = "\\d*";

D

26. What will be the output of the following code? public class StringTest { public static void main(String [] a) { String s1 = "test string"; String s2 = "test string"; if (s1 == s2) { System.out.println("same"); } else { System.out.println("different"); } } } A. The code will compile but not run. B. The code will not compile. C. "different" will be printed out to the console. D. "same" will be printed out to the console. E. None of the above.

B

27. Java arrays always start at index 1. A. True B. False

D

27. Which line prints double d in a left-justified field that is 20 characters wide, with 15 characters to the right of the decimal point? A. System.out.format("%20.5f", d); B. System.out.format("%20.15f", d); C. System.out.format("%-20.5f", d); D. System.out.format("%-20.15f", d);

A, D

28. Suppose MyThread extends java.lang.Thread, and MyRunnable implements java.lang .Runnable (but does not extend Thread). Both classes have no-args constructors. Which of the following cause a thread in the JVM to begin execution? (Choose all correct options.) A. (new MyThread()).start(); B. (new MyThread()).run(); C. (new MyRunnable()).run(); D. (new Thread(new MyRunnable())) E. .start();

C

28. Which of the following statements accurately describes how variables are passed to methods? A. Arguments are always passed by value. B. Arguments are always passed by reference. C. Arguments that are primitive type are passed by value. D. Arguments that are passed with the & operator are passed by reference.

D

29. How do you change the value that is encapsulated by a wrapper class after you have instan- tiated it? A. Use the setXXX() method defined for the wrapper class. B. Use the parseXXX() method defined for the wrapper class. C. Use the equals() method defined for the wrapper class. D. None of the above.

B

3. A thread wants to make a second thread ineligible for execution. To do this, the first thread can call the yield() method on the second thread. A. True B. False

B, C, E

3. Given the following: public abstract class Abby { abstract provideMe(); } public class SubAbby extends Abby { } Which statements are true? A. Abby generates a compiler error. B. SubAbby generates a compiler error. C. If SubAbby were declared abstract, it would compile without error. D. If SubAbby were declared abstract, it could be instantiated. E. Abby is a legal type for variables.

D

3. Suppose you want to write a class that offers static methods to compute hyperbolic trigonometric functions. You decide to subclass java.lang.Math and provide the new functionality as a set of static methods. Which one statement is true about this strategy? A. The strategy works. B. The strategy works, provided the new methods are public. C. The strategy works, provided the new methods are not private. D. The strategy fails because you cannot subclass java.lang.Math. E. The strategy fails because you cannot add static methods to a subclass.

A

3. What is the minimal modification that will make this code compile correctly? 1. final class Aaa 2. { 3. int xxx; 4. void yyy() { xxx = 1; } 5. } 6. 7. 8. class Bbb extends Aaa 9. { 10. final Aaa finalref = new Aaa(); 11. 12. final void yyy() 13. { 14. System.out.println("In method yyy()"); 15. finalref.xxx = 12345; 16. } 17. } A. On line 1, remove the final modifier. B. On line 10, remove the final modifier. C. Remove line 15. D. On lines 1 and 10, remove the final modifier. E. The code will compile as is. No modification is needed.

D

3. What keyword is used to prevent an object from being serialized? A. private B. volatile C. protected D. transient E. None of the above

D

3. Which of the following are legal loop constructions? (Choose all that apply.) A. while (int i<7) { i++; System.out.println("i is " + i); } B. int i = 3; while (i) { System.out.println("i is " + i); } C. int j = 0; for (int k=0, j+k != 10; j++,k++) { System.out.println("j=" + j + ", k=" + k); } D. int j=0; do { System.out.println("j=" + j++); if (j==3) continue loop; } while (j<10);

E, F

3. You have been given a design document for a veterinary registration system for implementation in Java. It states: "A pet has an owner, a registration date, and a vaccination-due date. A cat is a pet that has a flag indicating whether it has been neutered, and a textual description of its markings." Given that the Pet class has already been defined, which of the following fields would be appropriate for inclusion in the Cat class as members? (Choose all that apply.) A. Pet thePet; B. Date registered; C. Date vaccinationDue; D. Cat theCat; E. boolean neutered; F. String markings;

A

30. Suppose you are writing a class that provides custom deserialization. The class implements java.io.Serializable (and not java.io.Externalizable). What method should imple- ment the custom deserialization, and what is its access mode? A. private readObject B. public readObject() C. private readExternal() D. public readExternal()

C, E

31. Suppose threads aThread and bThread are both accessing a shared object named sharedOb, and aThread has just executed: sharedOb.wait(); What code can bThread execute in order to get aThread out of the waiting state, no matter what other conditions prevail? A. aThread.notify(); B. aThread.notifyAll(); C. aThread.interrupt(); D. sharedOb.notify(); E. sharedOb.notifyAll();

E

33. Suppose class Home has methods chopWood() and carryWater(); it also has a method called chopWoodAndCarryWater(), which just calls the other two methods. Which statements are true? (Choose all that apply.) A. chopWoodAndCarryWater() is an example of appropriate cohesion. B. chopWoodAndCarryWater() is an example of inappropriate cohesion. C. chopWoodAndCarryWater() is an example of appropriate coupling. D. chopWoodAndCarryWater() is an example of inappropriate coupling. E. B, D

B, C, D

34. Suppose class Lemon extends class Citrus. Given the following code: Lemon lem = new Lemon(); Citrus cit = new Citrus(); Which lines compile without error? (Choose all that apply.) A. lem = cit; B. cit = lem; C. lem = (Lemon)cit; D. cit = (Citrus)lem; E. cit = (Object)lem;

E

35. Suppose classes Lemon and Grapefruit extend class Citrus. Which statements are true regard- ing the following code? 1. Grapefruit g = new Grapefruit(); 2. Citrus c = (Citrus)g; 3. Lemon lem = (Lemon)c; A. The cast in line 2 is not necessary. B. Line 3 causes a compiler error. C. The code compiles, and throws an exception at line 3. D. The code compiles and runs without throwing any exceptions. E. A, C

E

36. Suppose class aaa.Aaa has a method called callMe(). Suppose class bbb.Bbb, which extends aaa.AAA, wants to override callMe(). Which access modes for callMe() in aaa.AAA will allow this? A. public B. protected C. default D. private E. A, B

B

37. What happens when you try to compile the following code and run the Zebra application? class Animal { float weight; Animal(float weight) { this.weight = weight; } } class Zebra extends Animal { public static void main(String[] args) { Animal a = new Animal(222.2f); Zebra z = new Zebra(); } } A. Class Animal generates a compiler error. B. Class Zebra generates a compiler error. C. The code compiles without error. The application throws an exception when the Animal constructor is called. D. The code compiles without error. The application throws an exception when the Zebra constructor is called. E. The code compiles and runs without error.

E

38. Given the following code: 1. class Xyz { 2. float f; 3. Xyz() { 4. ??? // What goes here? 5. } 6. Xyz(float f) { 7. this.f = f; 8. } 9. } What code at line 4 results in a class that compiles? A. super(); B. this(1.23f); C. this(1.23f); super(); D. super(1.23f); this(1.23f); E. A, B

A

39. What relationship does the extends keyword represent? A. "is a" B. "has a" C. Polymorphism D. Multivariance E. Overloading

D

4. A thread's run() method includes the following lines: 1. try { 2. sleep(100); 3. } catch (InterruptedException e) { } Assuming the thread is not interrupted, which one of the following statements is correct? A. The code will not compile, because exceptions cannot be caught in a thread's run() method. B. At line 2, the thread will stop running. Execution will resume in, at most, 100 milliseconds. C. At line 2, the thread will stop running. It will resume running in exactly 100 milliseconds. D. At line 2, the thread will stop running. It will resume running some time after 100 milliseconds have elapsed.

A

4. An abstract class can contain methods with declared bodies. A. True B. False

A

4. Which one statement is true about the following code fragment? 1. import java.lang.Math; 2. Math myMath = new Math(); 3. System.out.println("cosine of 0.123 = " + 4. myMath.cos(0.123)); A. Compilation fails at line 2. B. Compilation fails at line 3 or 4. C. Compilation succeeds, although the import on line 1 is not necessary. During execution, an exception is thrown at line 3 or 4. D. Compilation succeeds. The import on line 1 is necessary. During execution, an exception is thrown at line 3 or 4. E. Compilation succeeds and no exception is thrown during execution.

C

4. You have been given a design document for a veterinary registration system for implementation in Java. It states: "A pet has an owner, a registration date, and a vaccination-due date. A cat is a pet that has a flag indicating if it has been neutered, and a textual description of its markings." Given that the Pet class has already been defined and you expect the Cat class to be used freely throughout the application, how would you make the opening declaration of the Cat class, up to but not including the first opening brace? Use only these words and spaces: boolean, Cat, class, Date, extends, Object, Owner, Pet, private, protected, public, String. A. protected class Cat extends Owner B. public class Cat extends Object C. public class Cat extends Pet D. private class Cat extends Pet

A, E

41. Given the following class: class Xyzzy { int a, b; public boolean equals(Object x) { Xyzzy that = (Xyzzy)x; return this.a == that.a; } Which methods below honor the hash code contract? A. public int hashCode() { return a; } B. public int hashCode() { return b; } C. public int hashCode() { return a+b; } D. public int hashCode() { return a*b; } E. public int hashCode() { return (int)Math.random(); }

A

42. Give the following declarations: Vector plainVec; Vector<String> fancyVec; If you want a vector in which you know you will only store strings, what are the advantages of using fancyVec rather than plainVec? A. Attempting to add anything other than a string to fancyVec results in a compiler error. B. Attempting to add anything other than a string to fancyVec causes a runtime exception to be thrown. C. Attempting to add anything other than a string to fancyVec causes a checked exception to be thrown. D. Adding a string to fancyVec takes less time than adding one to plainVec. E. The methods of fancyVec are synchronized.

D

43. The declaration of the java.util.Collection interface is interface Collection <E> The addAll() method of that interface takes a single argument, which is a reference to a collection whose elements are compatible with E. What is the declaration of the addAll() method? A. public boolean addAll(Collection c) B. public boolean addAll(Collection c extends E) C. public boolean addAll(Collection ? extends E) D. public boolean addAll(Collection<? extends E> c)

E

44. The java.util.Arrays class has a binarySearch(int[] arr, int key) method. Which statements are true regarding this method? (Choose all that apply.) A. The method is static. B. The return value is the index in the array of key. C. The elements of the array must be sorted when the method is called. D. After the method returns, the elements of the array are sorted, even if they weren't sorted before the call. E. A, B, C

E

45. Given the following class: package ocean; public class Fish { protected int size; protected void swim() { } } Which of the following may appear in a subclass of Fish named Tuna that is not in the ocean package? A. void swim() { } B. public void swim() { } C. size = 12; D. (new Tuna()).size = 12; E. B, C

A

46. Given the following class: public class App { public static void main(String[] args) { System.out.println(args.length); } } Assuming App.class is stored in an appropriate location in file appjar.jar, what is printed when you type the following command line? java -cp appjar.jar -ea App 1 2 3 4 A. 4 B. 5 C. 6 D. 7 E. 8 F. 9

C

47. Given the following classes: public class Wrapper { public int x; } public class Tester { private static void bump(int n, Wrapper w) { n++; w.x++; } public static void main(String[] args) { int n = 10; Wrapper w = new Wrapper(); w.x = 10; bump(n, w); // Now what are n and w.x? } } When the application runs, what are the values of n and w.x after the call to bump() in the main() method? A. n is 10, w.x is 10 B. n is 11, w.x is 10 C. n is 10, w.x is 11 D. n is 11, w.x is 11

A

48. When does the string created on line 2 become eligible for garbage collection? 1. String s = "aaa"; 2. String t = new String(s); 3. t += "zzz"; 4. t = t.substring(0); 5. t = null; A. After line 3 B. After line 4 C. After line 5 D. The string created on line 2 does not become eligible for garbage collection in this code.

E

49. Suppose you want to run the following command line on a Windows system: java -classpath somewhere;elsewhere aaa.bbb.MyApplication On a Unix system the command line would be: java -classpath somewhere:elsewhere aaa.bbb.MyApplication Assume the CLASSPATH variable is not set. Which must be true in order for the application to run? A. Class MyApplication must contain the statement package aaa.bbb;. B. Class MyApplication must be in a directory named aaa and must contain the statement package bbb;. C. Class MyApplication must contain either the statement package somewhere.aaa.bbb; or the statement package elsewhere.aaa.bbb;. D. The file MyApplication.class must be found either in somewhere\aaa\bbb or in elsewhere\aaa\bbb. (Substitute forward slashes for backslashes on a Unix system.) E. A, D

E

5. A monitor called mon has 10 threads in its waiting pool; all these waiting threads have the same priority. One of the threads is thr1. How can you notify thr1 so that it alone moves from the Waiting state to the Ready state? A. Execute notify(thr1); from within synchronized code of mon. B. Execute mon.notify(thr1); from synchronized code of any object. C. Execute thr1.notify(); from synchronized code of any object. D. Execute thr1.notify(); from any code (synchronized or not) of any object. E. You cannot specify which thread will get notified.

A, B, C, E

8. Consider the following definition: 1. public class Outer { 2. public int a = 1; 3. private int b = 2; 4. public void method(final int c) { 5. int d = 3; 6. class Inner { 7. private void iMethod(int e) { 8. 9. } 10. } 11. } 12. } Which variables can be referenced at line 8? (Choose all that apply.) A. a B. b C. c D. d E. e

D

5. Consider the following class: 1. class Cruncher { 2. void crunch(int i) { 3. System.out.println("int version"); 4. } 5. void crunch(String s) { 6. System.out.println("String version"); 7. } 8. 9. public static void main(String args[]) { 10. Cruncher crun = new Cruncher(); 11. char ch = 'p'; 12. crun.crunch(ch); 13. } 14. } Which of the following statements is true? (Choose one.) A. Line 5 will not compile, because void methods cannot be overridden. B. Line 12 will not compile, because no version of crunch() takes a char argument. C. The code will compile but will throw an exception at line 12. D. The code will compile and produce the following output: int version. E. The code will compile and produce the following output: String version.

C

5. Consider the following classes, declared in separate source files: 1. public class Base { 2. public void method(int i) { 3. System.out.print("Value is " + i); 4. } 5. } 1. public class Sub extends Base { 2. public void method(int j) { 3. System.out.print("This value is " + j); 4. } 5. public void method(String s) { 6. System.out.print("I was passed " + s); 7. } 8. public static void main(String args[]) { 9. Base b1 = new Base(); 10. Base b2 = new Sub(); 11. b1.method(5); 12. b2.method(6); 13. } 14. } What output results when the main method of the class Sub is run? A. Value is 5Value is 6 B. This value is 5This value is 6 C. Value is 5This value is 6 D. This value is 5Value is 6 E. I was passed 5I was passed 6

A, E

5. Consider the following line of code: int[] x = new int[25]; After execution, which statements are true? (Choose all that apply.) A. x[24] is 0 B. x[24] is undefined C. x[25] is 0 D. x[0] is null E. x.length is 25

C

5. Given a class with a public variable theTint of type Color, which of the following methods are consistent with the JavaBeans naming standards? A. public Color getColor() B. public Color getTint() C. public Color getTheTint() D. public Color gettheTint() E. public Color get_theTint()

C

5. How many bytes does the following code write to file dest? 1. try { 2. FileOutputStream fos = newFileOutputStream("dest"); 3. DataOutputStream dos = new DataOutputStream(fos); 4. dos.writeInt(3); 5. dos.writeDouble(0.0001); 6. dos.close(); 7. fos.close(); 8. } 9. catch (IOException e) { } A. 2 B. 8 C. 12 D. 16 E. The number of bytes depends on the underlying system.

E

5. Select the order of access modifiers from least restrictive to most restrictive. A. public, private, protected, default B. default, protected, private, public C. public, default, protected, private D. default, public, protected, private E. public, protected, default, private

A

5. What is -8 % 5? A. -3 B. 3 C. -2 D. 2

E

5. Which one statement is true about the following code fragment? 1. String s = "abcde"; 2. StringBuffer s1 = new StringBuffer("abcde"); 3. if (s.equals(s1)) 4. s1 = null; 5. if (s1.equals(s)) 6. s = null; A. Compilation fails at line 1 because the String constructor must be called explicitly. B. Compilation fails at line 3 because s and s1 have different types. C. Compilation succeeds. During execution, an exception is thrown at line 3. D. Compilation succeeds. During execution, an exception is thrown at line 5. E. Compilation succeeds. No exception is thrown during execution.

D

5. Which statement is true about the following code fragment? 1. int j = 2; 2. switch (j) { 3. case 2: 4. System.out.println("value is two"); 5. case 2 + 1: 6. System.out.println("value is three"); 7. break; 8. default: 9. System.out.println("value is " + j); 10. break; 11. } A. The code is illegal because of the expression at line 5. B. The acceptable types for the variable j, as the argument to the switch() construct, could be any of byte, short, int, or long. C. The output would be the text value is two. D. The output would be the text value is two followed by the text value is three. E. The output would be the text value is two, followed by the text value is three, fol- lowed by the text value is 2.

E

5. Which statement is true about this application? 1. class StaticStuff 2 { 3. static int x = 10; 4. 5. static { x += 5; } 6. 7. public static void main(String args[]) 8. { 9. System.out.println("x = " + x); 10. } 11. 12. static {x /= 5; } 13. } A. Lines 5 and 12 will not compile because the method names and return types are missing. B. Line 12 will not compile because you can only have one static initializer. C. The code compiles and execution produces the output x = 10. D. The code compiles and execution produces the output x = 15. E. The code compiles and execution produces the output x = 3.

D

50. What is -15 % -10? A. 0 B. 5 C. 10 D. -5 E. -1

D

6. Consider the following application: 1. class Q6 { 2. public static void main(String args[]) { 3. Holder h = new Holder(); 4. h.held = 100; 5. h.bump(h); 6. System.out.println(h.held); 7. } 8. } 9. 10. class Holder { 11. public int held; 12. public void bump(Holder theHolder) { 13. theHolder.held++; } 14. } 15. } What value is printed out at line 6? A. 0 B. 1 C. 100 D. 101

B, C

6. Consider the following class definition: 1. public class Test extends Base { 2. public Test(int j) { 3. } 4. public Test(int j, int k) { 5. super(j, k); 6. } 7. } Which of the following are legitimate calls to construct instances of the Test class? (Choose all that apply.) A. Test t = new Test(); B. Test t = new Test(1); C. Test t = new Test(1, 2); D. Test t = new Test(1, 2, 3); E. Test t = (new Base()).new Test(1);

A

6. If you attempt to compile and execute the following application, will it ever print out the message In xxx? 1. class TestThread3 extends Thread { 2. public void run() { 3. System.out.println("Running"); 4. System.out.println("Done"); 5. } 6. 7. private void xxx() { 8. System.out.println("In xxx"); 9. } 10. 11. public static void main(String args[]) { 12. TestThread3 ttt = new TestThread3(); 13. ttt.xxx(); 14. ttt.start(); 12. } 13. } A. Yes B. No

A

6. In the following code fragment, after execution of line 1, sbuf references an instance of the StringBuffer class. After execution of line 2, sbuf still references the same instance. 1. StringBuffer sbuf = new StringBuffer("abcde"); 2. sbuf.insert(3, "xyz"); A. True B. False

B

6. What does the following code fragment print out at line 9? 1. FileOutputStream fos = new FileOutputStream("xx"); 2. for (byte b=10; b<50; b++) 3. fos.write(b); 4. fos.close(); 5. RandomAccessFile raf = new RandomAccessFile("xx", "r"); 6. raf.seek(10); 7. int i = raf.read(); 8. raf.close() 9. System.out.println("i = " + i); A. The output is i = 30. B. The output is i = 20. C. The output is i = 10. D. There is no output because the code throws an exception at line 1. E. There is no output because the code throws an exception at line 5.

B

6. What is 7 % -4? A. -3 B. 3 C. -4 D. 4

C

6. Which access modifier allows you to access method calls in libraries not created in Java? A. public B. static C. native D. transient E. volatile

B

6. Which of the following statements are true regarding the following method? void callMe(String... names) { } A. It doesn't compile. B. Within the method, names is an array containing Strings. C. Within the method, names is a list containing Strings. D. The method may be called only from within the enclosing class.

D

6. Which of the following statements is true? A. Object references can be converted in assignments but not in method calls. B. Object references can be converted in method calls but not in assignments. C. Object references can be converted in both method calls and assignments, but the rules governing these conversions are very different. D. Object references can be converted in both method calls and assignments, and the rules governing these conversions are identical. E. Object references can never be converted.

E

6. Which statement is true about this code? 1. class HasStatic 2. { 3. private static int x = 100; 4. 5. public static void main(String args[]) 6. { 7. HasStatic hs1 = new HasStatic(); 8. hs1.x++; 9. HasStatic hs2 = new HasStatic(); 10. hs2.x++; 11. hs1 = new HasStatic(); 12. hs1.x++; 13. HasStatic.x++; 14. System.out.println("x = " + x); 15. } 16. } A. Line 8 will not compile because it is a static reference to a private variable. B. Line 13 will not compile because it is a static reference to a private variable. C. The program compiles and the output is x = 102. D. The program compiles and the output is x = 103. E. The program compiles and the output is x = 104.

B

7. A Java monitor must either extend Thread or implement Runnable. A. True B. False

A, D

7. A file is created with the following code: 1. FileOutputStream fos = new FileOutputStream("datafile"); 2. DataOutputStream dos = new DataOutputStream(fos); 3. for (int i=0; i<500; i++) 4. dos.writeInt(i); You would like to write code to read back the data from this file. Which solutions will work? (Choose all that apply.) A. Construct a FileInputStream, passing the name of the file. Onto the FileInputStream, chain a DataInputStream, and call its readInt() method. B. Construct a FileReader, passing the name of the file. Call the file reader's readInt() method. C. Construct a PipedInputStream, passing the name of the file. Call the piped input stream's readInt() method. D. Construct a RandomAccessFile, passing the name of the file. Call the random access file's readInt() method. E. Construct a FileReader, passing the name of the file. Onto the FileReader, chain a DataInputStream, and call its readInt() method.

E

7. Consider the following class definition: 1. public class Test extends Base { 2. public Test(int j) { 3. } 4. public Test(int j, int k) { 5. super(j, k); 6. } 7. } Which of the following forms of constructor must exist explicitly in the definition of the Base class? Assume Test and Base are in the same package. (Choose all that apply.) A. Base() { } B. Base(int j) { } C. Base(int j, int k) { } D. Base(int j, int k, int l) { } E. A, C

C

7. Consider the following code. Which line will not compile? 1. Object ob = new Object(); 2. String[] stringarr = new String[50]; 3. Float floater = new Float(3.14f); 4. ob = stringarr; 5. ob = stringarr[5]; 6. floater = ob; 7. ob = floater; A. Line 4 B. Line 5 C. Line 6 D. Line 7

D

7. Given the following code, and making no other changes, which combination of access modifiers (public, protected, or private) can legally be placed before aMethod() on line 3 and be placed before aMethod() on line 8? 1. class SuperDuper 2. { 3. void aMethod() { } 4. } 5. 6. class Sub extends SuperDuper 7. { 8. void aMethod() { } 9. } A. line 3: public; line 8: private B. line 3: protected; line 8: private C. line 3: default; line 8: private D. line 3: private; line 8: protected E. line 3: public; line 8: protected

C, D, E

7. Given the following: public class Food { } public class Fruit extends Food { } public class Citrus extends Fruit { } public class Pomelo extends Citrus { } public class SuperDuper { public Fruit feedMe() { return new Fruit(); } } public class Subby extends SuperDuper { public ????? feedMe() { return new Pomelo (); } } Which of the following are legal return types for feedMe() in class Subby? A. Object B. Food C. Fruit D. Citrus E. Pomelo

A

7. In the following code fragment, after execution of line 1, sbuf references an instance of the StringBuffer class. After execution of line 2, sbuf still references the same instance. 1. StringBuffer sbuf = new StringBuffer("abcde"); 2. sbuf.append("xyz"); A. True B. False

B

7. What results from running the following code? 1. public class Xor { 2. public static void main(String args[]) { 3. byte b = 10; // 00001010 binary 4. byte c = 15; // 00001111 binary 5. b = (byte)(b ^ c); 6. System.out.println("b contains " + b); 7. } 8. } A. The output: b contains 10 B. The output: b contains 5 C. The output: b contains 250 D. The output: b contains 245

D

7. Which of the following statements are true? A. A final object's data cannot be changed. B. A final class can be subclassed. C. A final method cannot be overloaded. D. A final object cannot be reassigned a new address in memory. E. None of the above.

D

8. Consider the following code: 1. Dog rover, fido; 2. Animal anim; 3. 4. rover = new Dog(); 5. anim = rover; 6. fido = (Dog)anim; Which of the following statements is true? (Choose one.) A. Line 5 will not compile. B. Line 6 will not compile. C. The code will compile but will throw an exception at line 6. D. The code will compile and run. E. The code will compile and run, but the cast in line 6 is not required and can be eliminated.

C

9. This question concerns the following class definition: 1. package abcde; 2. 3. public class Bird { 4. protected static int referenceCount = 0; 5. public Bird() { referenceCount++; } 6. protected void fly() { /* Flap wings, etc. */ } 7. static int getRefCount() { return referenceCount; } 8. } Which statement is true about class Bird and the following class Parrot? 1. package abcde; 2. 3. class Parrot extends abcde.Bird { 4. public void fly() { 5. /* Parrot-specific flight code. */ 6. } 7. public int getRefCount() { 8. return referenceCount; 9. } 10. } A. Compilation of Parrot.java fails at line 4 because method fly() is protected in the superclass, and classes Bird and Parrot are in the same package. B. Compilation of Parrot.java fails at line 4 because method fly() is protected in the superclass and public in the subclass, and methods may not be overridden to be more public. C. Compilation of Parrot.java fails at line 7 because method getRefCount() is static in the superclass, and static methods may not be overridden to be nonstatic. D. Compilation of Parrot.java succeeds, but a runtime exception is thrown if method fly() is ever called on an instance of class Parrot. E. Compilation of Parrot.java succeeds, but a runtime exception is thrown if method getRefCount() is ever called on an instance of class Parrot.

B

9. What does the following code do? Integer i = null; if (i != null & i.intValue() == 5) System.out.println("Value is 5"); A. Prints "Value is 5". B. Throws an exception.

D

9. What is the range of values that can be assigned to a variable of type short? A. Depends on the underlying hardware B. 0 through 2^16 − 1 C. 0 through 2^32 − 1 D. −2^15 through 2^15 − 1 E. −2^31 through 2^31 − 1

E

9. Which of the following are appropriate situations for assertions? A. Preconditions of a public method B. Postconditions of a public method C. Preconditions of a private method D. Postconditions of a private method E. B, C, D

B

9. Which of the following keywords is used to invoke a method in the parent class? A. this B. super C. final D. static

B

9. Which of the following statements about threads is true? A. Every thread starts executing with a priority of 5. B. Threads inherit their priority from their parent thread. C. Threads are guaranteed to run with the priority that you set using the setPriority() method. D. Thread priority is an integer ranging from 1 to 100.

A

9. Which of the following statements are true? (Choose all that apply.) A. Given that Inner is a nonstatic class declared inside a public class Outer and that appro- priate constructor forms are defined, an instance of Inner can be constructed like this: new Outer().new Inner() B. If an anonymous inner class inside the class Outer is defined to implement the interface ActionListener, it can be constructed like this: new Outer().new ActionListener() C. Given that Inner is a nonstatic class declared inside a public class Outer and that appro- priate constructor forms are defined, an instance of Inner can be constructed in a static method like this: new Inner() D. An anonymous class instance that implements the interface MyInterface can be constructed and returned from a method like this: 1. return new MyInterface(int x) { 2. int x; 3. public MyInterface(int x) { 4. this.x = x;5. }6. };

A, B

9. Which of the following types are legal arguments of a switch statement? A. enums B. bytes C. longs D. floats E. strings

E

9. You execute the following code in an empty directory. What is the result? 1. File f1 = new File("dirname"); 2. File f2 = new File(f1, "filename"); A. A new directory called dirname is created in the current working directory. B. A new directory called dirname is created in the current working directory. A new file called filename is created in directory dirname. C. A new directory called dirname and a new file called filename are created, both in the current working directory. D. A new file called filename is created in the current working directory. E. No directory is created, and no file is created.

E

Consider the following code: 1. Cat sunflower; 2. Washer wawa; 3. SwampThing pogo; 4. 5. sunflower = new Cat(); 6. wawa = sunflower; 7. pogo = (SwampThing)wawa; Which of the following statements is true? (Choose one.) A. Line 6 will not compile; an explicit cast is required to convert a Cat to a Washer. B. Line 7 will not compile, because you cannot cast an interface to a class. C. The code will compile and run, but the cast in line 7 is not required and can be eliminated. D. The code will compile but will throw an exception at line 7, because runtime conversion from an interface to a class is not permitted. E. The code will compile but will throw an exception at line 7, because the runtime class of wawa cannot be converted to type SwampThing.

A, C, E

Consider this class: 1. public class Test1 { 2. public float aMethod(float a, float b) { 3. } 4. 5. } Which of the following methods would be legal if added (individually) at line 4? (Choose all that apply.) A. public int aMethod(int a, int b) { } B. public float aMethod(float a, float b) { } C. public float aMethod(float a, float b, int c) throws Exception { } D. public float aMethod(float c, float d) { } E. private float aMethod(int a, int b, int c) { }

A, B, D

Which of the following are valid declarations? Assume java.util.* is imported. A. Vector<Map> v; B. Set<String> s; C. Map<String> m; D. Map<String, String> m;

A

You can determine all the keys in a Map in which of the following ways? A. By getting a Set object from the Map and iterating through it. B. By iterating through the Iterator of the Map. C. By enumerating through the Enumeration of the Map. D. By getting a List from the Map and enumerating through the List. E. You cannot determine the keys in a Map.


Set pelajaran terkait

Chapter 14 Review Worksheet: Adolescence: Biosocial

View Set

Geography U.S. and Canada Chapters 1-18

View Set

Chapter 41 - Neurological Emergencies

View Set

Geol 9 Chapter 8 -Tsunami Versus Wind-Caused waves

View Set

Biology- Mrs. King, Leap test (reviews)

View Set

SEAN'S Sociology 101 Study Guide

View Set

Unit 6: Declaration of Independence

View Set