Java PRO192

Ace your homework & exams now with Quizwiz!

QN=21 (195) 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.

At line 2, the thread will stop running. It will resume running some time after 100 milliseconds have elapsed.

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.

Attempting to add anything other than a string to fancyVec results in a compiler error.

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.

B must have a no-args constructor.

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) { }

Base() { } Base(int j, int k) { }

1. Which of the following statements is correct? (Choose one.) 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.

Both primitives and object references can be both converted and cast.

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.

C must have a no-args constructor.

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

Checked exceptions

Which of the following should always be caught? (Choose one.) a. Runtime exceptions b. Checked exceptions c. Assertion errors d. Errors other than assertion errors

Checked exceptions

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.

Class Zebra generates a compiler error.

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? (Choose one.) a. Class loading takes no additional time. b. Class loading takes slightly more time. c. Class loading takes significantly more time.

Class loading takes no additional time.

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

Classes Data Methods

In order for objects in a List to be sorted, those objects must implement which interface and method? (Choose one.) a. Comparable interface and its compareTo method. b. Comparable interface and its compare method c. Compare interface and its compareTo method d. Comparable interface and its equals method

Comparable interface and its compareTo method.

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.

Compilation fails at line 2.

Given: 23. Object [] myObjects = { 24. new Integer(12), 25. new String("foo"), 26. new Integer(5), 27. new Boolean(true) 28. }; 29. java.util.Array.sort(myObjects); 30. for( int i=0; i<myObjects.length; i++) { 31. System.out.print(myObjects[i].toString()); 32. System.out.print(" "); 33. } What is the result? (Choose one.) a. Compilation fails due to an error in line 23. b. Compilation fails due to an error in line 29. c. A ClassCastException occurs in line 29. d. A ClassCastException occurs in line 31. e. The value of all four objects prints in natural order.

Compilation fails due to an error in line 29.

11. public static void parse(String str) { 12. try { 13. float f= Float.parseFloat(str); 14. } catch (NumberFormatException nfe) { 15. f = 0; 16. } finally { 17. System.out.println(f); 18. } 19. } 20. public static void main(String[] args) { 21. parse("invalid"); 22. } What is the result? (Choose one.) a. 0.0 b. Compilation fails. c. A ParseException is thrown by the parse method at runtime. d. A NumberFormatException is thrown by the parse method at runtime.

Compilation fails.

Give: 11. public static Iterator reverse(List list) { 12. Collections.reverse(list); 13. return list.iterator(); 14. } 15. public static void main(String[] args) { 16. List list = new ArrayList(); 17. list.add(" 1"); list.add("2"); list.add("3"); 18. for (Object obj: reverse(list)) 19. System.out.print(obj + ","); 20. } 'What is the result? (Choose one.) a. 3, 2, 1, b. 1, 2, 3, c. Compilation fails. d. The code runs with no output. e. An exception is thrown at runtime.

Compilation fails.

Given: 11. String test = "This is a test"; 12. String[] tokens = test.split("\s"); 13. System.out.println(tokens.length); What is the result? (Choose one.) a. 0 b. 1 c. 4 d. Compilation fails. e. An exception is thrown at runtime.

Compilation fails.

Given: 11. public static void main(String[] args) { 12. try { 13. args=null; 14. args[0] = "test"; 15. System.out.println(args[0]); 16. }catch (Exception ex) { 17. System.out.println("Exception"); 18. }catch (NullPointerException npe) { 19. System.out.println("NullPointerException"); 20. } 21. } What is the result? (Choose one.) a. Test b. Exception c. Compilation fails. d. NullPointerException

Compilation fails.

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.

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.

Class SomeException: 1. public class SomeException { 2. } Class A: 1. public class A { 2. public void doSomething() { } 3. } Class B: 1. public class B extends A { 2. public void doSomething() throws SomeException { } 3. } Which is true about the two classes? (Choose one.) a. Compilation of both classes will fail. b. Compilation of both classes will succeed. c. Compilation of class A will fail. Compilation of class B will succeed. d. Compilation of class B will fail. Compilation of class A will succeed.

Compilation of class B will fail. Compilation of class A will succeed.

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.

Compilation succeeds. No exception is thrown during execution.

Which one statement is true about the following code fragment? 1. String s = "FPT"; 2. StringBuffer s1 = new StringBuffer("FPT"); 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.

Compilation succeeds. No exception is thrown during execution.

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

Data Methods Code blocks enclosed in curly brackets

There are two classes in Java to enable communication using datagrams namely. a. DataPacket and DataSocket b. DatagramPacket and DatagramSocket c. DatagramPack and DatagramSock

DataPacket and DataSocket

The class is the primary class that has the driver information. a. DriverManager b. Driver c. ODBCDriver d. None of the others

DriverManager

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

False

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

False

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

False

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

False

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

False

The element method alters the contents of a Queue. a. True b. False

False

Which of the following are valid arguments to the DataInputStream constructor? (Choose one.) a. File b. FileReader c. FileInputStream d. RandomAccessFile

FileInputStream

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. };

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()

QN=102 (77) public class Test{ public static void main(String[] args){ Object ob1= new Object(); Object ob2= new Object(); if(ob1.equals(ob2)) System.out.println("ob1 equals ob2"); if(ob1==ob2) System.out.println("ob1==ob2"); System.out.println("Have a nice day!"); } } What is the output? a. ob1 equals ob2 Have a nice day! b. ob1==ob2 Have a nice day! c. Have a nice day! d. No output

Have a nice day!

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.

It always returns 0.

1. public class A { 2. public String doit(int x, int y) { 3. return "a"; 4. } 5. 6. public String doit(int... vals) { 7. return "b"; 8. } 9. } Given: 25. A a=new A(); 26. System.out.println(a.doit(4, 5)); What is the result? (Choose one.) a. Line 26 prints "a" to System.out. b. Line 26 prints "b" to System.out. c. An exception is thrown at line 26 at runtime. d. Compilation of class A will fail due to an error in line 6.

Line 26 prints "a" to System.out.

public class Test{ public static void main(String[] args){ String s1 = "xyz"; String s2 = "xyz"; if (s1 == s2) System.out.println("Line 4"); if (s1.equals(s2)) System.out.println("Line 6"); } } What is the output? a. Line 4 Line 6 b. Line 4 c. Line 6 d. No output, compile error e. No output

Line 4 Line 6

Given: 55. int []x= {1, 2,3,4, 5}; 56. int y[] =x; 57. System.out.println(y[2]); Which is true? (Choose one.) a. Line 57 will print the value 2. b. Line 57 will print the value 3. c. Compilation will fail because of an error in line 55. d. Compilation will fail because of an error in line 56.

Line 57 will print the value 3.

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

Line 6

public class Test{ public static void main(String[] args){ String s1 = "xyz"; String s2 = new String("xyz"); if (s1 == s2) System.out.println("Line 4"); if (s1.equals(s2)) System.out.println("Line 6"); } } What is the output? a. Line 4 Line 6 b. Line 4 c. Line 6 d. No output, compile error e. No output

Line 6

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.

Line 7 will not compile; an explicit cast is required to convert a Washer to a SwampThing.

Given: 10. class Line { 11. public static class Point { } 12. } 13. 14. class Triangle { 15. // insert code here 16. } Which code, inserted at line 15, creates an instance of the Point class defined in Line? (Choose one.) a. Point p = new Point(); b. Line.Point p = new Line.Point(); c. The Point class cannot be instatiated at line 15. d. Line l = new Line() ; Point p = new l.Point();

Line.Point p = new Line.Point();

Which of the following classes implements a FIFO Queue? (Choose one.) a. HashSet b. LinkedList c. PriorityQueue d. CopyOnWriteArraySet

LinkedList

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>();

List<String> theList = new Vector<String>(); Vector <String> theVec = new Vector<String>();

QN=100 (305) MVC is short call of a. Model-View-Controller b. Multiple-View-Controller c. Metal-View-Controller

Model-View-Controller

Given: 10. class Nav{ 11. public enum Direction { NORTH, SOUTH, EAST, WEST } 12. } 13. public class Sprite{ 14. // insert code here 15. } Which code, inserted at line 14, allows the Sprite class to compile? (Choose one.) a. Direction d = NORTH; b. Nav.Direction d = NORTH; c. Direction d = Direction.NORTH; d. Nav.Direction d = Nav.Direction.NORTH;

Nav.Direction d = Nav.Direction.NORTH;

When a negative byte is cast to a long, what are the possible values of the result? (Choose one.) a. Positive b. Zero c. Negative d. All the above

Negative

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

Never

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

No

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.

No directory is created, and no file is created.

QN=101 (129) public class Test{ public static void main(String[] args){ byte b = 2; byte b1 = 3; b = b * b1; System.out.println("b="+b); } } What is the output? a. b=6 b. No output because of compile error at line: b = b * b1; c. No output because of compile error at line: System.out.println("b="+b); d. No output because of compile error at line: byte b = 2; e. No output because of compile error at line: byte b = 3;

No output because of compile error at line: b = b * b1;

Given a string constructed by calling s = new String("xyzzy"), which of the calls modifies the string? (Choose one.) 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

None of the above

Which of the following is true? (Choose one.) 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

None of the above

Which of the statements below are true? (Choose one.) 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

None of the above

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.

None of the above.

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.

None of the above.

2. Which of the statements below are true? (Choose all that apply.) 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.

None of the above.

Which of the following are legal loop definitions? (Choose one.) 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 the above.

None of the above.

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

None of these

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);

NumberFormat nf = NumberFormat.getInstance(loc); String s = nf.format(f);

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

Object Stream Finally

6. Which of the following statements is true? (Choose one.) 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.

Object references can be converted in both method calls and assignments, and the rules governing these conversions are identical.

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.

On line 1, remove the final modifier.

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

One

Which of the following statements are true? 1)An abstract class may not have any final methods. 2)A final class may not have any abstract methods. a. Only statement 1 b. Only statement 2 c. Both statement 1 and 2

Only statement 2

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? (Choose one.) 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.

Override run().

Which of the following is not appropriate situations for assertions? (Choose one) a. Preconditions of a public method b. Postconditions of a public method c. Preconditions of a private method d. Postconditions of a private method

Preconditions of a public method

Which of the following interfaces does not allow duplicate objects? (Choose one.) a. Queue b. Set c. List

Set

Given: 11. public abstract class Shape { 12. int x; 13. int y; 14. public abstract void draw(); 15. public void setAnchor(int x, int y) { 16. this.x = x; 17. this.y = y; 18. } 19. } and a class Circle that extends and fully implements the Shape class. Which is correct? (Choose one.) a. Shape s = new Shape(); s.setAnchor(10,10); s.draw(); b. Circle c = new Shape(); c.setAnchor(10,10); c.draw(); c. Shape s = new Circle(); s.setAnchor(10,10); s.draw(); d. Shape s = new Circle(); s->setAnchor(10,10); s->draw(); e. Circle c = new Circle(); c.Shape.setAnchor(10,10); c.Shape.draw();

Shape s = new Circle(); s.setAnchor(10,10); s.draw();

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

Sometimes

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

Sometimes

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? (Choose one.) a. Sometimes b. Always c. Never d. None of the others choices

Sometimes

Given: 10. public class ClassA { 11. public void count(int i) { 12. count(++i); 13. } 14. } And: 20. ClassA a = new ClassA(); 21. a.count(3); Which exception or error should be thrown by the virtual machine? (Choose one.) a. StackOverflowError b. NullPointerException c. NumberFormatException d. IllegalArgumentException e. ExceptionlnlnitializerError

StackOverflowError

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*";

String delim = "\\d+";

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.

StringBuilder is generally faster than StringBuffer. StringBuffer is threadsafe; StringBuilder is not.

QN=85 (236) How do you use the File class to list the contents of a directory? (Choose one.) 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.

String[] contents = myFile.list();

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);

System.out.format("%-20.15f", 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.

The class will compile if it is declared abstract. The class may not be instantiated.

Which statement is true about this application? (Choose one.) 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.

The code compiles and execution produces the output x = 3.

QN=153 (59) What happens when you try to compile and run the following code? public class Q { 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<<

The code compiles, and prints out >>null<<

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.

The code fails to compile.

1. public class A { 2. public void method1() { 3. B b=new B(); 4. b.method2(); 5. // more code here 6. } 7.} 1. public class B { 2. public void method2() { 3. C c=new C(); 4. c.method3(); 5. // more code here 6. } 7.} 1. public class C { 2. public void method3() { 3. // more code here 4. } 5.} 25. try { 26. A a=new A(); 27. a.method1(); 28. }catch (Exception e) { 29. System.out.print("an error occurred"); 30. } Which two are true if a NullPointerException is thrown on line 3 of class C? (Choose two.) a. The application will crash. b. The code on line 29 will be executed. c. The code on line 5 of class A will execute. d. The code on line 5 of class B will execute. e. The exception will be propagated back to line 27.

The code on line 29 will be executed. The exception will be propagated back to line 27.

29. What will be the outcome when the following application is executed? public class ThreadTest { public void newThread() { Thread t = new Thread() { public void run() { System.out.println("Going to sleep"); try { sleep(5000); } catch (InterruptedException e) {} System.out.println("Waking up"); } }; t.start(); try { t.join(); } catch (InterruptedException e) {} System.out.println("All done"); } public static void main(String [] args) { new ThreadTest().newThread(); } } A. The code prints "Going to sleep," then "Waking up," and then "All done." B. The code prints "All done," then "Going to sleep," and then "Waking up." C. The code prints "All done" only. D. The code prints "Going to sleep" and then "Waking up." E. The code does not compile.

The code prints "Going to sleep," then "Waking up," and then "All done."

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.

The code will compile and produce the following output: int version.

Consider the following code: 1. Dog rover, fido; 2. Animal anim; 3. 4. rover = new Dog(); 5. anim = rover; 6. fido = (Dog)anim; Where: Mammal extends Animal Dog extends Mammal 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.

The code will compile and run.

9. 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.

The code will compile but will throw an exception at line 7, because the runtime class of wawa cannot be converted to type SwampThing.

8. Given 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.

The compiler does not create a default constructor.

What does the following code fragment print out at line 9? (Choose one.) 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.

The output is i = 20.

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.

The output would be the text value is two followed by the text value is three.

Given: 20. public class CreditCard { 22. private String cardlD; 23. private Integer limit; 24. public String ownerName; 26. public void setCardlnformation(String cardlD, 27. String ownerName, 28. Integer limit) { 29. this.cardlD = cardlD; 30. this.ownerName = ownerName; 31. this.limit = limit; 32. } 33. } Which is true? (Choose one.) a. The class is fully encapsulated. b. The code demonstrates polymorphism. c. The ownerName variable breaks encapsulation. d. The cardlD and limit variables break polymorphism. e. The setCardlnformation method breaks encapsulation.

The ownerName variable breaks encapsulation.

Which statement is true about this code? (Choose one.) 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 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.

The program compiles and the output is x = 104.

10. 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 Nightingale? 1. package singers; 2. 3. class Nightingale extends abcde.Bird { 4. Nightingale() { referenceCount++; } 5. 6. public static void main(String args[]) { 7. System.out.print("Before: " + referenceCount); 8. Nightingale florence = new Nightingale(); 9. System.out.println(" After: " + referenceCount); 10. florence.fly(); 11. } 12. } A. The program will compile and execute. The output will be Before: 0 After: 2. B. The program will compile and execute. The output will be Before: 0 After: 1. C. Compilation of Nightingale will fail at line 4 because static members cannot be overridden. D. Compilation of Nightingale will fail at line 10 because method fly() is protected in the superclass. E. Compilation of Nightingale will succeed, but an exception will be thrown at line 10, because method fly() is protected in the superclass.

The program will compile and execute. The output will be Before: 0 After: 2.

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.

The strategy fails because you cannot subclass java.lang.Math.

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

The style, which is one of SHORT, MEDIUM, LONG, or FULL The locale

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.

The thread that calls wait() goes into the monitor's pool of waiting threads.

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

There are no possible legal types.

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.

There is no difference; the rules are the same.

How can you ensure that multithreaded code does not deadlock? (Choose one.) 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. There is no single technique that can guarantee non-deadlocking code.

There is no single technique that can guarantee non-deadlocking code

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.

There will be a compiler error, because class Greebo does not correctly implement the Runnable interface.

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.

They must be defined inside a code block.

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.

Threads inherit their priority from their parent thread.

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.

Throw java.lang.IllegalArgumentException.

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. c. Compile error

Throws an exception.

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.

Transient variables are not serialized.

If you need a Set implementation that provides value-ordered iteration, which class should you use? (Choose one.) a. HashSet b. LinkedHashSet c. TreeSet

TreeSet

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

True

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

True

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

True

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("FPT"); 2. sbuf.append("-University"); a. True b. False

True

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("FPT"); 2. sbuf.insert(3, "-University"); a. True b. False

True

1. Which of the statements below are true? (Choose all that apply.) 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.

Unicode characters are all 16 bits.

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

Value is 5This value is 6

Select INCORRECT statement about deserialize. (choose 1) a. Any JVM that tries to deserialize an object must have access to that object's class definition. b. We use readObject() method of ObjectOutputStream class to deserialize. c. The readObject method deserializes the next object in the stream and traverses its references to other objects recursively to deserialize all objects that are reachable from it.

We use readObject() method of ObjectOutputStream class to deserialize.

When should objects stored in a Set implement the java.util.Comparable interface? A. Always B. When the Set is generic C. When the Set is a HashSet D. When the Set is a TreeSet E. Never

When the Set is a TreeSet

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.

When the application is run, all three threads (hp1, hp2, and hp3) will execute concurrently, taking time-sliced turns in the CPU.

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

When the exception is being thrown in response to catching of a different exception type

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

When the exception is constructed

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? (Choose one.) a. When the type of x is Object b. When the type of x is an array c. Always d. Never

When the type of x is Object

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.

Within the method, names is an array containing Strings.

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

Yes

QN=97 (76) 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

Yes

QN=98 (205) Is it possible to write code that can execute only if the current thread owns multiple locks? a. Yes b. No

Yes

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

Yes.

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? (Choose one.) 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.

You cannot specify which thread will get notified.

method is used to wait for a client to initiate communications. a. wait() b. accept() c. listen()

accept()

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";

assert x == 4; assert x == 4 : "x is not 4";

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

byte int char

When you compile a program written in the Java programming language, the compiler converts the human-readable source file into platform- independent code that a Java Virtual Machine can understand. What is this platform-independent code called? a. bytecode b. binary code c. machine code d. cpu instruction

bytecode

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

char c = '\u1234';

QN=68 (1516) Given: 12. public class Test { 13. public enum Dogs {collie, harrier}; 14. public static void main(String [] args) { 15. Dogs myDog = Dogs.collie; 16. switch (myDog) { 17. case collie: 18. System.out.print("collie "); 19. case harrier: 20. System.out.print("harrier "); 21. } 22. } 23. } What is the result? (Choose one.) a. collie b. harrier c. Compilation fails. d. collie harrier e. An exception is thrown at runtime.

collie harrier

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()

createNewFile()

QN=69 (1414) Given: 13. public class Pass { 14. public static void main(String [] args) { 15. int x = 5; 16. Pass p = new Pass(); 17. p.doStuff(x); 18. System.out.print(" main x = "+ x); 19. } 20. 21. void doStuff(int x) { 22. System.out.print("doStuff x = "+ x++); 23. } 24. } What is the result? (Choose one.) a. Compilation fails. b. An exception is thrown at runtime. c. doStuff x = 6 main x = 6 d. doStuff x = 5 main x = 5 e. doStuff x = 5 main x = 6 f. doStuff x = 6 main x = 5

doStuff x = 5 main x = 5

Which of the following are legal? (Choose two.) a. double d = 1.2d; b. double d = 1.2D; c. double d = 1.2d5; d. double d = 1.2D5;

double d = 1.2d; double d = 1.2D;

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

enums bytes

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.

float

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];

for (int i=0; i<ages.length; i++) sum += ages[i]; for (int i:ages) sum += i;

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

i = 1 j = 0

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())

if (x == y)

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.

int

Which of the following are legal? (Choose two.) a. int a = abcd; b. int b = ABCD; c. int c = 0xabcd; d. int d = 0XABCD; e. int f = 0ABCD;

int c = 0xabcd; int d = 0XABCD;

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);

int j = 0; for (int k=0, j+k != 10; j++,k++) { System.out.println("j=" + j + ", k=" + k); }

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;

int x = -1; x = x >>> 5;

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

java.util.ArrayList java.util.Stack

Which of the following classes implement java.util.List? (Choose two.) a. java.util.ArrayList b. java.util.HashMap c. java.util.TreeSet d. java.util.Stack

java.util.ArrayList java.util.Stack

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? (Choose one.) a. java.util.Arrays.equals(a1, a2); b. java.util.Arrays.compare(a1, a2); c. java.util.List.compare(a1, a2);

java.util.Arrays.equals(a1, a2);

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? (Choose one.) 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

line 3: private; line 8: protected

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

message four

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

n is 10, w.x is 11

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

name() toString()

Given: 10. interface Foo { int bar(); } 11. public class Sprite { 12. public int fubar( Foo foo) { return foo.bar(); } 13. public void testFoo() { 14. fubar( 15. // insert code here 16. ); 17. } 18. } Which code, inserted at line 15, allows the class Sprite to compile? (Choose one.) a. Foo { public int bar() { return 1; } } b. new Foo { public int bar() { return 1; } } c. new Foo() { public int bar(){return 1; } } d. new class Foo { public int bar() { return 1; } }

new Foo() { public int bar(){return 1; } }

QN=103 (4924) public class Test{ public static void main(String[] args){ Object ob1= new Object(); Object ob2= ob1; if(ob1.equals(ob2)) System.out.println("ob1 equals ob2"); if(ob1==ob2) System.out.println("ob1==ob2"); System.out.println("Have a nice day!"); } } What is the output? a. ob1 equals ob2 ob1==ob2 Have a nice day! b. ob1 equals ob2 Have a nice day! c. ob1==ob2 Have a nice day! d. None of the above

ob1 equals ob2 ob1==ob2 Have a nice day!

Given: 12. public class AssertStuff { 14. public static void main(String [] args) { 15. int x= 5; 16. int y= 7; 18. assert (x > y): "stuff"; 19. System.out.println("passed"); 20. } 21. } And these command line invocations: java AssertStuff java -ea AssertStuff What is the result? (Choose one.) a. Passed Stuff b. Stuff Passed c. passed An AssertionError is thrown with the word "stuff" added to the stack trace. d. passed An AssertionError is thrown without the word "stuff" added to the stack trace. e. passed An AssertionException is thrown with the word "stuff" added to the stack trace. f. passed An AssertionException is thrown without the word "stuff" added to the stack trace.

passed An AssertionError is thrown with the word "stuff" added to the stack trace.

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

private

12. 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

private

Suppose class A has a method called doSomething(), with default access. Suppose class B extends A and overrides doSomething(). Which access modes may not apply to B's version of doSomething()? (Choose one) a. public b. private c. protected d. Default

private

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? (Choose one.) a. public b. protected c. default d. private

private

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? (Choose one.) a. public b. protected c. default d. private

private

URL referring to databases use the form: a. protocol:subprotocol:datasoursename b. protocol:datasoursename c. jdbc:odbc:datasoursename d. jdbc:datasoursename

protocol:subprotocol:datasoursename

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

public protected

16. Suppose 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

public protected Default

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()

public Color getTheTint()

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)

public boolean addAll(Collection<? extends E> c)

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(); }

public int hashCode() { return a; } public int hashCode() { return (int)Math.random(); }

Given: 1. public interface A { 2. String DEFAULT_GREETING = "Hello World"; 3. public void method1(); 4. } A programmer wants to create an interface called B that has A as its parent. Which interface declaration is correct? (Choose one.) a. public interface B extends A { } b. public interface B implements A {} c. public interface B instanceOf A {} d. public interface B inheritsFrom A { }

public interface B extends 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 { ... }

public void doSomething(int a, float b) { ... }

A programmer needs to create a logging method that can accept an arbitrary number of arguments. For example, it may be called in these ways: logIt("log message 1 "); logIt("log message2","log message3"); logIt("log message4", "log message5", "log message6"); Which declaration satisfies this requirement? (Choose one.) a. public void logIt(String * msgs) b. public void logIt(String [] msgs) c. public void logIt(String... msgs) d. public void logIt(String msg1, String msg2, String msg3)

public void logIt(String... msgs)

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;

public void swim() { } size = 12;

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+");

sc.useDelimiter("\\d");

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);

super(); this(1.23f);

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()

suspend() and resume()

11. public class Bootchy { 12. int bootch; 13. String snootch; 14. 15. public Bootchy() { 16. this("snootchy"); 17. System.out.print("first "); 18. } 19. 20. public Bootchy(String snootch) { 21. this(420, "snootchy"); 22. System.out.print("second "); 23. } 24. 25. public Bootchy(int bootch, String snootch) { 26. this.bootch = bootch; 27. this.snootch = snootch; 28. System.out.print("third "); 29. } 30. 31. public static void main(String[] args) { 32. Bootchy b = new Bootchy(); 33. System.out.print(b.snootch +" " + b.bootch); 34. } 35. } What is the result? (Choose one.) a. snootchy 420 third second first b. snootchy 420 first second third c. first second third snootchy 420 d. third second first snootchy 420 e. third first second snootchy 420 f. first second first third snootchy 420

third second first snootchy 420

QN=180 (313) Whenever a method does not want to handle exceptions using the try block, the is used. a. throws b. throw c. throwable d. nothrows

throws

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

transient

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)

void xyz(float f) public void xyz(float f)

When comparing java.io.BufferedWriter to java.io.FileWriter, which capability exists as a method in only one of the two? (Choose one.) a. closing the stream b. flushing the stream c. writing to the stream d. marking a location in the stream e. writing a line separator to the stream

writing a line separator to the stream

Consider the following line of code: (49) int[] x = new int[25]; After execution, which statements are true? (Choose two.) 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

x[24] is 0 x.length is 25

What is the range of values that can be assigned to a variable of type short? (Choose one.) 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

−2^15 through 2^15 − 1

What is the range of values that can be assigned to a variable of type byte? (Choose one.) 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

−2^7 through 2^7 − 1

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

"is a"

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

-1

What is -50 >> 2 a. A negative number with very large magnitude. b. A positive number with very large magnitude. c. -13 d. -25 e. 13 f. 25

-13

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

-25

What is -8 % 5? a. -3 b. 3 c. -2 d. 2

-3

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

-5

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

/

Which of the following is NOTa valid comment: a. /*** comment **/ b. /** comment **/ c. /* comment d. // comment

/* comment

Given: 11. public static void main(String[] args) { 12. Object obj =new int[] { 1,2,3 }; 13. int[] someArray = (int[])obj; 14. for (int i: someArray) System.out.print(i +" "); 15. } What is the result? (Choose one.) a. 1 2 3 b. Compilation fails because of an error in line 12. c. Compilation fails because of an error in line 13. d. Compilation fails because of an error in line 14. e. A ClassCastException is thrown at runtime.

1 2 3

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. } 15. } What value is printed out at line 6? a. 0 b. 1 c. 100 d. 101

101

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.

12

7. 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

12.3

What is 7 % -4? a. -3 b. 3 c. -4 d. 4

3

How many bytes does the following code write to file dest? (Choose one.) 1. try { 2. FileOutputStream fos = newFileOutputStream("dest"); 3. DataOutputStream dos = new DataOutputStream(fos); 4. dos.writeInt(3); 5. dos.writeFloat(0.0001f); 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.

8

Given: class A { public void process() { System.out.print("A "); } public static void main(String[] args) { try { ((A)new B()).process(); } catch (Exception e) { System.out.print("Exception "); } } } class B extends A { public void process() throws RuntimeException { super.process(); if (true) throw new RuntimeException(); System.out.print("B"); } } What is the result? (Choose one.) a. Exception b. A Exception c. A Exception B d. A B Exception e. Compilation fails because of an error in line: public void process() throws RuntimeException f. Compilation fails because of an error in line: try { ((A)new B()).process(); }

A Exception

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 class An interface

19. Which of the following statements are true? A. A final class must be instantiated. B. A final class may only contain final methods. C. A final class may not contain non-final data fields. D. A final class may not be extended. E. None of the above.

A final class may not be extended.

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

A reference

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, B, and C do not ensure that multithreaded code does not deadlock.

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.

Access the variables only via synchronized methods.

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.

After line 2 executes, the StringBuffer object is eligible for garbage collection.

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.

After line 3

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

All of the above

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

All of the above

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

All of the above

Which of the following may legally appear as the new type (between the parentheses) in a cast operation? (Choose one.) a. Abstract classes b. Final classes c. Primitives d. All of the above

All of the above

Which of the following may legally appear as the new type (between the parentheses) in a cast operation? (Choose one.) a. Classes b. Interfaces c. Arrays of classes d. Arrays of interfaces e. All of the others

All of the others

Suppose prim is an int and wrapped is an Integer. Which of the following are legal Java statements? (Choose one.) a. prim = wrapped; b. wrapped = prim; c. prim = new Integer(9); d. wrapped = 9; e. All the above

All the above

When a negative long is cast to a byte, what are the possible values of the result? (Choose one.) a. Positive b. Zero c. Negative d. All the above

All the above

Which of the following are methods of the java.util.SortedSet interface? (Choose one.) a. first b. last c. headSet d. tailSet e. subSet f. All the above

All the above

Which of the following are true? (Choose one.) 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 the above

All the above

Which of the following are valid mode strings for the RandomAccessFile constructor? (Choose one.) a. "r" b. "rw" c. "rws" d. "rwd" e. All the above

All the above

Which of the following calls may be made from a non-static synchronized method? (Choose one.) 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 the above

All the above

Which of the following is(are) true? (Choose one.) 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 the above

All the above

Select correct statement(s) about remote class.(choose one) a. It must extend java.rmi.server.UnicastRemoteObject. b. It must implement the remote interface. c. It is the class whose methods provide services to clients. d. All the others choices

All the others choices

Select correct statements about remote interface. (choose 1) a. A remote interface is an interface that describes the remotely accessible methods of a remote object. b. All remote interfaces must extend java.rmi.Remote. c. All methods in a remote interface must throw java.rmi.RemoteException d. The type of a remote reference is a remote interface e. All the others choices

All the others choices

Which of the following are true? (Choose two.) 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.

An enum may contain public method definitions. An enum may contain private data.

What happens when you try to compile and run this application? (Choose one.) 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.

An exception is thrown at line 7.

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.

An exception is thrown at line 9.

10. public class ClassA { 11. public void methodA() { 12. ClassB classB = new ClassB(); 13. classB.getValue(); 14. } 15.} And: 20. class ClassB { 21. public ClassC classC; 22. 23. public String getValue() { 24. return classC.getValue(); 25. } 26.} And: 30. class ClassC { 31. public String value; 32. 33. public String getValue() { 34. value = "ClassB"; 35. return value; 36. } 37.} ClassA a = new ClassA(); a.methodA(); What is the result? (Choose one.) a. Compilation fails. b. ClassC is displayed. c. The code runs with no output. d. An exception is thrown at runtime.

An exception is thrown at runtime.


Related study sets

CH.4 Communication and Documentation

View Set

Chapter 04. Communication and Physical Assessment of the Child and Family

View Set

CA life and Health: Life Insurance Basics

View Set