OCP 804 Exams -04

      在〈OCP 804 Exams -04〉中尚無留言
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class MapClass {
   public static void main(String[] args) {
      Map<String, String> partList = new TreeMap<>();
      partList.put("P002", "Large Widget");
      partList.put("P001", "Widget");
      partList.put("P002", "X-Large Widget");
      Set keys = partList.keySet();
      for (String key:keys) {
         System.out.println(key + " " + partList.get(key));
What is the result?
A. p001 Widget
   p002 X-Large Widget
B. p002 Large Widget
   p001 Widget
C. p002 X-large Widget
   p001 Widget
D. p001 Widget
   p002 Large Widget
E. compilation fails

Answer: A
TreeMap不允許key值重複, 如果重複了, 後來加入的會蓋掉以前的
A valid reason to declare a class as abstract is to:

A. define methods within a parent class, which may not be overridden in a child class
B. define common method signatures in a class, while forcing child classes to contain unique method implementations
C. prevent instance variables from being accessed
D. prevent a class from being extended
E. define a class that prevents variable state from being stored when object Instances are serialized
F. define a class with methods that cannot be concurrently called by multiple threads

Answer: B
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class NameList{
   public static void main(String[] args){
      List<String> nameList=new ArrayList<>(3);
      nameList.add("John Adams");
      nameList.add("George Washington");
      nameList.add("Thomas Jefferson");
      for (String name:nameList){
What is the result?
A. John Adams
   George Washington
   Thomas Jefferson
B. George Washington
   John Adams
   Thomas Jefferson
C. Thomas Jefferson
   John Adams
   George Washington
D. An exception is thrown at runtime
E. Compilation fails

Answer: B
Given the fragment:
class MyClass extends Thread{
    public OtherThread ot;
    MyClass(String title){
    public static void main(String[] args){
        MyClass a=new MyClass("Thread A");
        MyClass b=new MyClass("Thread B");
    public void run(){
        //use variable "ot" to do time-consuming stuff
    public void setThread(Thread x){
If thread a and thread b are running, but not completing, which two could be occurring?
A. livelock
B. deadlock
C. starvation
D. loose coupling
E. cohesion

Answer: AB
A:A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result.
B:Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
import java.util.*;
interface Glommer{}
interface Plinkable{}
class Flimmer implements Plinkable{
   List t=new ArrayList();
class Flommer extends Flimmer{}
class Tagget{
   void doStuff(){String s="yo";}
Which three statements concerning the OO concepts "is-a" and "has-a" are true?
A. Flimmer is-a Plinkable
B. Flommer has-a Tagget
C. Flommer is-a Glommer
D. Tagget has-a String
E. Flommer is-a Plinkable
F. Flimmer is-a Flommer
G. Tagget is-a Plinkable

Answer: ADE
原答案是ADF, 但 F 是錯的
A: Flimmer implements Plinkable. Flimmer is-a Plinkable.
D:The relationship modeled by composition is often referred to as the "has-a" relationship. HereTaggethas-aString.
F: Flommer extends Flimmer, So there is an "is-a relationship between Flommer and Flimmer. 這解釋真的是怪
Note: The has-a relationship has anencapsulation feature (like private or protected modifier used before each member field or
import java.util.*;
public class CompareTest {
   public static void main(String[] args) {
      TreeSet set1 = new TreeSet(
         new Comparator() {
            public boolean compare(String s1, String s2) {
               return s1.length() > s2.length();
      for (String n: set1) {
What is the result?
A. peach
B. peach
C. apple
D. The program does not compile.
E. The program generates an exception at runtime.

Answer: D
覆蓋 compare, 是要傳回int的,所以要寫成public int compare(String s1, String s2) {return 整數值}
Given the code fragment:
public class ReadFile01 {
   public static void main(String[] args) {
      String fileName = "myfile.txt";
      try (BufferedReader buffIn = // Line 4
         new BufferedReader(new FileReader(fileName))) {
         String line = "";
         int count = 1;
         line = buffIn.readLine(); // Line 7
         do {
            line = buffIn.readLine();
            System.out.println(count + ": " + line);
         } while (line != null);
      } catch (IOException | FileNotFoundException e) {
         System.out.println("Exception: " + e.getMessage());
What is the result, if the file myfile.txt does not exist?
A. A runtime exception is thrown at line 4
B. A runtime exception is thrown at line 7
C. Creates a new file and prints no output
D. Compilation fails

Answer: D
FileNotFoundException是IOException的子類別,  二者不能同時放在多重catch中
Which two forms of abstraction can a programmer use in Java?
A. enums
B. interfaces
C. primitives
D. abstract classes
E. concrete classes
F. primitive wrappers

Answer: BD
Which three statements are correct about thread's sleep method?
A. The sleep (long) method parameter defines a delay in milliseconds.
B. The sleep (long) method parameter defines a delay in microseconds.
C. A thread is guaranteed to continue execution after the exact amount of time defined in the sleep (long) parameter.
D. A thread can continue execution before the amount of time defined in the sleep (long) parameter.
E. A thread can continue execution after the amount of time defined in the sleep(long) parameter
F. Only runtime exceptions are thrown by the sleep method.
G. A thread loses all object monitors (lock flags) when calling the sleep method.

Answer: ACE
微秒的英文是 microsecond
Which two compile?
A. interface Compilable {
      void compile();
B. interface Compilable {
      final void compile();
C. interface Compilable {
      static void compile();
D. interface Compilable {
      abstract void compile();
E. interface Compilable {
      protected abstract void compile ();

Answer: AD
要不要加abstract都可以,加了也是白加, 因為編譯器自己會加
最後, interface是要讓子類別實作, 是在規範子類別的物件方法, 所以加了static就不倫不類了
Given this code fragment:
public static void main(String[] args) {
   try {
      String query = "SELECT * FROM Item";
      Statement stmt = conn.createStatement();
      ResultSet rs = stmt.executeQuery(query);
      ResultSetMetaData rsmd = rs.getMetaData(); // Line 14
      int colCount = rsmd.getColumnCount();
      while (rs.next()) {
         for (int i = 1; i <= colCount; i++) {
            System.out.print(rs.getObject(i) + " "); // Line 17
   } catch (SQLException se) {
Assume that the SQL query returns records. What is the result?
A. Compilation fails due to error at line 17
B. The program prints Error
C. The program prints each record
D. Compilation fails at line 14

Answer: C
public class Test {
   void display(String[] arr) {
      try {
      } catch(ArrayIndexOutOfBoundsException |
         NullPointerException e) {
         e = new Exception();
         throw e;
   public static void main(String[] args) throws Exception {
      try {
         String[] arr = {"Unix","Solaris",null};
         new Test().display(arr);
      } catch(Exception e) {
What is the result?
A. Null
B. class java.lang.ArraylndexOutOfBoundsException
C. class java.lang.NullPointerException
D. class java.lang.Exception
E. Compilation fails.

Answer: E
多重catch的參數是final的, 所以 e 不能再重新指定給其他物件
Which is a key aspect of composition?
A. Using inheritance
B. Method delegation
C. Creating abstract classes
D. Implementing the composite interface

Answer: B
delegation[͵dɛləˋgeʃən] : 委託
自己不會作就外包叫別人作, 就是Composition的精神
Given the code fragment:
try(Connection conn=DriverManager.getConnection(url)){
   Statement stmt=conn.createStatement();
   ResultSet rs=stmt.executeQuery(query);
   //...other methods
}catch(SQLException se){}
What change should you make to apply good coding practices to this fragment?
A. Add nested try-with-resources statements for the statement and Resulset declarations.
B. Add the statement and Resulset declarations to the cry-with-resources statement.
C. Add a finally clause after the catch clause.
D. Rethrow SQLException.

Answer: B
Which statement creates a low overhead, low-contention random number generator that is isolated to thread to generate a random
number between 1 and 100?
A. int i = ThreadLocalRandom.current().nextInt(1, 101);
B. int i = ThreadSafeRandom.current().nextInt(1, 101);
C. int i = (int) Math.random()*100+1;
D. int i = (int) Math.random(1, 101);
E. int i = new random().nextInt(100)+1;

Answer: A
ThreadLocalRandom用在有限資源的平台上, 進行多任務存取隨機數
public class Test {
   public static void display(long ivar) {
   public static void display(Integer ivar) {
      System.out.println(ivar * ivar);
   public static void display(Long ivar) {
      System.out.println(ivar * ivar * ivar);
   public static void main(String[] args) {
      int var =2;
      new Test().display(var);
What is the result?
A. 2
B. 4
C. 8
D. Compilation fails

Answer: A
方法參數先比對原生資料, 沒有的話就向上轉, byte->short->int->long
若向上轉也找不到, 才找Integer
class Plant {
   abstract String growthDirection();
class Embryophyta extends Plant {
   String growthDirection() { return "Up " ;}
class Carrot extends Plant{
   String growthDirection(){ return "Down ";}
public class Garden {
   public static void main(String[] args) {
      Embryophyta e = new Embryophyta();
      Embryophyta c = new Carrot();
      System.out.print(e.growthDirection() + c.growthDirection());
What is the result?
A. Up Down
B. Up Up
C. Up null
D. Compilation fails
E. An exception is thrown at runtime

Answer: D
class Plant要宣告為abstract

Given the Java classes:
public class Hard {
   private int static = 1;
   class Harder extends Hard {
      private int strict = 2;
      public void go(){
         System.out.print(super.strict); //line 8
      }//line 9
   public static void main(String[] args) {
      new Hard().new Harder().go();
What is the result?
A. 112
B. 221
C. 211
D. RuntimeException is throws at line 8
E. RuntimeException is throws at line 9

Answer: C
import java.util.concurrent.atomic.AtomicInteger;
public class Incrementor {
   public static void main(String[] args) {
      AtomicInteger[] var = new AtomicInteger[5];
      for (int i = 0; i < 5; i++) {
         var[i] = new AtomicInteger();
      for (int i =0; i < var.length; i++) {
         if (i ==2)
         System.out.print(var[i] + " ");
What is the result?
A. 1 1 1 1 1
B. 1 2 3 4 5
C. 0 1 2 3 4
D. 0 1 4 3 4

Answer: A
public class SuperThread extends Thread {
   public void run(String name) {
   public void run(Runnable r) {
      r = new runnable() {
         public void run() {
   public static void main(String[] args) {
      Thread t = new SuperThread();
Which two are true?
A. Thread is printed
B. Runnable is printed
C. No output is produced
D. No new threads of execution are started within the main method
E. One new thread of execution is started within the main method
F. Two new threads of exclusion are started within the main method

Answer: CE
因為沒有public void run(), 所以會執行Thread類別的預設run(), 沒東西印出來
也就是說, 會產生一個新的執行緒, 但沒作什麼事就死了


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