OCA 808

      在〈OCA 808〉中尚無留言

Java 國際認証

Oracle(甲骨文) Java認証全名為 Java Oracle Certified Professional。屬國際級的考試認証,通行於世界各地。 在台灣區的考試全為英文試題,不得選取或變更語系。

2019年初開始,只能考取 Java 8 或以上版本的認証。至於 Java7 及以下的版本全面廢止。

國際認証是通行於全球所認可的考試制度,無論到那個國度,每個國家都承認這種技能。如美國、英國、歐洲、菲律賓、澳州、新加坡等英語系國家,當然也包含中國大陸、香港、日本、韓國。

Java考試編號

808 : OCA for Jdk 8.0
809 : OCP for Jdk 8.0
803 : OCA for Jdk 7.0
804 : OCP for Jdk 7.0

Java 主要認証

OCA : 基礎認証,考試內容在評斷個人是否具有基礎的程式基礎,較為容易。Java8.0 的考試編號為 808

OCP : 進階認証,考試內容在評斷個人是否具有獨立作業能力,甚是艱難。Java8.0 的考試編號為 809。通常需在業界有二、三年的經歷,才比較容易通過考試。

升級考 : Java8.0 的考試編號為810,凡具有SCJP、或前版OCP 的應考生,才可選取直接升級新版OCP認証。

上述每科考試費用,都在NT$4500上下。

考試方式

考試方式依官網為主,大略內容如下 :
808 : 70題選擇題,考試時間為150分鐘,及格分數為63%。
809 : 65題選擇題,考試時間為150分鐘,及格分數為65%。
810 : 70題選擇題,考試時間為150分鐘,及格分數為60%。

Q-001

Given the code fragment
public class Test {
    static int count=0;
    int i=0;
    public void changeCount(){
        while(i<5){
            i++;
            count++;
        }
    }
    public static void main(String[] args) {
        Test check1=new Test();
        Test check2=new Test();
        check1.changeCount();
        check2.changeCount();
        System.out.println(check1.count+":"+check2.count);
    }
}
what is the result?
A. 10 : 10
B. 5:5
C. 5 : 10
D. Compilation fails

Ans : A
解說 :
i 為物件變數, check1的i, 與check2 的i 是不一樣的變數
count 為類別變數, check1的count 與check2的count是同一個變數
check1.count是錯誤的, 應該寫為 Test.count. 
雖Java可以使用check1.count, 但c#是完全禁止的

底下的程式碼中, t1.sleep(2000), 結果是main主執行緒去睡覺, 而不是t1去睡覺, 
所以為了防止誤會, 藍色的地方需要改成 Thread.sleep(2000);

    public static void main(String[] args) {
        Thread t1=new Thread(new Job());
        t1.start();
        try {
            Thread.sleep(2000);
            t1.sleep(2000);
            
        } catch (InterruptedException ex) {}
        System.out.println("主執行死掉了");
    }

Q-002

public class Case {
    public static void main(String[] args) {
        String product = "Pen";
        product.toLowerCase();
        product.concat(" BOX".toLowerCase());
        System.out.println(product.substring(4,6));
    }
}
What is the result?
A. box
B. nbo
C. bo
D. nb
E. An exception is thrown at runtime

Ans. E
解說:
product.concat(" BOX".toLowerCase()); product的結果還是 "Pen"
但如果是 product=product.concat(" BOX".toLowerCase()), 結果是 "bo"

Q-003

public static void main(String[] args) {
    String[] arr={"A", "B", "C", "D"};
    for (int i=0;i<arr.length;i++){
	System.out.print(arr[i]+" ");
	if(arr[i].equals("C")){
            continue;
 	}
	System.out.println("Work done");
	break;
    }
}
What is the result?
A) A B C D Work done
B) A B C Work done
C) A Work done
D) Complation fails.

Ans. C
解說:
i=0時, 列印 A, 然後不會continue, 再印work done, 然後break整個中段

Q-004

public static void main(String[] args) {
    int numbers[];
    numbers= new int[2];
    numbers[0] = 10;
    numbers[1] = 20;
    numbers=new int[4];
    numbers[2] = 30;
    numbers[3] = 40;
    for (int x: numbers){
	System.out.print(" "+x);
    }
}
What is the result?
A) 10 20 30 40
B) An exception is thrown at runtime.
C) Compilation fails.
D) 0 0 30 40

Ans : D

Q-005

Which three statements describe the object-oriented features of the Java language?
A) A main method must be declared in every class.
B) Object can share behaviors with other objects.
C) Objects cannot be reused.
D) A subclass can inherit from a superclass.
E) A package must contain more than one class.
F) Object is the root class of all other objects.

Ans : B D F

Q-006

public static void main(String[] args) {
	String date=LocalDate.parse("2014/05/04").format(DateTimeFormatter.ISO_DATE_TIME);
	System.out.println(date);
}
What is the result?
A) May 04, 2014T00:00:00.000
B) 2014-05-04T00:00:00.000
C) 5/4/14T00:00:00.000
D) An exception is thrown at runtime.

Ans : D
解說 : 
Date d=new Date();可取得目前的時間系統, 
印出d.toString()為 Wed Aug 12 12:13:24 CST 2020
但若要列印出人類常用的格式, 可使用SimpleDateFormat, 如下
String str=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date());
System.out.println(str);

到了Java8開始, 建議不要再使用Date了, 而要改用LocalDate. 因為LocalDate 是thread-safe.
LocalDate沒有時區及時間資訊, 僅有日期資訊. 使用ISO-8601系統, 格式為 yyyy-mm-dd.
請注意, 是 "-", 而不是 "/". 使用 "/" 會發生runtime error
所以正確要改為 LocalDate date=LocalDate.parse("2014-05-04");

LocalDate.format()是要將LocalDate物件轉成字串, 轉換格式依()的參數而定.
因為LocalDate沒有時間格式, 所以不能使用DateTimeFormatter.ISO_DATE_TIME, 
只能使用 DateTimeFormatter.ISO_DATE
所以若改成String date=LocalDate.parse("2014-05-04").format(DateTimeFormatter.ISO_DATE);
則輸出結果為:2014-05-04

Q-007

public static void main(String[] args) {
    int i = 10;
    int j = 20;
    int k = j += i/5;
    System.out.print(i + " : " + j + " : " + k);
}
What is the result?
A) 10 : 22 : 22
B) 10 : 22 : 20
C) 10 : 22 : 6
D) 10 : 30 : 6

Ans : A

Q-008

String shirts [][] =new String[2][2];
shirts[0][0] = "red";
shirts[0][1] = "blue";
shirts[1][0] = "small";
shirts[1][1] = "medium";
Which code fragment prints red:blue:small:medium:
A) 
    for (int index=0 ; index<2 ;){
        for (int idx=0 ; idx<2 ;){
            System.out.print(shirts[index][idx] + ":");
            idx++;
        }
        index++;
    }
B) 
    for (int index=0 ; index<2 ; ++index){
        for (int idx=0 ; idx<2 ; ++idx){
            System.out.print(shirts[index][idx] + ":");
        }
    }
C) 
    for (String c : colors){
        for (String s: size){
            System.out.println(s + ":");
        }
    }
D) 
    for (int index=1 ; index<2 ; index++){
        for (int idx=1 ; idx<2 ; idx++){
            System.out.print(shirts[index][idx] + ":");
        }
    }
Ans : A B
解說:
for (;;){} 為一無窮迴圈

Q-009

Given the following code for a Planet object:

public class Planet{
    public String name;
    public int moons;
    public Planet(String name, int moons){
        this.name = name;
        this.moons = moons;
    }
}

And the following main method:
public static void main(String[] args) {
    Planet[] planets = {
        new Planet("Mercury", 0),
        new Planet("Venus", 0),
        new Planet("Earth", 1), 
        new Planet("Mars", 2)
    };
    System.out.println(planets);
    System.out.println(planets[2]);
    System.out.println(planets[2].moons);
}
What is the output?
A) 
    [LPlanets.Planet;@15db9742
    Earth
    1
B)
    [LPlanets.Planet;@15db9742
    Venus
    0
C)
    [LPlanets.Planet;@15db9742
    Planets.Planet@6d06d69c
    [LPlanets.Moon;@15db97421
D) 
    [LPlanets.Planet;@15db9742
    Planets.Planet@6d06d69c
    1
Ans : D

Q-010

public static void main(String[] args) {
    String s = " Java Duke ";
    int len = s.trim().length();
    System.out.print(len);
}
What is the result?
A) 9
B) 8
C) 10
D) 11
E) Compilation fails.

Ans : A
解說:
trim()只會刪除字串前後的空格, 中間的空格不理會

Q-011

Given the code fragment:
int wd = 0;
String days[] = {"sun", "mon", "wed", "sat"};
for (String s:days){
    switch(s){
        case "sat":
        case "sun":
            wd -= 1;
            break;
        case "mon":
            wd++;
        case "wed": 
            wd +=2;
    }
}
System.out.println(wd);
What is the result?
A) 1
B) 3 
C) -1
D) 4
E) Compilation fails.
Ans : B
wd -=1  如同wd = wd - 1;, 右邊的值放入左邊

Q-012

Given the code fragment
public static void main(String[] args) {
    ArrayList myList = new ArrayList();
    String[] myArray;
    try{
        while (true){
            myList.add("My String");
        }
    }
    catch(RuntimeException re){
        System.out.println("Caught a RuntimeException");
    }
    catch(Exception e){
        System.out.println("Caught an Exception");
    }
    System.out.println("Ready to use");
}
What is the result?
A) Execution terminates in the first catch statement, 
   and caught a RuntimeException is printed to the console.
B) Execution terminates in the second catch statement, 
   and caught an Exception is printed to the console.
C) A runtime error is thrown in the thread “main”.
D) Execution completes normally, 
   and Ready to use is printed to the console.
E) The code fails to compile because a throws keyword is required.

Ans : C
此題會進入無窮迴圈, 導致記憶体不足, 最後產生 Exception in thread “main” java.lang.OutOfMemoryError: Java heap space

Q-013

Given the following array:
int[] intArr = {8, 16, 32, 64, 128};
Which two code fragments, Independently, print each element in this array?
A) 
    for (int i=0; i<intArr.length;i++){
        System.out.print(i + " ");
    }
B) 
    for (int i :intArr){
        System.out.print(intArr[i] + " ");
    }
C) 
    for (int i ; i < intArr.length ; i++){
        System.out.print(intArr[i] + " ");
    }
D) 
    for (int i=0 ; i < intArr.length ; i++){
        System.out.print(intArr[i] + " ");
    }
E) 
    for (int i=0 : intArr){
        System.out.print(intArr[i] + " ");
        i++;
    }
F)
    for (int i : intArr){
        System.out.print(i + " ");
    }
Ans : D F

Q-014

Given the code fragment : 
float var1 = (12_345.01 >= 123_45.00)? 12_456 : 124_56.02f;
float var2 = var1 + 1024;
System.out.println(var2);

What is the result?
A) 13480.0
B) Compilation fails.
C) An exception is thrown at runtime.
D) 13480.02

Ans : A

Q-015

Given the code fragment:
public static void main(String[] args) {
    StringBuilder sb=new StringBuilder(5);
    String s="";
    if(sb.equals(s)){
        System.out.println("Match 1");
    }
    else if (sb.toString().equals(s.toString())){
        System.out.println("Match 2");
    }
    else{
        System.out.println("No Match");
    }
}
What is the result?
A) No Match
B) A NullPointerException is thrown at runtime.
C) Match 2
D) Match 1

Ans : C

Q-016

Which two class definitions faile to compile?
A) 
    public class A2{
        private static int i;
        private A2(){}
    }
B) 
    abstract class A3{
        private static int i;
        public void doStuff(){}
        public A3(){}
    }
C) 
    class A4{
        protected static final int i;
        private void doStuff(){}
    }
D)
    final class A1{
        public A1(){}
    }
E)
    final abstract class A5{
        protected static int i;
        void doStuff(){}
        abstract void doIt();
    }
Ans : C E
解說:
final static int count 一定要有初始值
final int price也一定要有初始值, 亦可於建構子內, 且只能在建構子內給值, 並只能設定一次

class Toy{
    final int price;
    final static int count=10;
    public Toy(){
        int a=100;     
        price=10;
    }
}

Q-017

Given the code fragment : 
abstract class Toy{
    int price;
    //line n1
}
Which three code fragments are valid at line n1?
A) 
    public abstract Toy getToy(){
        return new Toy();
    }
B) 
    public void printToy();
C) 
    public int calculatePrice(){
        return price;
    }
D)
    public static void insertToy(){
        /* code goes here */
    }
E)
    public abstract int computeDiscount();
Ans : C D E
解說 :
抽像類別裏的抽像方法, 一定要加abstract
abstract class Pokemon{
    abstract public void setLevel();
}

介面裏的抽像方法, 不一定要加abstract及public, 因系統會自動加入public abstract
interface Water{
    void setSwinning();
}

Q-018

Which statement is true about Java byte code?

A. It can run on any platform.
B. It can run on any platform only if it was compiled for that platform.
C. It can run on any platform that has the Java Runtime Environment.
D. It can run on any platform that has a Java compiler.
E. It can run on any platform only if that platform has both the Java Runtime Environment and a Java compiler.

Ans : C

Q-019

Given the code fragment:
public static void main(String[] args){
    double discount = 0;
    int qty = Integer.parseInt(args[0]);
    // line n1;
}

And given the requirements:

If the value of the qty variable is greater than or equal to 90, discount = 0.5
If the value of the qty variable is between 80 and 90, discount = 0.2

Which two code fragments can be independently placed at line n1 to meet the requirements?
What is the result?
A) 
    if (qty >= 90) {discount = 0.5; }
    if (qty > 80 && qty < 90) {discount = 0.2; }
B) 
    discount = (qty >= 90) ? 0.5 : 0;
    discount = (qty > 80) ? 0.2 : 0;
C) 
    discount = (qty >= 90) ? 0.5 : (qty > 80) ? 0.2 : 0;
D) 
    if (qty > 80 && qty < 90) {
        discount = 0.2;
    } else {
        discount = 0;
   }
   if (qty >= 90) {
        discount = 0.5;
   } else {
       discount = 0;
   }
E)
    discount = (qty > 80) ? 0.2 : (qty >= 90) ? 0.5 : 0;

Ans : A C

Q-020

class Vehicle {
    int x;
    Vehicle() {
        this(10); // line n1
    }
    Vehicle(int x) {
        this.x = x;
    }
}
class Car extends Vehicle {
    int y;
    Car() {
        super();
        this(20); // line n2
    }
    Car(int y) {
        this.y = y;
    }
    public String toString() {
        return super.x + ":" + this.y;
    }
}
And given the code fragment:
    Vehicle y=new Car();
    System.out.println(y);
What is the result?
A) 0:20
B) 10:20
C) Compilation fails at line n1
D. Compilation fails at line n2

Ans : D
解說
super及this都必需放在建構子的第一行, 所以二個不能同時出現

Q-021

Given the following class
class Rectangle{
    private double length;
    private double height;
    private double area;
    public void setLength(double length){
        this.length = length;
    }
    public void setHeight(double height){
        this.height = height;
    }
    public void setArea(){
        area = length * height;
    }
}

Whick two changes would encapsulate this class and ensure that the area field is always equals to length * height whenever the Rectangle class is used?

A. Call the setArea method at the end of the setHeight method.
B. Call the setArea method at the beginning of the setHeight method.
C. Call the setArea method at the end of the setLength method.
D. Call the setArea method at the beginning of the setLength method.
E. Change the setArea method to private.
F. Change the area field to public.

Ans : A C
setArea()可以維持在public不用更變, 讓外部要調用或不調用都可以

Q-022

Given
class C2 {
    public void displayC2() {
        System.out.print("C2");
    }
}
interface I {
    public void displayI ();
}
class C1 extends C2 implements I {
    public void displayI() {
        System.out.print("C1");
    }
}

And given the code fragment:

C2 obj1 = new C1();
I obj2 = new C1();

C2 s=obj2;
I t=obj1;

t.displayI();
s.displayC2();

What is the result?

A) C1C1
B) Compilation fails.
C) C2C2
D) C1C2

Ans : B
obj2是 Interface I, 無法轉成 C2

Q-023

Which three are advantages of the Java exception mechanism?

A.Improves the program structure because the error handling code is separated from the normal program function.
B. Provides a set of standard exceptions that covers all the possible errors.
C. Improves the program structure because the programmer can choose where to handle exceptions.
D. Improves the program structure because exceptions must be handled in the method in which they occurred.
E. Allows the creation of new exceptions that are tailored to the particular program being created.

Answer: A,C,E
解說:
B. 例外處理並不會處理(Cover)所有的錯誤. 比如unchecked Exception 就不需強制寫try-catch
D. 例外可以使用call stack的方式, 丟給上層的方法, 所以不一定要在發生錯誤的方法中處理.
public class Test2 {
    public static void main(String[] args) {
        Pikachu p1=new Pikachu();
        try{
            p1.setArea();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
}
class Pikachu{
    int height, width, area;
    public void setArea()throws Exception{//Call Stack
        if (width==0 || height==0)
            throw new Exception("不能為0");
        area=width*height;
    }
}

在main中, 也可以使用call stack, 如
public static void main(String args)throws Exception{}
此時會造成系統crash閃退, 所以一般程式碼不會這樣寫. 
但考試時, 就是愛考這種五四三的, 要注意這種寫法是正確的.

另外, 若在建構子發生例外, 則無法產生物件, 所得到的結果為null
public class Test2 {
    public static void main(String[] args){
        Pikachu p1=null;
        try{
            p1=new Pikachu();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
        if (p1==null){
            System.out.println("沒有產生皮卡丘");
        }
    }
}
class Pikachu{
    public Pikachu()throws Exception{
        throw new Exception("建構子中發生錯誤");
    }
}
結果為 :
建構子中發生錯誤
沒有產生皮卡丘

Q-024

Given the following classes : 
public class Employee {
    public int salary ;
}
public class Manager extends Employee {
    public int budget ;
}
public class Director extends Manager {
    public int stockOptions ;
}

And given the following main method:

public static void main (String[] args) {
    Employee employee = new Employee () ;
    Manager manager = new Manager () ;
    Director director = new Director () ; 
    //line n1
}

Which two options fail to compile when placed at line n1 of the main method?
A. employee.salary = 50_000;
B. director.salary = 80_000;
C. employee.budget = 200_000;
D. manager.budget = 1_000_000;
E. manager.stockOption = 500;
F. director.stockOptions = 1_000;

Ans : C E

Q-025

class Alpha{
    int ns;
    static int s;
    Alpha(int ns){
        if(s<ns){
            s=ns;
            this.ns=ns;
        }
    }
    void doPrint(){
        System.out.println("ns = "+ns+" s = "+s);
    }
}
public class TestA{
    public static void main(String[]args){
        Alpha ref1=new Alpha(50);
        Alpha ref2=new Alpha(125);
        Alpha ref3=new Alpha(100);
        ref1.doPrint();
        ref2.doPrint();
        ref3.doPrint();
    }
}
what is this result?
A 
    ns = 50 s = 50 
    ns = 125 s = 125 
    ns = 0 s = 125
B 
    ns = 50 s = 125
    ns = 125 s = 125
    ns = 100 s = 125
C 
    ns = 50 s = 125
    ns = 125 s = 125
    ns = 0 s = 125
D 
    ns = 50 s = 50
    ns = 125 s = 125
    ns = 100 s = 100

Ans : C

Q-026

4.  class X{
5.     public void printFileContent(){
6.         /* code goes here */
7.         throw new IOException();
8.     }
9.  }
10. public class Test{
11.    public static void main (String [] args ){
12.        X xobj = new X();
13.        xobj.printFileContent();
14.    }
15. }

Which two modifications should you make so that the code compiles successfully?

A) Replace line 13 with;
    try {
        xobj.printFileContent();
    }
    catch(Exception e){ }
B) Replace line 5 with public void printFileContent() throws IOException{
C) Replace line 11 with public static void main(String[] args )throws Exception{
D) Replace line 7 with throw IOException(“Exception raised”);
E) At line 14,insert throw new IOException();

Ans : A B
解說:
此題有些爭議性
正確答案是AB, 但其實若是選BC, 也是可以的. 只是main會造成runtime error, 
而題目註明是二個答案, 所以就選AB

Q-027

public static void main (String [] args ){
    int[][] arr=new int[2][4];
    arr[0]=new int[]{1,3,5,7};
    arr[1]=new int[]{1,3};
    for (int[] a:arr){
	for (int i:a){
            System.out.print(i+" ");
	}
	System.out.println("");
    }
}

what is the result?
A. Compilation fails.
B. 1 3
   followed by an ArrayIndexOutOfBoundsException
C. 1 3
   1 3 0 0
D. 1 3
   1 3
E. 1 3 5 7
   1 3

Ans : E
解說:
    public static void main(String[] args)throws Exception{
        int [][]arr=new int[][]//等長陣列
        {
            {1,3,5,7}, 
            {2,4,6,8}
        };
        int[][]s=new int[2][];//不等長
        s[0]=new int[4];
        s[1]=new int[10];

Q-028

interface Exportable{
    void export();
}
class Tool implements Exportable{
    protected void export(){ //line n1
        System.out.println("Tool::export");
    }
}
public class Test extends Tool implements Exportable{
    public void export(){ //line n2
        System.out.println("RTool::export");
    }
    public static void main(String[] args) {
        Tool aTool=new Test();
        Tool bTool=new Tool();
        callExport(aTool);
        callExport(bTool);
    }
    public static void callExport(Exportable ex){ //line n2
        ex.export();
    }
}
What is the result?
A. Compilation fails only at line n2.
B. RTool::export Tool::export
C. Tool::export Tool:export
D. Compilation fails only at line n1.
E. Compilation fails at both line n1 and line n2.

Ans : D
解說:
此題在網路上有很多答案都說是B, 其實大錯特錯了. 正確答案是 D. 
因為Line 1 在實作介面的方法, 都是pubic. 不可以為protected.

如果Line改成public , 那答案才是B

Q-029

public class Test{
    int x, y;
    public Test(int x, int y){
        initialize(x, y);
    }
    public void initialize(int x, int y){
        this.x=x*x;
        this.y=y*y;
    }
    public static void main(String[] args){
        int x=3, y=5;
        Test obj=new Test(x, y);
        System.out.println(x + " "+ y);
    }
}

what is the result?
A. 0 0
B. Compilation fails
C. 3 5
D. 9 25

Ans : C

Q-030

interface Downloadable{
    public void download();
}
interface Readable extends Downloadable{ //line n1
    public void readBook();
}
abstract class Book implements Readable{ //line n2
    public void readBook(){
        System.out.println("Read Book");
    }
}
class EBook extends Book{ //line n3
    public void readBook(){
        System.out.println("Read E-Book");
    }
}

And given the code fragment:
Book book1 = new EBook();
book1.readBook();
what is the result?
A. Read Book
B. Compilation fails at line n1
C. Compilation fails at line n2
D. Compilation fails at line n3
E. Read E-Book

Ans : D
line n3 需實作download()方法
解說
如果line n3有實作download的話, 那答案會是E
因子類別方法覆蓋父類別方法時, 父類別方法屍骨無存. 所以就算使用父類別參考, 還是執行
子類別的方法

Q-031

public class Person{
    String name;
    int age=25;
    public Person(String name){
        this(); //line n1
        setName(name);
    }
    public Person(String name, int age){
        Person(name); //line n2
        setAge(age);
    }
    //setter and getter methods go here
    public String show(){
        return name + " "+ age;
    }
    public static void main(String[] args){
        Person p1=new Person("Jeses");
        Person p2= new Person("Walter", 52);
        System.out.println(p1.show());
        System.out.println(p2.show());
    }
}

what is the result?
A. Compilation fails only at line n2.
B. Compilation fails only a line n1.
C. Jeses 5
   Walter 52
D. Compilation fails at both line n1 and line n2

Ans : D
解說
Line 1 : this()需拿掉, 因為沒有預設建構子
Line 2 : 需改為 this(name)

    public Person(){}
    public Person(String name){
        this(); //line n1
        setName(name);
    }
    public Person(String name, int age){
        this(name); //line n2
        setAge(age);
    }

Q-032

public class Triangle{
    static double area;
    int b=2, h=3;
    public static void main(String[] args){
        double p, b, h; //line n1
        if (area ==0) {
            b=3;
            h=4;
            p=0.5;
        }
        area=p * b * h; //line n2
        System.out.println("Area is  "+ area);
    }
}

what is the result?
A. Compilation fails at line n2.
B. Compilation fails at line n1.
C. Area is 6.0
D. Area is 3.0

Ans : A
b, h, p可能沒有初始化

Q-033

 3. public static void main(String[] args){
 4. 	int iVar =100;
 5. 	float fVar =100.100f;
 6. 	double dVar =123;
 7. 	iVar = fVar;
 8. 	fVar = iVar;
 9. 	dVar = fVar;
10. 	fVar = dVar;
11. 	dVar = iVar;
12. 	iVar = dVar;
13. }

Which three lines fail to compile?
A. line 12
B. line 9
C. line 10
D. line 8
E. line 11
F. line 7

Ans : A C F

Q-034

public static void main(String[] args){
    //line n1
    switch(x){
	case 1:
            System.out.println("One");
	    break;
	case 2:
	    System.out.println("Two");
	    break;
    }
}
Which three code fragments can be independently inserted at line n1 to enable the code to print One?
A. long x=1;
B. byte x=1;
C. Integer x=new Integer("1");
D. double x=1;
E. short x=1;
F. String x="1";

Ans : B C E

Q-035

class A{
    public A(){
        System.out.print("A ");
    }
}
class B extends A{
    public B(){ //line n1
        System.out.print("B ");
    }
}
class C extends B{
    public C(){  //line n2
        System.out.println("C ");
    }
    public static void main(String[] args){
        C c=new C();
    }    
}

what is the result?
A. Compilation fails at line n1 and line n2.
B. A B C
C. C
D. C B A

Ans : B
若要嚴格來說, 答案是A, 因為class C 沒有public. 但此題是考super(), 所以是B

Q-036

public class MianTest{
    public static void main(int[] args){
        System.out.println("int main " + args[0]);
    }
    public static void main(Object[] args){
        System.out.println("Object main " + args[0]);
    }
    public static void main(String[] args){
        System.out.println("String main " + args[0]);
    }
}
and commands:
javac MainTest1.java
java MainTest 1 2 3
what is the result?
A. String main 1
B. An exception is thrown at runtime.
C. int main 1
D. Compilation fails.
E. Object main 1

Ans : A

Q-037

public class Test{
    public static final int MIN=1;
    public static void main(String args[])
    {
        int x=args.length;
        System.out.println(args.length);
        if(checkLimit(x)) {     //line n1
            System.out.println("Java SE");
        }
        else{
            System.out.println("Java EE");
        }
    }
    public static boolean checkLimit (int x){
        return (x>=MIN) ? true :false;
    }
}
And given the commands:
javac Test.java
java Test 1 2 3
what is the result?
A. Compilation fails at line n1.
B. 0
   Java EE
C. 3
   Java SE
D. A NullPointerExcpetion is thrown at runtime.

Ans : C

Q-038

public static void main(String args[]){
	short s1 = 200;
	Integer s2 = 400;
	Long s3 = (long) s1 +s2;     //line n1
	String s4 = (String)(s3 * s2);//line n2
	System.out.println("Sum is " + s4);
}
what is the result?
A. Sum is 600
B. A ClassCastException is thrown at line n2.
C. Compilation fails at line n2.
D. A ClassCastException is thrown at line n1.
E. Compilation fails at line n1.

Ans : C
解說 :
Line 2 必需為 String s4=String.valueOf(s3*s2);

Q-039

public class MyException extends RuntimeException{}
public class Test{
    public static void main(String args[]){
        try{
            method1();
        }
        catch(MyException ne){
            System.out.print("A");
        }
    }
    public static void method1(){   //line n1
        try{
            throw Math.random() > 0.5 ? new MyException(): new RuntimeException();
        }
        catch(RuntimeException re){
            System.out.println("B");
        }
    }
}
what is the result?
A. B
B. Either A or B
C. A compile time error occurs at line n1.
D. AB

Ans : A

Q-040

public class Test{
    public static void main(String args[]){
        if (args[0].equals("Hello") ? false : true){
            System.out.println("Success");
        }
        else{
            System.out.println("Failure");
        }
    }
}
And given the commands:

java Test Hello
what is the result?
A. Success
B. Compilation fails.
C. An exception is thrown at runtime.
D. Failure

Ans : D
請注意, 這題有陷井.輸入Hello後, equals是 true, 但 true是返回第一個參數 fasle, 所以會跑 else區塊

Q-041

public static void main(String[] args) {
    String[] arr={"Hi", "How", "Are", "Yo"};
    List arrList=new ArrayList <> (Arrays.asList(arr));
    if(arrList.removeIf((String s) -> {return s.length() <= 2;})){
        System.out.println(s + " removed");
    }
}
What is the result?
A. The program compiles, but it prints nothins.
B. Compilation failes.
C. An UnsupportedOperationException is thrown at runtime.
D. Hi removed

Ans : B
String s 為Lambda內的區域變數, 所以無法被Lambda之外使用
Arrays.asList() : 將陣列轉為 List. 
但請注意, 陣列裏不可以為基本資料型態, 如 int[] arr={1, 2, 3}
Integer[] arr={1, 2, 3}才可以放入 asList()裏

Q-042

public static void main(String[] args) {
    int ii=0;
    int jj=7;
    for (ii=0;ii<jj-1;ii=ii+2){
        System.out.print(ii + " ");
    }
}
What is the result?
A. Compilation fails.
B. 0 2 4 6
C. 2 4
D. 0 2 4

Ans : D

Q-043

The following grid shows the state of a 2D array
ocp808_1
This grid is created with the following code:
 char[][] grid=new char[3][3];
 grid[1][1]='X';
 grid[0][0]='O';
 grid[2][1]='X';
 grid[0][1]='O';
 grid[2][2]='X';
 grid[1][2]='O';
 //line n1
Which line of code, when inserted in place of //line n1, adds an x into the grid so that the grid contains three consecutive X's?
A.  grid[2][0]='X';
B.  grid[1][3]='X';
C.  grid[0][2]='X';
D.  grid[1][2]='X';
E.  grid[3][1]='X';

Ans : A

Q-044

public static void main(String[] args) {
    String ta="A ";
    ta=ta.concat("B ");
    String tb="C ";
    ta=ta.concat(tb);
    ta.replace('C', 'D');
    ta=ta.concat(tb);
    System.out.println(ta);
}
What is the result?
A. A C D
B. A B C C
C. A B D
D. A B C D 
E. A B D C

Ans : B

Q-045

Given : 
class Test{
    public static int stVar = 100;
    public int var = 200;
    public String toString(){
        return var + ":" + stVar;
    }
}
And given the code fragment:
Test t1=new Test();
t1.var = 300;
System.out.println(t1);
Test t2=new Test();
t2.stVar = 300;
System.out.println(t2);

What is the result?
A. 300:100
   200:300
B. 200:300
   200:300
C. 300:300
   200:300
D. 300:0
   0:300

Ans : A

Q-046

public static void main(String[] args) {
	//line n1
	array[0]=10;
	array[1]=20;
	System.out.print(array[0] + ":" + array[1]);
}
Which code fragment, when inserted at line n1, enables the code to print 10:20?
A. int[] array=new int[2];
B. int array = new int[2];
C. int array[2];
D. int [] array;
   array = int[2];

Ans : A

Q-047

class Vehicle{
    String type;
    int maxSpeed;
    Vehicle(String tyep, int maxSpeed){
        this.type=type;
        this.maxSpeed=maxSpeed;
    }
}
class Car extends Vehicle{
    String trans;
    Car(String trans){      //line n1
        this.trans=trans;
    }
    Car(String type, int maxSpeed, String trans){
        super(type, maxSpeed);
        this(trans);        //line n2
    }
}
And given the code fragment:
    Car c1=new Car("Auto");
    Car c2=new Car("4W", 150, "Manual");
    System.out.println(c1.type + " " +c1.maxSpeed + " " + c1.trans);
    System.out.println(c2.type + " " +c2.maxSpeed + " " + c2.trans);
What is the result?
A. null 0 Auto
   4W 150 Manual
B. Compilation fails at both line n1 and line n2
C. Compilation fails only at line n2
D. 4W 100 Auto
   4W 150 Manual
E. Compilation fails only at line n1

Ans : B
line n1下一行需寫入 super("",100)
line n2需刪除, super()及this()都必需放在建構子第一行, 所以只能出現一種.

Q-048

You are asked to create a method that accepts an array of integers and returns the highest value from that array.
Given the code fragment:
class Test {
    public static void main(String[] args) {
        int numbers[] ={12,13,42,32,15,156,23,51,12};
        int max=findMax(numbers);
    }
    /* line n1*/{
        int max=0;
        /* code goes here*/
        return max;
    }
}
What method signature do you use at line n1?
A. public int findMax(int[] numbers)
B. final int findMax(int[])
C. static int findMax(int[] numbers)
D. static int[] findMax(int max) 

Ans : C

Q-049

int n[][] = {{1, 3}, {2, 4}};
for (int i=n.length-1;i>=0;i--){
	for (int y: n[i]){
		System.out.print(y);
	}
}
What is the result?
A. 4231
B. 3142
C. 2413
D. 1324

Ans : C

Q-050

13.  List colors=new ArrayList();
14.  colors.add("green");
15.  colors.add("red");
16.  colors.add("blue");
17.  colors.add("yellow");
18.  colors.remove(2);
19.  colors.add(3, "cyan");
20.  System.out.print(colors);
What is the result?
A. An IndexOutOfBoundsException is thrown at runtime.
B. [green, red, yellow, cyan]
C. [green, red, cyan, yellow]
D. [green, blue, yellow, cyan] 

Ans : B

Q-051

class Animal{
    String type = "Canine";
    int maxSpeed=60;
    Animal(){}
    Animal(String type, int maxSpeed){
        this.type=type;
        this.maxSpeed=maxSpeed;
    }
}
class WildAnimal extends Animal{
    String bounds;
    WildAnimal(String bounds){
        //line n1
    }
    WildAnimal(String type, int maxSpeed, String bounds){
        //line n2
    }
}
And given the code fragment:
7.  WildAnimal wolf=new WildAnimal("Long");
8.  WildAnimal tiger=new WildAnimal("Feline", 80, "Short");
9.  System.out.println(wolf.type + " " + wolf.maxSpeed + " " + wolf.bounds);
10. System.out.println(tiger.type + " " + tiger.maxSpeed + " " + tiger.bounds);

Which two modification enable the code to print the following output?
Canine 60 Long
Feline 80 Short

A. Replace line n1 with:
   this("Canine", 60);
B. Replace line n2 with:
   super(type, maxSpeed);
   this(bounds);
C. Replace line n1 with:
   super();
   this.bounds = bounds;
D. Replace line n1 with:
   this.bounds = bounds;
   super();
E. Replace line n2 with:
   super(type, maxSpeed);
   this.bounds = bounds;

Ans : C E

Q-052

public static void main(String[] args) {
    LocalDate date=LocalDate.of(2012, 01, 32);
    date.plusDays(10);
    System.out.println(date);
}
What is the result?
A. Compilation fails.
B. 2020-02-10
C. A DateTimeException is thrown at runtime.
D. 2012-02-11 

Ans : C
日期 2012,01 32 超過31
另外, 要寫成 date=date.plusDays(10);

Q-053

public class Test {
    public static void main(String[] args) {
        String str1="Java";
        String[] str2={"J","a","v","a"};
        String str3="";
        for (String str:str2){
            str3=str3+str;
        }
        boolean b1=(str1==str3);
        boolean b2=(str1.equals(str3));
        System.out.print(b1 + ", "+b2);
    }
}
What is the result?
A. true, true
B. true, false
C. false, true
D. false, false

Ans : C

Q-054

Given the code fragments:
class Student{
    String name;
    int age;
}
And,
4.  public class Test {
5.      public static void main(String[] args) {
6.          Student s1=new Student();
7.          Student s2=new Student();
8.          Student s3=new Student();
9.          s1=s3;
10.         s3=s2;
11.         s2=null;
12.    }
13. }
Which statement is true?
A. After line 11, two objects are eligible for garbage collection.
B. After line 11, none of the objects are eligible for garbage collection.
C. After line 11, three objects are eligible for garbage collection.
D. After line 11, one object is eligible for garbage collection.

Ans : D

Q-055

Given the following segment of code:
ArrayList<Vehicle> myList = new ArrayList<>();
myList.add(new MotorCycle());
Which two statements, if either were true, would make the code compile?
A. MotorCycle is a superclass of Vehicle.
B. Vehicle and MotoryCycle both implement the Transportation interface.
C. Vehicle is an interface that is implemented by the Motorcycle class.
D. Vehicle is a superclass of MotorCycle.
E. Vehicle and MotorCycle both extend the Transportation superclass.
F. MotorCycle is an interface that implements the Vehicle class.

Ans : C D

Q-056

class Student{
    String name;
    public Student(String name){
        this.name=name;
    }
}
public class Test {
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[1]=new Student("Richard");
        students[2]=new Student("Donald");
        for (Student s: students){
            System.out.println(""+s.name);
        }
    }
}
What is the result?
A. A NullPointerException is thrown at runtime.
B. Compilation fails.
C. Richard
   Donald
D. null
   Richard
   Donald
E. An ArrayIndexOutOfBoundsException is thrown at runtime.

Ans : A
student[0] 並沒有產生Student物件

Q-057

Given the code fragment:
public class Test {
    void readCard(int cardNo)throws Exception{
        System.out.println("Reading Card");
    }
    void checkCard(int cardNo)throws RuntimeException { //line n1
        System.out.println("Checking Card");
    }
    public static void main(String[] args) {
        Test ex=new Test();
        int cardNo=1234;
        ex.checkCard(cardNo);   //line n2
        ex.readCard(cardNo);    //line n3
    }
}

What is the result?
A. Compilation fails only at line n2.
B. Reading Card
   Checking Card
C. Compilation fails only at line n1
D. Compilation fails at both line n2 and line n3.
E. Compilation fail only at line n3.

Ans : E

Q-058

int nums1[]=new int[3];
int nums2[]={1, 2, 3, 4, 5};
nums1=nums2;
for (int x:nums1){
    System.out.print(x+":");
}
What is the result?
A. Compilation fails.
B. 1:2:3:4:5:
C. An ArrayOutOfBoundsException is thrown at runtime.
D. 1:2:3:

Ans : B

Q-059

public class Test {
    public static void main(String[] args) {
        int x=1;
        int y=0;
        if(x++ > ++y){
            System.out.print("Hello ");
        }
        else{
            System.out.print("Welcome ");
        }
        System.out.print("log " + x + ":" + y);
    }
}
What is the result?
A. Welcome Log 1:0
B. Hello Log 2:1
C. Hello Log 1:0
D. Welcome Log 2:1

Ans : D

Q-060

public class Test {
    int a1;
    public static void doProduct(int a){
        a=a*a;
    }
    public static void doString(StringBuilder s){
        s.append(" " + s);
    }
    public static void main(String[] args) {
        Test item=new Test();
        item.a1=11;
        StringBuilder sb=new StringBuilder("Hello");
        Integer i=10;
        doProduct(i);
        doString(sb);
        doProduct(item.a1);
        System.out.println(i + " " + sb +" " + item.a1);
    }
}
What is the result?
A. 10 Hello Hello 121
B. 100 Hello 121
C. 10 Hello Hello 11
D. 100 Hello Hello 121
E. 10 Hello 11

Ans : D

Q-061

Given the code snippet from a compiled Java source file:
public class MyFile {
    public static void main(String[] args) {
        String arg1= args[1];
        String arg2= args[2];
        String arg3= args[3];
        System.out.println("Arg is " + arg3);
    }
}
Which command line arguments should you pass to the program to obtain the following output?
Arg is 2
A. java MyFile 1 3 2 2
B. java MyFile 1 2 2 3 4
C. java MyFile 0 1 2 3
D. java MyFile 2 2 2

Ans : A

Q-062

Given the code fragment:
public static void main(String[] args) {
    int[] arr={1, 2, 3, 4};
    int i=0;
    do{
	System.out.print(arr[i] +" ");
	i++;
    }while (i < arr.length-1);
}
What is the result?
A. 1 2 3
B. Compilation fails.
C. 1 2 3 4
D. 1 2 3 4
   followed by an ArrayIndexOutOfBoundsException

Ans : A

Q-063

Given : 
public class Test {
    int x;
    int y;
    public void doStuff(int x, int y){
        this.x=x;
        y=this.y;
    }
    public void display(){
        System.out.print(x + " " + y + " : ");
    }
    public static void main(String[] args) {
        Test m1=new Test();
        m1.x=100;
        m1.y=200;
        Test m2=new Test();
        m2.doStuff(m1.x, m1.y);
        m1.display();
        m2.display();
    }
}
What is the result?
A. 100 0 : 100 200 :
B. 100 200 : 100 0 :
C. 100 200 : 100 200 :
D. 100 0 : 100 0 :  

Ans : B

Q-064

7.  StringBuilder sb1=new StringBuilder("Duke");
8.  String str1=sb1.toString();
9.  //insert code here
10. System.out.print(str1 == str2);
Which code fragment, when inserted at line 9, enables the code to print true?
A. String str2 = "Duke";
B. String str2 = new String(str1);
C. String str2 = str1;
D. String str2= sb1.toString();

Ans : C

Q-065

public class Test {
    public static void main(String[] args) {
        Test ts=new Test();
        System.out.print(isAvailable + " ");
        isAvailable = ts.doStuff();
        System.out.println(isAvailable);
    }
    public static boolean doStuff(){
        return !isAvailable;
    }
    static boolean isAvailable = false;
}
What is the result?
A. false true
B. true false
C. Compilation fails
D. true true
E. false false

Ans : A

Q-066

Given:
package clothing;
class Shirt{
    public static String getColor(){
        return "Green";
    }
}

Given the code fragment:
package clothing.pants;
//line n1
public class Jeans {
    public void matchShirt(){
        //line n2
        if (color.equals("Green")){
            System.out.print("Fit");
        }
    }
    public static void main(String[] args) {
        Jeans trouser = new Jeans();
        trouser.matchShirt();
    }
    public static boolean doStuff(){
        return !isAvailable;
    }
    static boolean isAvailable = false;
}
Which two sets of actions, idenpendently, enable the code fragment to print Fit?
A. At line n1 insert : import clothing;
   At line n2 insert: String color = Shirt.getColor();
B. At line n1 insert: import static clothing.Shirt.getColor;
   At line n2 insert: String color=getColor();
C. At line n1 no change required.
   At line n2 insert: String color=Shirt.getColor();
D. At line n1 insert: imort clothing.Shirt;
   At line n2 insert: String color = getColor();
E. At line n1 insert: import clothing.*;
   At line n2 insert: String color = Shirt.getColor();

Ans : E

Q-067

Given the code fragment
public class Employee{
    String name;
    boolean contract;
    double salary;
    Employee(){
        //line n1
    }
    public String toString(){
        return name + ":" + contract + ":" + salary;
    }
    public static void main(String[] args){
        Employee e=new Employee();
        //line n2
        System.out.print(e);
    }
}
Which two modifications, when made independently, enable the code to print Joe:true:100.0?
A. Replace line n2 with:
   e.name="Joe";
   e.contract = true;
   e.salary = 100;
B. Replace line n1 with:
   this.name=new String("Joe");
   this.contract = new Boolean(true);
   this.salary = new Double(100);
C. Replace line n1 with:
   this("Joe", true, 100);
D. Replace line n1 with:
   name = "Joe";
   contract = TRUE;
   salary = 100.0f;
E. Replace line n2 with:
   this.name = "Joe";
   this.contract = true;
   this.salary =100;

Ans : A B

Q-068

Given:
Acc.java:
package p1;
public class Acc{
   int p;
   private int q;
   protected int r;
   public int s;
}

Test.java:
package p2;
import p1.Acc;
public class Test extends Acc{
   public static void main(String[] args{
       Acc obj=new Test();
   }
}
Which statement is true;
A. p, r, and s are accessible via obj.
B. Both p and s are accessible via obj.
C. Both r and s are accessible via obj.
D. Only s is accessible via obj.

Ans : D

Q-069

public class Test {
    public static void main(String[] args) {
        boolean a=new Boolean(Boolean.valueOf(args[0]));
        boolean b=new Boolean(args[1]);
        System.out.println(a + " " + b);
    }
}
And given the commands:
javac Test.java
java Test TRUE null
What is the result?
A. false false
B. TRUE null
C. true true
D. A ClassCastException is thrown at runtime.
E. true false

Ans : E

Q-070

Which statement is true about the switch statement?
A. The break statement, at the end of each case block, is mandatory.
B. Its expression must evaluate to a single value.
C. Its case label literals can be changed at runtime.
D. It must contain the default section.

Ans : B
mandatory[ˋmændə͵torɪ] : 強制的

Q-071

04 class X{
05     public void printFileContent(){
06         /* code goes here */
07         throw new IOException();
08     }
09 }
10 public class Test {
11     public static void main(String[] args){
12         X xobj=new X();
13         xobj.printFileContent();
14     }
15 }
Which two modifications should you make so that the code compiles successfully?
A. Replace line 5 with public void printFileContent() throws IOException{
B. Replace line 11 with public static void main(String[] args) throws Exception {
C. At line 14, insert throw new IOException();
D. Replace line 7 with throw IOException("Excpetion raised");
E. Replace line 13 with
   try{
       xobj.printFileContent();
   }
   catch(Exception e){}
   catch(IOException e){}

Ans : A B

Q-072

Given:
public class Triangle {
    static double area;
    int b=2, h=3;
    public static void main(String[] args){
        double p, b, h; //line n1
        if(area==0){
            b=3;
            h=4;
            p=0.5;
        }
        area = p*b*h;   //line n2
        System.out.println("Area is " + area);
    }
}
What is the result?
A. Compilation fails at line n1.
B. Compilation fails at line n2.
C. Area is 6.0
D. Area is 3.0

Ans : B
解說
double p, b, h;
if(area==0){ 
    b=3; 
    h=4; 
    p=0.5; 
}
會造成b, h, p可能沒有初始化的錯誤

Q-073

public class Test {
    int x, y;
    public Test(int x, int y){
        initialize(x, y);
    }
    public void initialize(int x, int y){
        this.x=x*x;
        this.y=y*y;
    }
    public static void main(String[] args){
        int x=3, y=5;
        Test obj=new Test(x, y);
        System.out.println(x + " " + y);
    }
}
What is the result?
A. 3 5
B. 0 0
C. Compilation fails.
D. 9 25

Ans : A

Q-074

class Alpha{
    int ns;
    static int s;
    Alpha(int ns){
        if(s<ns){
            s=ns;
            this.ns=ns;
        }
    }
    void doPrint(){
        System.out.println("ns = " + ns + " s= " + s);
    }
}
public class Test {
    public static void main(String[] args){
        Alpha ref1=new Alpha(50);
        Alpha ref2=new Alpha(125);
        Alpha ref3=new Alpha(100);
        ref1.doPrint();
        ref2.doPrint();
        ref3.doPrint();
    }
}

What is the result?

A. ns = 50 s= 50
   ns = 125 s= 125
   ns = 100 s= 100
B. ns = 50 s= 125
   ns = 125 s= 125
   ns = 0 s= 125
C. ns = 50 s= 125
   ns = 125 s= 125
   ns = 1000 s= 125
D. ns = 50 s= 50
   ns = 125 s= 125
   ns = 0 s= 125

Ans : B

Q-075

Which two class definitions fail to compile?
A. class A4{
       protected static final int i;
       private void doStuff(){}
   }
B. abstract class A3{
       private static int i;
       public void doStuff(){}
       public A3(){}
   }
C. public class A2{
       private static int i;
       private A2(){}
   }
D. final class A1{
       public A1(){}
   }
E. final abstract class A5{
       protected static int i;
       void doStuff(){}
       abstract void doIt();
   }
Ans : A E
解說:
A. protected final static int i必需要初始化
E. abstract 跟 final不可以同時出現

Q-076

public class Test {
    public static void main(String[] args){
        Short s1=200;
        Integer s2=400;
        Long s3=(long)s1+s2;        //line n1
        String s4=(String)(s3*s2);  //line n2
        System.out.println("Sum is "+s4);
    }
}
What is the result?
A. A ClassCastException is thrown at line n1.
B. Compilation fails at line n1.
C. Sum is 600
D. Compilation fails at line n2.
E. A ClassCastException is thrown at line n2.

Ans : D
解說
數字轉字串, 必需使用String.valueOf(數字格式)
int a=10;
String s=String.valueOf(a);

Q-077

public class Jump {
    static String args[]={"Lazy", "Lion", "is", "always"};
    public static void main(String[] args){
        System.out.println(args[1] + " " + args[2] + " " + args[3] + " jumping");
    }
}
And the commands:
javac Jump.java
java Jump Crazy Elephant is always

What is the result?
A. Lazy Lion is jumping
B. Lion is always jumping
C. Crazy elephant is jumping
D. Elephant is always jumping
E.Compilation fails

Ans : D

Q-078

Which tree are valid types for switch?

A. int
B. float
C. double
D. Integer
E. String
F. Float
Ans : A D E
switch裏的條件, 只可以為 byte, short, int, String共四個
Byte, Short, Integer 會自動解封裝成 byte, short, integer, 所以也可以

Q-079

class Circle{
    double radius;
    public double area;
    public Circle(double r){radius=r;}
    public double getRadius(){return radius;}
    public void setRadius(double r){radius =r;}
    public double getArea(){return /* ??? */;}
}
public class Test {
    public static void main(String[] args){
        Circle c1=new Circle(17.4);
        c1.area=Math.PI * c1.getRadius() * c1.getRadius();
    }
}

This class is poorly encapsulated. You need to change the circle class to compute and 
return the area instead. 
What three modifications are necessary to ensure that the class is being properly encapsulated?

A. Change the access modifier of the setradius() method to private
B. Change the getArea() method public double getArea(){return area;}
C. When the radius is set in the Circle constructor and the setRadius() method, 
   recomputed the area and store it into the area field.
D. Change the getRadius() method: 
   public double getRadius(){
       area = Math.PI * radius * radius;
       return radius;
   }

Ans : B C D
其實D並不需要, 但題目要求要三個答案, 所以只能捨棄掉絕對是錯誤的A

Q-080

Which two statements are true for a two-dimensional array?

A. It cannot contain elements of different types.
B. Using a row by column convention, each row of a two-dimensional array must be of the same size.
C. At declaration time, the number of elements of the array in each dimension must be specified.
D. All methods of the class Object may be invoked on the two-dimensional array.

Ans : A D
A : 陣列只能包含一種型態, 所以是對的
D : Object類別裏的所有方法, 都可以被二維陣列使用, 因為二維陣列是繼承Object的子類別

Q-081

class CD{
    int r;
    CD(int r){
        this.r=r;
    }
}
class DVD extends CD{
    int c;
    DVD(int r, int c){
        //line n1
    }
}
And given the code fragment:
DVD dvd=new DVD(10,20);
which code fragment should you use at line n1 to instantiate the dvd object successfully?
A. super.r=r;
   this.c=c;
B. super(r);
   this(c);
C. super(r);
   this.c=c;
D. this.c=r;
   super(c);

Ans: C

底下網站, 有更多的考古題

https://blog.csdn.net/pxg943055021/article/details/80068512

發佈留言

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