love fish大鹏一曰同风起,扶摇直上九万里

常用链接

统计

积分与排名

friends

link

最新评论

SCJP考题2(详尽答案) (转)

test 1
##########

***     ================
1.1 Which of the following are valid constructors of the class java.lang.AssertionError?
A. AssertionError()
B. AssertionError(String detailMessage)
C. AssertionError(boolean detailMessage)
D. AssertionError(int detailMessage)
E. AssertionError(StackTraceElement detailMessage)
Answer: ACD

****    ================
1.2 What should be inserted at line 7 so that the code compiles and guarantees to print -
Apple Cricket Banana in the same order.
1.  import java.util.*;
2.  
3.  public class SetTest
4.  {
5.      public static void main(String args[])
6.      {
7.          // what should be inserted here?
8.          
9.          set.add("Apple");
10.         set.add("Cricket");
11.         set.add("Banana");
12.        
13.         Iterator iter = set.iterator();
14.         while(iter.hasNext())
15.         {
16.             System.out.print(iter.next() + " ");
17.         }
18.     }
19. }
A. Set set = new LinkedHashSet();
B. Set set = new HashSet();
C. Set set = new TreeSet();
D. TreeSet maintains the Set elements sorted according to their natural order; however other sets do not guarantee iteration order of the set. In particular, they do not guarantee that the order will remain constant over time.
Answer: A
Note:  JDK 1.4 adds a new collection class LinkedHashSet to the collections framework. LinkedHashSet remembers the order in which objects are inserted.
TreeSet maintains its elements in their natural order, hence iterating will produce "Apple Banana Cricket " instead of "Apple Cricket Banana ". Hence option C is incorrect.
HashSet is a basic implementation of Set. It makes no guarantees as to the iteration order of the set;in particular.

****    ==============================
1.3 What will happen when you attempt to compile and run the following code?
public class Test{
   int i = 0;
   public static void main(String argv[]) {
       Test t = new Test();
       t.myMethod();
   }
   public void myMethod(){
       while(true) {
           try {
               wait();
           }catch (InterruptedException e) {}
           i++;
       }
   }
}
A. Compile time error, no matching notify within the method.
B. Compile and run but an infinite looping of the while method.
C. Compilation and run without any output.
E. Runtime Exception "IllegalMonitorStatException".
Answer: E
Note: The wait/notify protocol can only be used within code that is synchronized. In this case calling code does not have a lock on the object(not synchronized) and will thus cause an Exception at runtime.

*****   ====================
1.4 What will be the result of executing the following main() method?
1.  public static void main(String[] args)
2.  {
3.      String myString;
4.      int x = 100;
5.    
6.      if (x < 100) myString = "x is less than 100";
7.      if (x > 100) myString = "x is greater than 100";
8.      System.out.println(myString.length());
9.  }
A. The code will compile with a warning that variable myString might not have been initialized
B. The code will compile without any warnings
C. The code will not compile. But it will compile and print the length of myString if the variable myString is initialized in an unconditional statement before line 8
D. None of these
Answer: D??
Note: myString may be initiated to be null and then run time error.

****    ==================
1.5 What results from running the code below?
int a = -5; int b = -2;
System.out.println(a % b);
A. 0
B. 1
C. -1
D. A compiler error saying "%" operator is not valid for negative numbers.
Answer: C
Note:  To calculate a % b(a modulus b), the simplest way is, drop any negative signs from both the operands and calculate the result. Now if the left-hand side operand is negative negate the result, the sign of right-hand side operand doesn't matter. In our case (-5 % -2) is equal to -(5 % 2) = -(1) = -1, hence C is correct. If the calculate a%b(a=5, b=-2), the result will be 1.

**      =================
1.6 What is the return type of method add(Object o) of Set interface, and what does it indicate?
A. It returns an int representing hash code of the newly added object
B. It returns an Integer object representing hash code of the newly added object
C. It returns a boolean. Returns true if this set already contains the specified element.
D. It returns a boolean. Returns true if this set did not already contain the specified element.
E. Return type is void. Any error in the add operation is reported by throwing an exception.
F. None of these
Answer: D

***     =====================
1.7 Which of the following classes implement java.util.Map interface?
A. Hashtable
B. HashMap
C. Dictionary
D. IdentityHashMap
E. Vector
Answer: ABD
Note: The abstract class Dictionary is a legacy class and as per Java API documentation, it is obsolete. It does not implement Map interface.

**      ===================
1.8 The package favorite.fruits contains different classes for different fruits. Orange is one of the classes in this package. Assume that all the classes from this package are compiled with assertions enabled. Which of the following will enable assertions at runtime for this package, but will disable it for the class Orange, using standard JDK 1.4?
A. java -ea:favorite.fruits... -da:favorite.fruits.Orange <Main Class>
B. java -ea:favorite.fruits...,-da:favorite.fruits.Orange <Main Class>
C. java -ea:favorite.fruits... -da:Orange <Main Class>
D. java -ea:favorite.fruits... -da Orange <Main Class>
E. None of these
Answer: A+++++++++++++++++++++++

****    ========================
1.9 What is the valid declaration for the finalize() method?
A. protected void finalize() throws Throwable
B. final finalize()
C. public final finalize()
D. private boolean finalize()
E. private final void finalize() throws Exception
Answer: A

**      ====================
1.10 What is the result of compiling and executing the following code?
public class ThreadTest extends Thread {
   public void run() {
       System.out.println("In run");
       yield();
       System.out.println("Leaving run");
   }
   public static void main(String args []) {
       (new ThreadTest()).start();
   }
}
A. The code fails to compile in the main() method.
B. The code fails to compile in the run() method.
C. Only the text "In run" will be displayed.
D. The text "In run" followed by "Leaving run" will be displayed.
E. The code compiles correctly, but nothing is displayed.
Answer: D

****    ====================
1.11 Which of the following are valid declarations for a native method?
A. public native void aMethod();
B. private native String aMethod();
C. private native boolean aMethod(int val){};
D. public native int aMethod(String test);
E. private native boolean aMethod(boolean flag, Integer val);
Answer: ABDE
Note: The 'native' does not affect the access qualifiers, so a native method can be public or private. It is also valid to return primitives as well as objects from a native method (so returning a String is valid) - it is also valid to pass in objects as well as primitives. Answer C is incorrect, because it attempts to define the actual method, by using '{...}'.

**      =======================
1.12 Which of the following will definitely stop a thread from executing?
A. wait()
B. notify()
C. yield()
D. suspend()
E. sleep()
Answer: ACDE

****    =======================
1.13 Which one of the following fragments shows the most appropriate way to throw an exception? Assume that any undeclared variables have been appropriately declared elsewhere and are in scope and have meaningful values.
A.  1.  Exception e = new MalformedURLException("Invalid URL");
   2.  if (!myURL.isValid()) // myURL is a URL object
   3.  {
   4.      throw e;
   5.  }
B.  1.  if (!myURL.isValid ())
   2.  {
   3.      throw new MalformedURLException("URL " + myURL.getName() + " is not valid");
   4.  }
C.  1.  if (!myURL.isValid ())
   2.  {
   3.      throw IOException;
   4.  }
D.  1.  if (!myURL.isValid ())
   2.  {
   3.      throw "Invalid URL";
   4.  }
E.  1.  if (!myURL.isValid ())
   2.  {
   3.      throw new IOException();
   4.  }
Answer: B



###########
test 2
###########

**      =============
2.1 What will happen when you attempt to compile and run the following code?
(Assume that the code is compiled and run with assertions enabled.)
public class AssertTest {
   private void methodA(int i) {
       assert i >= 0 : methodB();
       System.out.println(i);
   }
   private String methodB(){
       return "The value must not be negative";
   }
   public static void main(String args[]){
       AssertTest test = new AssertTest();
       test.methodA(-10);
   }  
}
A. It will print -10.
B. It will result in AssertionError with the message -"The value must not be negative".
C. The code will not compile.
D. None of these
Answer: B

***     ================
2.2 Which of the following are true?
A. Java uses a time-slicing scheduling system for determining which Thread will execute.
B. Java uses a pre-emptive, co-operative system for determining which Thread will execute.
C. Java scheduling is platform dependent and may vary from one implementation to another.
D. You can set the priority of a Thread in code.
Answer: CD

****    ==================
2.3 Which Java collection class can be used to maintain the entries in the order in which they were last accessed?
A. java.util.HashSet
B. java.util.LinkedHashMap
C. java.util.Hashtable
D. java.util.Vector
E. None of these
Answer: B
Note: LinkedHashMap is a very important class of Java's collection framework; it is important to understand its features and usages.

*****   ===================
2.4 What will happen when you attempt to compile and run the following code?
class MyClass {
   static String myName = "SCJP";
   MyClass getMyClass() {    
       System.out.println(myName);
       return null;    
   }
   public static void main(String[ ] args) {
       System.out.println( new MyClass().getMyClass().myName );
   }
}
A. Compile time error
B. Run time error
C. Prints SCJP twice
D. Prints SCJP once
E. None of the above
Answer: C
Note: compiler sees the return type of getMyClass method as MyClass and calling myName on MyClass is valid at compile time.
Also it doesn't give any runtime error which is not very obvious. Please note that a null reference may be used to access a class (static) variable without causing an exception. The static variable is called on the class itself and not on the object. Had the myName variable non-static, the above code at run time would give NullPointerException.

***     =====================
2.5 What results from running the code below?
int a = 5; int b = -2;
System.out.println(a % b);
A. A compiler error saying "%" operator is not valid for negative numbers
B. 1
C. 0
D. -1
E. None of the above
Answer: B
Note: To calculate a % b(a modulus b), the simplest way is, drop any negative signs from both the operands and calculate the result.

***     ================
2.6 A block of text contains 100 words. You are required to make a list of distinct words from those 100 words;moreover you are required to report how many distinct words exist in that block of text. Which Java collection class would you use;and which of its method would give the number of distinct words in the block?
A. java.util.LinkedList class, and its size() method
B. java.util.HashSet class, and its size() method
C. java.util.HashMap class, and its size() method
D. java.util.ArrayList class, and its size() method
E. java.util.Dictionary class, and its size() method
Answer: B

***     ================
2.7 What will be printed by the following code?
String banner = "One man, One vote";
int subInd1 = banner.lastIndexOf("One", 10);
System.out.println(subInd1);
A. 0
B. -1
C. 10
D. None of these
Answer: D 9

*****   =====================
2.8 What results by running the following code fragment?
   int a = 8;
   int b = 3;
   float f = a++/b--;
   System.out.println(f);
A. 3.0
B. 4.5
C. 2.0
D. 2.6
Answer: C
Note: a++/b-- is int, and then implicitly cast to float.

***     ================
2.9 We have the following organization of classes.
class Parent { }
class DerivedOne extends Parent { }
class DerivedTwo extends Parent { }  
Which of the following statements is correct for the following expression?
Parent p = new Parent();
DerivedOne d1 = new DerivedOne();
DerivedTwo d2 = new DerivedTwo();
d1 = (DerivedOne)p;
A. Illegal both compile and runtime
B. Legal at compile time, but fails at runtime
C. Legal at compile and runtime
D. None of the above
Answer: B
Note: Since the object contained in p is not actually a DeriveOne object, the assignment will cause Java to throw a ClassCastException.

****    ===================
2.10 Which of the following will compile and run without an error?
A. Integer i =  new Integer('A');
B. Integer i = new Integer("7");
C. Character c = new Character("A");
D. Boolean b = new Boolean(null);
E. Integer i = new Integer("0x10");
Answer: ABD
Note: Option E will compile correctly but will throw a NumberFormatException at runtime, as the string argument does not represent a string in decimal format. E???


############
test 3
############

*****   =========================
3.1 What will be printed when you execute the following code?
class C {
   C() {
       System.out.print("C");
   }
}
class A {
   C c = new C();
   A() {
       this("A");
       System.out.print("A");
   }
   A(String s) {
       System.out.print(s);
   }
}
class B extends A {
   B() {
       super("B");
       System.out.print("B");
   }
   public static void main(String[] args) {
       new B();
   }
}
A. BB
B. CBB
C. BAB
D. None of these
Answer: B


***     ========================
3.2 Which of the following method(s) must be implemented correctly if the class has to behave properly and consistently with all Java collection classes and interfaces?
A. public int hashCode()
B. protected Object clone()
C. public String toString()
D. public boolean equals(Object obj)
E. public long hashCode()
F. Only option E is correct
Answer: AD


***     ===========================
3.3 If an instance of a class needs to be added to a TreeSet, which interface this class must implement?
(Assume that the TreeSet is instantiated with the default no-argument constructor)
A. java.util.SortedSet
B. java.lang.Cloneable
C. java.lang.Comparable
D. java.util.RandomAccess
E. java.io.Serializable
Answer: C

***     ============================
3.4 The ThreadGroup class instance
A. Allows threads to be manipulated as group.
B. Provides support for ThreadDeath listeners.
C. May contain other ThreadGroups.
D. Must contain threads of the same type.
Answer: AC

*****   ==========================
3.4 What will happen when you compile and run the following code?
public class Test {
   public void myMethod(Object o) {
       System.out.println("My Object");
   }
   public void myMethod(String s) {
       System.out.println("My String");
   }
   public static void main(String args[]) {
       Test t = new Test();
       t.myMethod(null);
   }
}
A. The code does not compile.
B. The code compiles cleanly and shows "My Object".
C. The code compiles cleanly and shows "My String"//更精确地匹配
D. The code throws an Exception at Runtime.
Answer: C


*****   ==========================
3.5 Which of the following results in a negative value of a?
A. int  a = -1; a = a >>> 8;
B. byte a = -1; a = (byte)(a >>> 5);//char only has 16 bytes, that is 65535
C. int  a = -1; a = a >> 5;
D. int  a = -1; a = a >>> 32;
Answer: BCD


****    ==========================
3.6 Which one statement is true about class Animal above and class Tiger below?
1.  package abc;
2.
3.  public class Animal
4.  {
5.      protected static int refCount = 0;
6.      public Animal() {refCount++;}
7.      protected void runFast() { } // Run as fast as you can
8.      static int getRefCount() { return refCount; }
9.  }

1.  package def;
2.  
3.  class Tiger extends abc.Animal
4.  {
5.      Tiger() { refCount++; }
6.      
7.      public static void main(String args[])
8.      {
9.          System.out.println("Before: " + refCount);
10.         Tiger ashtonish = new Tiger();
11.         System.out.println("After: " + refCount);
12.         ashtonish.runFast();
13.     }
14. }
A. Compilation of Tiger fails at line 5 because static members cannot be overridden.
B. Compilation of Tiger fails at line 12 because method runFast() is protected in the superclass.
C. The program will compile and execute. The output will be
Before: 0
After: 1
D. Compilation will succeed, but an exception will be thrown at line 12, because method runFast() is protected in the superclass.
E. The program will compile and execute. The output will be
Before: 0
After: 2
Answer: E


*****   ============================
3.7 What is displayed when the following piece of code is compiled and executed?
class Test {
   public static void main(String [] args) {
           Base b = new Subclass();
           System.out.println(b.x);
           System.out.println(b.method());
       }
}
class Base {
   int x = 2;
   int method(){
           return x;
   }
}
class Subclass extends Base {
   int x = 3;
   int method() {
   return x;
   }
}
A. Nothing. The code fails to compile because the object b is not created in a valid way.
B. 2 3
C. 2 2
D. 3 3
E. 3 2子类引用赋给父类,运行时按父类变量赋值,而方法则用子类的
Answer: B

**      =======================
3.8 What will happen when you attempt to compile and run the following code?
    (Assume that the code is compiled and run with assertions enabled.)
1.  public class AssertTest
2.  {
3.      public static void main(String args[])
4.      {
5.          for(int i=0;i <10;i++)
6.          {
7.              try
8.              {
9.                  assert i%2==0 : i--;
10.                 System.out.println("Even number : " + i);
11.             }
12.             catch(AssertionError ae)
13.             {
14.                 System.out.println("Odd number : " + ++i);
15.             }
16.         }
17.     }
18. }
A. It will print odd and even numbers from 0 to 9 correctly (0 even and 1 odd)
B. It will print odd and even numbers from 0 to 9 incorrectly (0 odd and 1 even)
C. Compilation error at line 9
D. Compilation error at line 10
E. It will result in an infinite loop
Answer: A

**      ====================
3.9 What will happen when you attempt to compile and run the following code?
(Assume that the code is compiled and run with assertions enabled)
1.  public class AssertTest
2.  {
3.      public static void main(String args[])
4.      {
5.          float f1 = Float.NaN;
6.          float f2 = f1;
7.          float f3 = 1.2f;
8.          
9.          try
10.         {
11.             assert (f2 == f1) : f2 = 2;
12.             f3 = 1.5f;
13.         }catch(AssertionError ae)
14.         {
15.             f3++;
16.         }
17.        
18.         f3 += f2;
19.         System.out.println("f3 = " + f3);
20.     }
21. }
A. Compilation error at line 5
B. Compilation error at line 7
C. It will print - f3 = 3.5
D. It will print - f3 = 4.2
E. It will print - f3 = NaN
Answer: D

****    =================
3.10 Which of the following will compile without errors?
A. Byte b = new Byte(123);
B. Byte b = new Byte("123");
C. Byte b = new Byte();//Constructor Summary        
Byte(byte value)
          Constructs a newly allocated Byte object that represents the specified byte value.        
Byte(String s)
          Constructs a newly allocated Byte object that represents the byte value indicated by the String parameter.
  b = 123;
D. Byte b = new Byte((int)123.4);
Answer: B

****    =====================
3.11 What will happen when we try to compile the following code?
1.  public void WhichArray( Object x )
2.  {
3.          if( x instanceof int[] )
4.      {
5.              int[] n = (int[]) x ;
6.              for( int i = 0 ; i < n.length ; i++ )
7.          {
8.                  System.out.println("integers = " + n[i] );
9.              }
10.         }    
11.         if( x instanceof String[] )
12.     {
13.             System.out.println("Array of Strings");
14.         }
15.     }
A. The compiler objects to line 3 comparing an Object with an array.
B. The compiler objects to line 5 casting an Object to an array of int primitives.
C. The compiler objects to line 11 comparing an Object to an array of Objects.
D. It compiles without error.
Answer: D

****    ==================
3.12 Which of the following statements about threading are true?
A. You can only obtain a mutually exclusive lock on methods in a class that extends Thread or implements runnable.
B. You can obtain a mutually exclusive lock on any object.
C. You can't obtain a mutually exclusive lock on any object.
D. Thread scheduling algorithms are platform dependent.
Answer: BD


###############
test 4
###############

*****   =======================
4.1 What will happen when you invoke the following method?
void infiniteLoop(){
   byte b = 1;
   while ( ++b > 0 );
   System.out.println("Welcome to My World!");
}
A. The loop never ends(infinite loop).
B. Prints "Welcome to My World!".
C. Compilation error : ++ operator should not be used for byte type variables.
D. Prints nothing.
Answer: B
NOte: Here the variable 'b' will go up to 127. After that overflow will occur and 'b' will be set to -ve value, the loop ends and prints "Welcome to My World!".

****    =======================
4.2 Which of the following statements are true about java.util.IdentityHashMap?
A. It implements Map interface
B. It is synchronized
C. In an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2).
D. In an IdentityHashMap, two keys k1 and k2 are considered equal if and only if k1.equals(k2) OR if both k1 and k2 are null
E. It violates general contract of the interface Map
F. It keeps its keys in a sorted order
Answer: ACE

****    ===================
4.3 Which of the following results in a positive value of a?
A. int  a = -1; a = a >>> 5;
B. int  a = -1; a = a >>> 32;
C. byte a = -1; a = (byte)(a >>> 30);
D. int  a = -1; a = a >> 5;
Answer: AC

****    =====================
4.4 Select the statements which are valid from the list below.
A. The primitive data type "char" is 16-bits wide.
B. Unicode uses 16-bits to represent a character.
C. Unicode uses 32-bits to represent a character.
D. UTF uses 24-bits to represent a character.
E. UTF uses as many bits as are needed to represent a character.
Answer: ABE

***     =====================
4.5 You are writing a set of classes related to cooking and have created your own exception hierarchy derived from java.lang.Exception as follows:
  Exception
  +-- BadTasteException
         +-- BitterException
         +-- SourException
Your base class, "BaseCook" has a method declared as follows:
  int rateFlavor(Ingredient[] list) throws BadTasteException
class "TexMexCook", derived from BaseCook has a method which overrides BaseCook.rateFlavor(). Which of the following are legal declarations of the overriding method?
A. int rateFlavor(Ingredient[] list) throws BadTasteException
B. int rateFlavor(Ingredient[] list) throws Exception
C. int rateFlavor(Ingredient[] list) throws BitterException
D. int rateFlavor(Ingredient[] list)
Answer: ACD
Note: the overriding method must throw the same exception or a subclass.the overriding method need not have to throw an exception.

*****   =====================
4.6 Which is the most appropriate code snippet that can be inserted at line 18 in the following code?
(Assume that the code is compiled and run with assertions enabled)
1.  import java.util.*;
2.  
3.  public class AssertTest
4.  {
5.      private HashMap cctld;
6.      
7.      public AssertTest()
8.      {
9.          cctld = new HashMap();
10.         cctld.put("in", "India");
11.         cctld.put("uk", "United Kingdom");
12.         cctld.put("au", "Australia");
13.         // more code...
14.     }
15.     // other methods ....  
16.     public String getCountry(String countryCode)
17.     {
18.         // What should be inserted here?
19.         String country = (String)cctld.get(countryCode);
20.         return country;
21.     }
22. }
A. assert countryCode != null;
B. assert countryCode != null : "Country code can not be null" ;
C. assert cctld != null : "No country code data is available";
D. assert cctld : "No country code data is available";
E. assert cctld.size() != 0 : "No country code data is available";
Answer: C
Note: assertions should be used to check for conditions that should never happen.

**      =================
4.7 Which of the following will print exactly 7?
1.  class MyClass
2.  {
3.      public static void main(String args[])
4.      {
5.          double x = 6.5;
6.          System.out.println(Math.floor(x+1));
7.          System.out.println(Math.ceil(x));
8.          System.out.println(Math.round(x));
9.      }
10. }
A. Line 6 only
B. Lines 6 and 7 only
C. Lines 6, 7 and 8
D. None of these
Answer: D 8
Note: is double and output is 7.0

*****   ========================
4.8 Consider the following statement:
   Thread myThread = new Thread();
Which of the following statements are true regarding myThread?
A. The thread myThread is now in a runnable state.
B. The thread myThread has a priority of 5.
C. On calling the start() method on myThread, the run method in the Thread class will be executed.
D. On calling the start() method on myThread, the run method in the calling class will be executed.
Answer: C
Note: the priority of myThread will be inherited from the Thread that called the constructor.



###############
test 5
###############
*****   ========================
5.1 What will happen when you attempt to run the following code from command line using command – java AssertTest?
(Assume that the code is compiled with assertions enabled)
1.  public class AssertTest
2.  {
3.      static int i = 10;
4.      public static void main(String args[])
5.      {
6.          i = i*2;
7.          try
8.          {
9.              assert isValid() : i = i/4;
10.         }
           catch(AssertionError ignore){}
11.        
12.         System.out.println("i = " +i);
13.     }
14.    
15.     public static boolean isValid()
16.     {
17.         i = i * 2;
18.         return false;
19.     }
20. }
A. It will print - i = 20
B. It will print - i = 10
C. It will print - i = 40
D. It will print - i = 5
E. None of these
Answer: A
Note: It is not runtime Assertion enabled! And assert Expression1 cannot have side effect.


***     ===============
5.2 What will happen when you attempt to compile and run the following code?
1.  public class WrapperDemo
2.  {
3.      public static void main(String args[])
4.      {
5.          Character c = new Character('A');
6.          Integer i = new Integer('A');
7.          
8.          int a = c.intValue();
9.          int b = i.intValue();
10.        
11.         if(a == b)
12.             System.out.println("Both are equal");
13.         else
14.             System.out.println("Both are not equal");
15.     }
16. }
A. It will print - Both are equal
B. It will print - Both are not equal
C. It will throw NumberFormatException at runtime
D. Compilation error at line 8
E. Compilation error at line 6
Answer: D
Note: The Wrapper class Boolean and Character do not extend java.lang.Number,and do not implement its intValue() method.


**      =====================
5.3 Given a byte with a value of 01110111, which of the following statements will produce 00111011?
Note : 01110111 = 0x77
A. 0x77 << 1;
B. 0x77 >>> 1;
C. 0x77 >> 1;
D. B and C.
E. None of the above
Answer: D
Note:  Since the leading bit(first bit from left) is a 0, both the >> and >>> operators work identically.


**      ==================
5.4 A class with all its constructors as private can't be extended and instantiated by any other class. True/False?
A. True
B. False
Answer: A
Note: From the child class default constructor, there is a default call to the parent class default constructor.


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


*****   ========================
5.6 Comment if the following code implements hashCode() method of Object class correctly? Select the most appropriate answer.
1.  public class CorrectHashCode
2.  {
3.      private int number;
4.      
5.      public CorrectHashCode(int i)
6.      {
7.          number = i;
8.      }
9.      
10.     public int hashCode()
11.     {
12.         int i = (int)(Math.random() * 100);
13.         return i * number;
14.     }
15.    
16.     // other methods
17. }
A. The code implements hashCode() method correctly
B. The code does not implement hashCode() method correctly
C. This implementation of hashCode() method is correct if only if the equals() method is not overridden
D. The given code does not contain enough information to comment on the correctness of the hashCode() method implementation
E. None of these
Answer: B


*****   ====================
5.7 What will happen if you compile/run this code? Assume the code to be written inside main().
int i = 012;
int j = 034;
int k = 056;
int l = 078;//error, 八进制越过范围
System.out.println(i);
System.out.println(j);
System.out.println(k);
A. Prints 12, 34 and 56.
B. Prints 24, 68 and 112.
C. Prints 10, 28 and 46.
D. Compilation error.
Answer: D


****    =====================
5.8 Which of the following is a valid way to declare an abstract method which is intended to be public?
A. public abstract method();
B. public abstract void method();
C. public abstract void method(){}
D. public virtual void method();
E. public void method() implements abstract;
Answer: B
Note: the {} braces indicate that the method is actually implemented, and is therefore not abstract. In other words, even empty braces are a valid way to define a method.


**      ====================
5.9 What is the effect of adding the sixth element to a Vector created using the following code?
   new Vector(5, 10);
A. An IndexOutOfBounds exception is thrown.
B. The vector grows in size to a capacity of 10 elements.
C. The vector grows in size to a capacity of 15 elements.
D. Nothing. Size is the number of the elements in vector, while capacity will increase. The Vector will have grown when the fifth element was added, because Vector elements are zero-based.


***     ================
5.10 You have created a TimeOut class as an extension of Thread, the purpose being to print a"Time's Up" message if the Thread is not interrupted within 10 seconds of being started. Here is the run method which you have coded.
1.  public void run()
2.  {
3.          System.out.println("Start!");
4.          try
5.      {
6.              Thread.sleep(10000 );
7.              System.out.println("Time's Up!");
8.          }
9.      catch(InterruptedException e)
10.     {
11.                 System.out.println("Interrupted!");
12.         }
13.     }
Given that a program creates and starts a TimeOut object, which of the following statements is true?
A. Exactly 10 seconds after the start method is called, "Time's Up!" will be printed.
B. Exactly 10 seconds after "Start!" is printed, "Time's Up!" will be printed.
C. The delay between "Start!" being printed and "Time's Up!" will be 10 seconds plus or minus one tick of the system clock.
D. If "Time's Up!" is printed you can be sure at least 10 seconds have elapsed since "Start!" was printed.
Answer: D


*       ===================
5.11 Which of the following are the correct and appropriate implementations of the hashCode() method that can be inserted at line 20 in this code;so that the code compiles correctly and the general contracts of equals and hashCode methods are observed.
1.  public class CorrectHashCode
2.  {
3.      private int number;
4.      
5.      public CorrectHashCode(int i)
6.      {
7.          number = i;
8.      }
9.      
10.     public boolean equals(Object obj)
11.     {
12.         if(obj instanceof CorrectHashCode)
13.         {
14.             return
15.             (number == ((CorrectHashCode)obj).number);
16.         }
17.         return false;
18.     }
19.    
20.     // which implementation of hashCode should be inserted here?
21. }
A.  public int hashCode() {
       Integer num = new Integer(number);
       return num.hashCode();
   }
B.  public int hashCode(){
       int i = (int)(Math.random() * 100);
       return i * number;
   }
C.  public int hashCode(){
       return number;
   }
D.  public long hashCode(){
       Integer num = new Integer(number);
       return num.hashCode();
   }
Answer: AC


###########
test 6
###########
***     ==================
6.1 You wish to store a small amount of data and make it available for rapid access. You do not have a need for the data to be sorted, uniqueness is not an issue and the data will remain fairly static Which data structure might be most suitable for this requirement?
A. TreeSet
B. HashMap
C. LinkedList
D. An array
Answer: D

***     ==================
6.2 What will happen when you attempt to compile and run the following code?
public class MyThread extends Thread {
   String myName;
   MyThread(String name){
       myName = name;
   }
   public void run(){
       for(int i=0; i<100;i++) {
           System.out.println(myName);
       }
   }
   public static void main(String args[]){
       try {
           MyThread mt1 = new MyThread("mt1");
           MyThread mt2 = new MyThread("mt2");
           mt1.start();
           // XXX
           mt2.start();
       }
       catch(InterruptedException ex){}
   }
}
A. The above code in its current condition will not compile.
B. In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), mt1.join(); can be placed at //XXX position.
C. In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), mt1.sleep(100); can be placed at //XXX position.
D. In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), mt1.run(); can be placed at //XXX position.
E. In order to make the MyThread class prints "mt1" (100 times) followed by "mt2" (100 times), there is no need to write any code.
Answer: AB
Note: the above code will not compile as "InterruptedException" is never thrown in the try block.

****    =========================
6.3 The no-argument constructor provided by the compiler when no constructor is explicitly provided in the code is always public. True/False?
A. True
B. False
Answer: B
Note: The access modifier for the default constructor provided by the compiler is the same as that of the class to which the constructor belongs.

****    ========================
6.4 What will be output by the following statement?
System.out.println(1 << 32);
A. 1
B. -1
C. 32
D. -2147483648
Answer: A
Note: With the left shift operator the bits will "wrap around" i.e. the shift takes place by (32 % 32) = 0 bits. Thus the result of System.out.println(1 << 32) would be 1.

***     ====================
6.5 Which of the following can be applied to constructors?
A. final
B. static
C. synchronized
D. native
E. None of these
Answer: E
Note: a constructor cannot be synchronized as objects are owned by threads and never any two threads can share a single object.

***     ==================
6.6 Which of the following are valid statements regarding the following piece of code?
1. String s1 = "abcd";
2. StringBuffer sb1 = new StringBuffer("abcd");
3. int val = 6;
4. System.out.println(s1 + val);
5. System.out.println(sb1 + val);
A. The text "abcd6" is displayed followed by "abcd6".
B. The code fails to compile because String conversion does not apply to StringBuffer.
C. The code compiles but upon execution, throws a NullPointerException at line 5.
D. The code fails to compile at line 2, because this is not a valid way to create a StringBuffer.
Answer: B
Note: but "sb1 + s1" is OK.

****    ====================
6.7 Which of the following can be inserted at line 10, so that the code compiles and prints the required result.
public class WrapperDemo {
   public static void main(String args[]) {
       System.out.println(getArea(7));
   }
   public static Double getArea(int r) {
       // what should be inserted here?
   }
}
A. return Double.valueOf(Math.PI*r*r);
B. return Double.parseDouble(Math.PI*r*r);
C. return Double.parseDouble("" + Math.PI*r*r);
D. return new Double(Math.PI*r*r);
E. return Double.valueOf("" + Math.PI*r*r);
F. Only option D is correct
Answer: DE
Note:  The static method valueOf(String s) takes a String parameter representing double value and returns a Double object holding this value.

****    =====================
6.8 Consider the class hierarchy shown below:
           FourWheeler
   (implements DrivingUtilities)
           / / \ \
         /  /   \  \
       /   /     \   \
     /    /       \    \
   /     /         \     \
Car  Truck        Bus  Crane
Consider the following code below:
1.  DrivingUtilities du;
2.  FourWheeler fw = new FourWheeler();
3.  Car myCar;
4.  du = (DrivingUtilities)fw;
5.  myCar = (Car)du;
Which of the statements below are true?
A. The code will compile and run.
B. The code will compile but will throw an exception at runtime because the runtime class of du cannot be converted to myCar, because going down the hierarchy is not allowed.
C. The code at line4 will compile even without the explicit cast.
D. Line 5 will not compile because an interface cannot be casted to a class.
Answer: Bc
Note: C is correct because at runtime the variable du holds a reference to an object of class FourWheeler which cannot be converted to an object of class myCar as it makes it go down the hierarchy which is illegal.

****    ====================
6.9 Which of the following is true regarding main Thread?
A. It is the thread from which other "child" threads will be spawned.
B. It must be the last thread to finish execution. When the main thread stops, the program terminates.
C. It has the highest priority.
D. main is not a thread.
Answer: AB
Note: First of all please note that main is a thread. By default it has normal priority of 5. You can check this by "Thread t = Thread.currentThread();" and then checking the priority by calling getPriority() method.

***     =======================
6.10 What will happen when you attempt to compile and run the following code?
1.  public class Test
2.  {
3.      public static void main(String args[])
4.      {
5.          Boolean b1 = new Boolean("Yes");
6.          Boolean b2 = new Boolean("No");
7.          Object obj = new Boolean(b2.equals(b1));
8.          
9.          System.out.println(obj);
10.     }
11. }
A. Compilation error at line 5
B. Compilation error at line 6
C. Compilation error at line 7
D. It will print - true
E. It will print - false
Answer: D

***     ===================
6.11 What will happen when you attempt to compile and run the following code?
(Assume that the code is compiled and run with assertions enabled)
1.  public class AssertTest
2.  {
3.      public static void main(String args[])
4.      {
5.          int i = 5;      
6.          Object obj1 = new Object();
7.          Object obj2 = obj1;
8.          
9.          try
10.         {
11.             assert obj1.equals(obj2) : i += 10;
12.         }
13.         catch(AssertionError ignore){}
14.         System.out.println(i);
15.     }
16. }
A. Compilation error at line 11
B. Compilation error at line 13
C. It will print-10
D. It will print-15
E. It will print-5
Answer: E
Note; can catch AssertionError


############
test 7
############
***     ================
7.1 What will happen when you attempt to compile and run the following code?
1.  public class TestEqual
2.  {
3.      public static void main(String args[])
4.      {
5.          Boolean bool[] = new Boolean[5];
6.          bool[0] = new Boolean("true");
7.          bool[1] = new Boolean(false);
8.          
9.          System.out.print(bool[0].equals(bool[3]));
10.         System.out.print(" " + bool[1].equals(bool[3]));
11.     }
12. }
A. The code will not compile
B. It will throw NullPointerException at runtime
C. It will print - false false
D. It will print - false true
E. It will print - true false
Answer: C

*****   =====================
7.2 What will happen when you compile and run the following code?
public class MyClass{
   private static int x = getValue();
   private static int y = 5;
   private static int getValue() {  
       return y;
   }
   public static void main(String args[]) {
       System.out.println(x);
   }  
}
A. Compiler error complaining about access restriction of private variables of MyClass.
B. Compiler error complaining about forward referencing.
C. prints 0
D. prints 10
Answer: C
Note: as y = 5 is not called before "x = getValue()".

*****   =================
7.3 If a.equals(b) is true, which of the following statements are always true?
(Assume that the classes of a and b have overridden all the required methods correctly)
A. b.equals(a) is always true
B. a == b is always true
C. a.getClass() == b.getClass() is always true
D. a.hashCode() == b.hashCode() is always true
E. Only option A is correct
Answer: AD
Note: The general contract of hashCode() method of Object class mentions : If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
If you are designing a class that overrides equals method, it is generally necessary to override the hashCode method as well, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
Note that converse of this is not correct. i.e. if a.equals(b) is false, the hash codes returned by them need not be different.

**      ==================
7.4 Which of the following keywords can be applied to the variables or methods of an interface?
A. static
B. private
C. synchronized
D. protected
E. public
Answer: AE

***     =====================
7.5 What is displayed when the following code fragment is compiled and executed (assume that the enveloping class and method is correctly declared and defined):
StringBuffer sb1 = new StringBuffer("abcd");
StringBuffer sb2 = new StringBuffer("abcd");
String s1 = new String("abcd");
String s2 = "abcd";
System.out.println(s1==s2);
System.out.println(s1=s2);
System.out.println(sb1==sb2);
System.out.println(s1.equals(sb1));
System.out.println(sb1.equals(sb2));
A. The code fails to compile, complaining that the line System.out.println(s1=s2); is illegal.
B. The code fails to compile because the equals() method is not defined for the StringBuffer class.
C. false true true false false
D. false abcd false false false
E. false true false false false
Answer: D
Note: StringBuffer does not override the equals() method, and so will always only compare the object references.

***     ====================
7.6 The Class class has no public constructor.
A. True
B. False
Answer: A
Note: Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

*****   =========================
7.7 What will be printed by executing the following code?
1.  String s1 = new String("Case Matters");
2.  String s2 = new String("case matters");
3.  String s3 = s1.toLowerCase();
4.  String s4 = s2.toLowerCase();
5.  System.out.print((s1 == s3) + " ");
6.  System.out.print((s2 == s4) + " ");
7.  System.out.print((s3 == s4) + " ");
A. false false false
B. false true true
C. true true true
D. true false true
E. None of these
Answer: E
Note: When changing the case of strings the rule is that the original string is returned if there is no change required otherwise a new string object is created.

***     ========================
7.8 What results from the following code fragment?
1.  int i = 5;
2.  int j = 10;
3.  System.out.println(i + ~j);
A. Compilation error because "~" doesn't operate on integers
B. -5
C. -6
D. 15
Answer: C
Note: Java allows you to use ~ operator for integer type variables and The shortest way to calculate is ~j  = (- j) - 1


############
test 8
############

***     ====================
8.1 What is the result when you compile and run the following code?
public class ThrowsDemo {  
   static void throwMethod() {  
       System.out.println("Inside throwMethod.");  
       throw new IllegalAccessException("demo");  
   }
   public static void main(String args[]) {  
       try {  
           throwMethod();  
       } catch (IllegalAccessException e) {  
           System.out.println("Caught " + e);  
       }  
   }  
}
A. Compilation error
B. Runtime error
C. Compiles successfully, nothing is printed.
D. prints : Inside throwMethod. followed by caught: java.lang.IllegalAccessExcption: demo
Answer: A
Note: java.lang.IllegalAccessExcption must be caught or it must be declared in the throws clause of the throwMethod().

*****   ===============
8.2 What will happen when you compile and run the following code?
public class MyClass {
   public static void main(String args[]) {
       byte b = 0;
       b += 1;
       System.out.println(b);
   }
}
A. Compile time error
B. Runtime error
C. 1
D. None of these
Answer: C
Note: If "b += 1" change to "b = b++", it also prints 1.But if it change to "b = b + 1",then compile errer take place,because "b + 1" case to int.

****    =======================
8.3 It is valid to throw (and re-throw) an exception inside a catch{} clause.
For example:
    ...
       catch (Exception e) {
           throw e;
       }
A. True
B. False
Answer: A
Note: This is valid. It will cause the exception to be passed to the handlers at the next-higher level. All further catch clauses are ignored in the current try block.

*****   =====================
8.4 What is the output of the following code?
1.  public class Note
2.  {
3.          public static void main(String args[])
4.      {
5.              String name[] = {"Killer","Miller"};
6.              String name0 = "Killer";        
7.              String name1 = "Miller";
8.              swap(name0, name1);
9.              System.out.println(name0 + ", " + name1);
10.             swap(name);
11.             System.out.println(name[0] + ", " + name[1]);
12.         }
13.         public static void swap(String name[])
14.     {
15.             String temp;
16.             temp = name[0];
17.             name[0] = name[1];
18.             name[1] = temp;
19.         }  
20.         public static void swap(String name0, String name1)
21.     {
22.             String temp;
23.             temp = name0;
24.             name0 = name1;
25.             name1 = temp;
26.         }    
27.     } // end of Class Note
A. Killer, Miller followed by Killer, Miller
B. Miller, Killer followed by Killer, Miller
C. Killer, Miller followed by Miller, Killer
D. Miller, Killer followed by Killer, Miller
Answer: C
Note: In java all parameters are passed by value. In case of primitives, the copy of the variable is passed while case of object references, its the copy of the reference which is passed.

*****   ===================
8.5 Comment if the following code implements equals method of Object class correctly?     Select the most appropriate answer.
1.  public class BetterString
2.  {
3.      String str;
4.      
5.      public BetterString(String s)
6.      {
7.          str = s;
8.      }
9.      
10.     public boolean equals(Object obj)
11.     {
12.         if(obj instanceof BetterString)
13.         {
14.             if(obj == this)
15.                 return true;
16.             else
17.                 return str.equals(obj);
18.         }
19.         else if(obj instanceof String)
20.         {
21.             return str.equals(obj);
22.         }
23.         return false;          
24.     }
25. }
A. The code implements equals method correctly
B. The code implements equals method correctly, but does not provide any additional feature over the equals method provided by String class
C. The code does not implement equals method correctly
D. The given code does not contain enough information to comment on the correctness of the equals method implementation
E. None of these
Answer: C
Note: The code attempts to provide equals comparison with a String. String is a built in final class in Java. It is inappropriate as well as incorrect to provide an equals comparison with any built in Java class, as it violates "symmetry" requirement mentioned in the general contract of Object's equals method. It says - for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. This is not valid for the above code, because if an object of class BetterString is passed to the equals method of String class, it would result in false;irrespective of its contents.

****    ===================
8.6 A Java monitor must either extend Thread or implement Runnable. True/False?
A. True
B. False
Answer: B
Note: as a monitor is any object that has synchronized code. Thus a Java monitor need not extends Thread class or implement Runnable interface.

***     =====================
8.7 What will be the result of executing the following code?
Given that Test1 is a class.
1. Test1[] t1 = new Test1[10];
2. Test1[][] t2 = new Test1[10][];
3. System.out.println(t2[0][0]);
A. The code will not compile as we are using t2[0][0] without initializing
B. The code will compile and print null
C. The code will compile but throw a runtime exception
D. None of these
Answer: C
Note: In case of arrays initialization is supposed to be complete when we specify the leftmost dimension of the array. The problem occurs at runtime if we try to access an element of the array which has not been initialized (specification of size).

*****   =========================
8.8 What will be the result of executing the following code?
int i = 0;
int myArray[] = new int[0];
for (i = 0; i < myArray.length; i++){
   System.out.println(myArray[i]);
}
A. The code will not compile as the size of array should be at least 1
B. The code will compile but throw an exception at runtime
C. The code will compile and "0" will be printed
D. None of these
Answer: D
Note:  The code will compile and run perfectly fine but it will not print anything. It is perfectly legal in Java to create arrays of size zero. The flow of control will never enter the for loop as the condition at the beginning of for loop is never satisfied. But note that If you directly print "myArray" and not in the for loop,then complie error that ArrayIndexOutOfBoundException(???).

***     ===================
8.9 For what reasons might a thread stop execution?
A. A thread with higher priority began execution.
B. The thread's wait() method was invoked.
C. The thread invoked its yield() method.
D. The thread's pause() method was invoked. //has destroy(), hasn’t pause().
E. The thread's sleep() method was invoked.
Answer: ABCE

****    =======================
8.10 Which of the following can be used for reading the system property named "count"?
The value of this property will be a string representing a number in the range 1 to 1000.
A. Integer.decode("count");
B. Integer.getProperty("count");
C. Integer.getSystemProperty("count");
D. Integer.getInteger("count");
E. Integer.valueOf("count");
Answer: D
Note:  The static method getInteger(String propertyName) is of form:
public static Integer getInteger(String nm)
This method returns the integer value of the system property with the specified name.


##########
test 9
##########

**      ==================
9.1 What will be the output when you compile and execute the following program?
class Base extends Thread {
   public void run() {
       while(true)
       System.out.println("Start running..");  
   }
   static public void main(String[] a) {
       Base anObj = new Base();
       anObj.start();
   }
}
A. Start running..
B. Start running..  
  ..............
  in an infinite loop
C. Compilation error. Cannot extend Thread class
D. No output
Answer: B

**      =======================
9.2 If a thread executes wait(), and subsequently gets notified, it immediately proceeds with execution of the code that follows the wait() call. True/False?
A. True
B. False
Answer: B

*****   =======================
9.3 Will there be any problem in a multi-threaded context if only local variables are declared in a method?
A. Yes, you need synchronized in the blocks of code which read and write a local variable value.
B. Yes, you need synchronized in the blocks of code which read (but not write) a local variable value
C. Absolutely no
D. None of the above.
Answer: C
Note: In case you have local variables (variables declared in a method), then there is no problem of synchronization in a multi-threaded context. The local variables are accessed from the thread's stack, the instance variables are accessed through object references, and static variables are accessed through class or object references. The local variables in the methods that the thread is executing are separate for different threads. There is no way for one thread to access the local variables of another thread. While objects and their instance variables can be shared between threads in a java program, for that one thread needs to pass the object reference to the other thread. The static variables are automatically shared between all threads in a java program.

*****   =================
9.4 Which of the following are correct and proper usages of assertions?
A:private void doSomething(int value) {
   assert (value > 0 && value < 1000)  : "The value must be in the range [1 -999]";
   // more code
}
B:public void doSomething(int value) {
   assert (value > 0 && value < 1000)  : "The value must be in the range [1 -999]";
   // more code
}
C:private int doSomething() {
   // compute result
   assert result > 0 : "Incorrect result";
   return result;
}
D:public int doSomething() {
   // compute result
   assert result > 0 : "Incorrect result";
   return result;
}
A. A is a proper usage
B. B is a proper usage
C. C is a proper usage
D. D is a proper usage
Answer: B??????????
Note: This is a very important concept in assertions. Assertions can be used to test preconditions, postconditions and invariants. Java insists that assertions should not be used for testing the preconditions of the public methods. Instead, preconditions on public methods are enforced by explicit checks inside methods resulting in particular, specified exceptions. This is essential for two reasons-
(1) Exceptions can be explicitly mentioned in the throws cause of the method, and checked exceptions must be caught while invoking the method.
(2) Assertions can be disabled while running the code.
However, postcondition checks are best implemented via assertions, whether or not they are specified in public methods.

****    ==================
9.5 Which of the following can be inserted at line 12 so that the code compiles and prints the odd numbers in the given range?
1.  import java.util.ArrayList;
2.  
3.  public class OddNumbers
4.  {
5.      public static void main(String args[])
6.      {
7.          ArrayList oddNumbers = new ArrayList();
8.          for(int i=0;i < 10;i++)
9.          {
10.             if(i%2 == 0)
11.                 continue;
12.             // what should be inserted here?
13.             oddNumbers.add(number);
14.             System.out.println(number);
15.         }
16.     }
17. }
A. int number = i;
B. Integer number = new Integer(i);
C. Byte number = new Byte(i);
D. Integer number = Integer.parseInt("" + i);
E. Object number = new Integer(i);
Answer: BE

**      =====================
9.6 What will happen when you attempt to compile and run the following code?
interface MyInterface{
   int x = 0;
   int myMethod(int x);
}
class MyImplementation implements MyInterface{
   public int myMethod(int x){
       return super.x;
   }
}
public class MyTest{
   public static void main(String args[]) {
       MyInterface mi = new MyImplementation();
       System.out.println(mi.myMethod(10));
   }
}
A. 0
B. 10
C. Compilation error
D. None of the above
Answer: The statement "super.x;" inside myMethod() will cause compilation error as the super class of MyImplementation class (Object class) doesn't define variable x. Please note that MyInterface is not the super class of MyImplementation class as referred by super.x.

****    =========================
9.7 What is displayed when the following piece of code is executed?
class Test extends Thread{
   public void run(){
       System.out.println("1");
       yield();
       System.out.println("2");
       suspend();
       System.out.println("3");
       resume();
       System.out.println("4");
   }
   public static void main(String []args) {
       Test t = new Test();
       t.start();
   }
}
A. 1  2  3  4
B. 1  2  3
C. 1  2
D. Nothing. This is not a valid way to create and start a thread.
E. 1
Answer: C
Note: The code will run, but the thread suspends itself after displaying "2". Threads cannot un-suspend themselves (since they ARE suspended and therefore not running!).

**      =======================
9.8 Consider the following code fragment, and select the correct statements(s).
1.  public class Test extends MyBase implements MyInterface
2.  {
3.          int x = 0;
4.
5.          public Test(int inVal) throws Exception
6.          {
7.                  if (inVal != this.x)
8.                  {
9.                      throw new Exception("Invalid input");
10.                 }
11.         }
12.
13.         public static void main(String args[])
14.         {
15.                 Test t = new Test(4);
16.         }
17. }
A. The code fails to compile at line 1. It is not valid to both implement an interface and extend from a parent class simultaneously.
B. The code fails to compile at line 5. It is not valid for constructors to throw exceptions.
C. The code fails to compile at line 9, because this is not valid way to throw an exception.
D. The code fails to compile at line 15. The compiler complains that there is an uncaught exception.
E. The code fails to compile at line 7, because this is not a valid way to reference variable x.
Answer: D

****    ===================
9.9 The default implementation of equals() method in Object class does not perform "deep" comparison. State true or false.
A. True
B. False
Answer: A

posted on 2007-05-24 10:21 liaojiyong 阅读(1786) 评论(0)  编辑  收藏 所属分类: Java认证试题


只有注册用户登录后才能发表评论。


网站导航: