OCP 804 Exams -07

      在〈OCP 804 Exams -07〉中尚無留言
Q-121
class Counter extends Thread{
   int i=10;
   public synchronized void display(Counter obj){
      try{
         Thread.sleep(5);
         obj.increment(this);
         System.out.println(i);
     }catch(InterruptedException ex){}
   }
   public synchronized void increment(Counter obj){
      i++;
   }
}
public class Test{
   public static void main(String[] args){
      final Counter obj1=new Counter();
      final Counter obj2=new Counter();
      new Thread(new Runnable(){
         public void run(){obj1.display(obj2);}
      }).start();
      new Thread(new Runnable(){
         public void run(){obj2.display(obj1);}
      }).start();
   }
}
From what threading problem does the program suffer?
A. deadlock
B. livelock
C. starvation
D. race condition


Answer: A
Q-122
Given the code fragment:
public class IsContentSame {
   public static boolean isContentSame() throws IOException {
      Path p1 = Paths.get("D:\\faculty\\report.txt");
      Path p2 = Paths.get("C:\\student\\report.txt");
      Files.copy(p1, p2, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES,LinkOption.NOFOLLOW_LINKS );
      if (Files.isSameFile(p1, p2)) {
         return true;
      } 
      else {
         return false;
      }
   }
   public static void main(String[] args) {
      try {
         boolean flag = isContentSame();
         if (flag) {
            System.out.println("Equal");
         } else {
            System.out.println("Not equal");
         }
      } catch (IOException e) {
         System.err.println("Caught IOException: " + e.getMessage());
      }
   }
}
What is the result when the result.txt file already exists in c:\student?
A. The program replaces the file contents and the file's attributes and prints Equal.
B. The program replaces the file contents as well as the file attributes and prints Not equal.
C. An unsupportedoperationException is thrown at runtime.
D. The program replaces only the file attributes and prints Not equal.


Answer: B
Q-123
Given the following incorrect program
class MyTask extends RecursiveTask{
   final int low;
   final int high;
   static final int THRESHOLD=/*...*/;
   MyTask(int low, int high){
      this.low=low;
      this.high=high;
   }
   Integer computeDirectly(){/*...*/}
   protected void compute(){
      if(high-low<=THRESHOLD)
         return computeDirectly();
      int mid=(low+high)/2;
      invokeAll(new MyTask(low, mid), new MyTask(mid, high));
   }
}
Which two changes make the program work correctly?
A. Results must be retrieved from the newly created MyTask instances and combined.
B. The threshold value must be increased so that the overhead of task creation does not dominate the cost of computation.
C. The midpoint computation must be altered so that it splits the workload in an optimal manner.
D. The compute () method must be changed to return an Integer result.
E. The compute () method must be enhanced to (fork) newly created tasks.
F. The myTask class must be modified to extend RecursiveAction instead of RecursiveTask


Answer: AD
protected void compute()需改為protected Integer compute()
最後一行需改為return xxx.compute()+xxx.join();
Q-124
Given the database table
And given this class:
public boolean evaluate(Rowset rs){
   CacheRowSet crs=(CacheRowSet)rs;
   try{
      float columnValue=crs.getFloat(3);
      if((columnValue>=this.low) && (columnValue<=this.high)){
        return true;
      }
   }catch(Exception e){
      System.out.println("Exception caugh in filter");
      return false;
   }
}
Assume that the SQL integer queries are valid. What is the result of compiling and executing this code fragment?
Refer to the exhibit.

Q-125
Given that myFile.txt contains:
First
Second
Third
And given:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile04 {
   public static void main(String[] args) {
      try (BufferedReader buffIn =
           new BufferedReader(new FileReader("D:\\faculty\\myfile.txt"))) {
         String line = "";
         int count = 1;
         buffIn.mark(1);
         line = buffIn.readLine();
         System.out.println(count + ": " + line);
         line = buffIn.readLine();
         count++;
         System.out.println(count + ": " + line);
         buffIn.reset();
         line = buffIn.readLine();
         count++;
         System.out.println(count + ": " + line);
      } catch (IOException e) {
         System.out.println("IOException");
      }
   }
}
What is the result?
A. 1: First
   2: Second
   3: Third
B. 1: First
   2: Second
   3: First
C. 1: First
   2: First
   3: First
D. IOExcepton
E. Compilation fails


Answer: B
Q-126
Given:
public class Print01 {
   public static void main(String[] args) {
      double price = 24.99;
      int quantity = 2;
      String color = "Blue";
      // insert code here. Line ***
   }
}
Which two statements, inserted independently at line ***, enable the program to produce the following output:
We have 002 Blue pants that cost $24.99.
A. System.out.printf("We have %03d %s pants that cost $%3.2f.\n",quantity, color, price);
B. System.out.printf("We have$03d$s pants that cost $$3.2f.\n",quantity, color, price);
C. String out = String.format ("We have %03d %s pants that cost $%3.2f.\n",quantity, color, price); 
   System.out.println(out);
D. String out = System.out.format("We have %03d %s pants that cost $%3.2f.",quantity, color, price);
   System.out.println(out);
E. System.out.format("We have %s%spants that cost $%s.\n",quantity, color, price);


Answer: AC
Q-127
Given the cache class:
public class Cache<T> {
   private T t;
   public void setValue (T t) { this.t=t; }
   public T getValue() {return t; }
}
What is the result of the following?
Cache<> c = new Cache<Integer>(); // Line 1
c.setValue(100); // Line 2
System.out.print(c.getValue().intValue() +1); // Line 3
A. 101
B. Compilation fails at line 1.
C. Compilation fails at line 2.
D. Compilation fails at line 3.


Answer: B
Q-128
Given the code fragment:
public class Base {
   BufferedReader br;
   String record;
   public void process() throws FileNotFoundException {
      br = new BufferedReader(new FileReader("manual.txt"));
   }
}
public class Derived extends Base {
   // insert code here. Line ***
   public static void main(String[] args) {
      try {
         new Derived().process();
      } catch (Exception e) { }
   }
}
Which code fragment inserted at line ***, enables the code to compile?
A. public void process () throws FileNotFoundException, IOException { 
      super.process ();
      while ((record = br.readLine()) !=null) {
         System.out.println(record);
      }
   }
B. public void process () throws IOException {
      super.process ();
      while ((record = br.readLine()) != null) {
         System.out.println(record);
      }
   }
C. public void process () throws Exception {
      super.process ();
      while ((record = br.readLine()) !=null) {
         System.out.println(record);
      }
   }
D. public void process (){
      try {
         super.process ();
         while ((record = br.readLine()) !=null) {
            System.out.println(record);
         }
      }
      catch (IOException | FileNotFoundException e) { }
   }
E. public void process (){
      try {
         super.process ();
         while ((record = br.readLine()) !=null) {
            System.out.println(record);
         }
      }
      catch (IOException e) {}
    }


Answer: E
A : 多了IOException
B : 只能是FileNotFoundException 或其子類別, 或不丟
C : 同 B
D : 多重catch不能有父子關係
Q-129
An application is waiting for notification of changes to a tmp directory using the following code statements:
Path dir = Paths.get("tmp")
WatchKey key = dir.register (watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY) ;
In the tmp directory, the user renames the file testA to testB,
Which statement is true?
A. The events received and the order of events are consistent across all platforms.
B. The events received and the order of events are consistent across all Microsoft Windows versions.
C. The events received and the order of events are consistent across all UNIX platforms.
D. The events received and the order of events are platform dependent.


Answer: A
Q-130
QUESTION 130
Given:
StringBuffer b = new StringBuffer("3");
System.out.print(5+4+b+2+1);
What is the result?
A. 54321
B. 9321
C. 5433
D. 933
E. Output is Similar to: 9java.lang.StringBuffer@100490121.
F. Compilation fails.


Answer: F
StringBuffer不能用 "+" 連結字串
Q-131
Which four are true about enums?
A. An enum is typesafe.
B. An enum cannot have public methods or fields.
C. An enum can declare a private constructor.
D. All enums implicitly implement Comparable.
E. An enum can subclass another enum.
F. An enum can implement an interface.


Answer: ACDF
Enum不能有子類別
Q-132
Given:
abstract class Boat {
   String doFloat() { return "floating"; }
   abstract void doDock();
}
class Sailboat extends Boat {
   public static void main(String[] args) {
      Boat b = new Sailboat(); // Line A
      Boat b2 = new Boat(); // Line B
   }
   String doFloat() { return "slow float"; } // Line C
   void doDock() { } // Line D
}
Which two are true about the lines labeled A through D?
A. The code compiles and runs as is.
B. If only line A is removed, the code will compile and run.
C. If only line B is removed, the code will compile and run.
D. If only line D is removed, the code will compile and run.
E. Line C is optional to allow the code to compile and run.
F. Line C is mandatory to allow the code to compile and run.


Answer: CE
mandatory [ˋmændə͵torɪ] : 強制的, 義務的
Q-133
Given the code fragment:
10 try {
11    String query = "SELECT * FROM Employee WHERE ID=110";
12    Statement stmt = conn.createStatement();
13    ResultSet rs = stmt.executeQuery(query);
14    System.out.println("Employee ID: " + rs.getInt("ID"));
15 } catch (Exception se) {
16    System.out.println("Error");
17 }
Assume that the SQL query matches one record. What is the result of compiling and executing this code?
A. The code prints Error.
B. The code prints the employee ID.
C. Compilation fails due to an error at line 13.
D. Compilation fails due to an error at line 14.


Answer: A
少了rs.next(), 則cursor依然停在BOF, 會出現SQLException
Q-134
Given the directory structure that contains three directories: company, Salesdat, and Finance:
Company
  Salesdat
     Target.dat
  Finance
     Salary.dat
  Annual.dat
And the code fragment:
public class SearchApp extends SimpleFileVisitor<Path> {
   private final PathMatcher matcher;
   SearchApp() {
      matcher = FileSystems. getDefault().getPathMatcher("glob:*.dat");
   }
   void find(Path file) {
      Path name = file.getFileName(); 
      if(name != null && matcher.matches(name)) { 
         System.out.println(name);
      }
   }
   public FileVisitResult visitFile (Path file, BasicFileAttributes attrs){
      find (file);
      return FileVisitResult.CONTINUE;
   }
   public static void main (String[] args) throws IOException{
      SearchApp obj=new SearchApp();
      Files.walkFileTree(Paths.get("//company"), obj);
   }
}
If Company is the current directory, what is the result?
A. Prints only Annual.dat
B. Prints only Salesdat, Annual.dat
C. Prints only Annual.dat, Salary.dat, Target.dat
D. Prints at least Salesdat, Annual.dat, Salary.dat, Target.dat


Answer: C
public FileVisitResult visitFile()是在找到檔案時才動作, 如果是目錄的話, 不會進入此方法
如果連目錄都要動作的話, 需寫在public FileVisitResult preVisitDirectory()的方法裏
"*.dat" 是以 ".dat" 為結尾的字串
如果是 "*dat" or "**dat", 又在preVisitDirectory()有find()的話, 才會印出Salesdat
Q-135
Given:
import java.util.Scanner;
public class Painting {
   public static void main(String[] args) {
      String input = "Pastel, *Enamel, Fresco, *Gouache";
      Scanner s = new Scanner(input);
      s.useDelimiter(",\\s*");
      while (s.hasNext()) {
         System.out.print(s.next()+" ");
      }
   }
}
What is the result?
A. Paste1 Ename1 Fresco Gouache
B. Paste1 *Ename1 Fresco *Gouache
C. Pastel Ename1 Fresco Gouache
D. Pastel Ename1, Fresco Gouache


Answer: B
"," 作為分隔號
"\\s*" 是多個空格的話, 也作分隔號
Q-136
Which type of ExecutorService supports the execution of tasks after a fixed delay?
A. DelayedExecutorService
B. ScheduledExecutorService
C. TimedExecutorService
D. FixedExecutorService
E. FutureExecutorService


Answer: B
Q-137
How many Threads are created when passing task to an Executor instance?
A. A new Thread is used for each task.
B. A number of Threads equal to the number of CPUs Is used to execute tasks.
C. A single Thread Is used to execute all tasks.
D. A developer-defined number of Threads is used to execute tasks.
E. A number of Threads determined by system load is used to execute tasks.
F. The method used to obtain the Executor determines how many Threads are used to execute tasks.


Answer: F
Q-138
Given:
import java.util.*;
interface Glommer{}
interface Plinkable{}
class Filmmer implements Plinkable{
   List<Tagget> t=new ArrayList<>();
}
class Flommer extends Flimmer{String s="hey";}
class Tagget implements Glommer{
   void doStuff(){String s="yo";}
}
Which two statements concerning the OO concepts "is-a" and "has-a" are true?
A. Flimmer is-a Glommer.
B. Flommer has-a String.
C. Tagget has-a Glommer.
D. Flimmer is-a ArrayList.
E. Tagget has-a doStuff()
F. Tagget is-a Glommer.


Answer: BF
E 是錯誤的原因是 has-a 是針對物件屬性, 不是針對方法
Q-139
Given the Greetings.properties file, containing:
HELLO_MSG = Hello, everyone!
GOODBYE_MSG = Goodbye everyone!
And given:
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
public class ResourceApp {
   public void loadResourceBundle() {
      ResourceBundle resource = ResourceBundle.getBundle("Greetings", Locale.US);
      System.out.println(resource.getObject(1));
   }
   public static void main(String[] args) {
      new ResourcesApp().loadResourceBundle();
   }
}
What is the result?
A. Compilation fails
B. HELLO_MSG
C. GOODGYE_NSG
D. Hello, everyone!
E. Goodbye everyone!


Answer: A
要改成resource.getObject("HELLO_MSG")
Q-140
Given:
interface Vehicle{
   public void start();
   public void stop();
}
interface Motorized{
   public void stop();
   public void slow();
}
public class Car implements Vehicle, Motorized{
   public void start();
   public void stop();
   public void slow();
}
What is the result of invoking Car's stop method?
A. Both vehicles and Motorized's stop methods are invoked.
B. Vehicles stop method is invoked.
C. Motorized's stop method is invoked.
D. The implementation of the Car's stop determines the behavior.
E. Compilation fails.


Answer: E
Car的三個方法沒實作, 前面要加abstract
Car 的類別前面也要加abstract

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *