2009年2月13日 星期五

第119題

Given:
11. public static void main(String[] args){
12. String str = "null";
13. if (str == null) {
14. System.out.println("null");
15. }else (str.length() == 0) {
16. System.outprintln("zero");
17. }else{
18. System.out.println("some");
19. }
20. }
What is the result?
A. null
B. zero
C. some
D. Compilation fails.
E. An exception is thrown at runtime.
答案:D
參考:4-1 條件控制、11-2 文字類型

---------------------------------------------

第15行改成 else if 就可以編譯.

第118題

Given
10. class Foo{
11. static void alpha(){/* more code here */}
12. void beta() {/* more code here */)
13. }
Which two statements are true? (Choose two.)
A. Foo.beta() is a valid invocation of beta().
B. Foo.alpha() is a valid invocation of alpha().
C. Method beta() can directly call method alpha().
D. Method alpha() can directly call method beta().
答案:BC
參考:8-2 方法種類與呼叫方式

-------------------------------------------

B. Foo.alpha() is a valid invocation of alpha(). //static 可以呼叫 static方法
C. Method beta() can directly call method alpha(). // non-static 也可以呼叫static方法............

第117題

Given:
11. class Converter{
12. public static void main(String[] args){
13. Integer i = args[0];
14. int j = 12;
15. System.out.println("It is " + (j==i) + " that j==i.");
16. }
17. }
What is the result when the programmer attempts to compile the code and run it with the command
java Converter 12?
A. It is true that j==i.
B. It is false that j==i.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 13.
答案:D
參考:8-4 main()方法的參數傳遞與系統屬性設定

----------------------------------------

args 是 String, 所以不能指派給 Integer.

第116題

Given:
11. public class Commander{
12. public static void main(String[] args){
13. String myProp = /* insert code here */
14. System.out.println(myProp);
15. }
16. }
and the command line:
java -Dprop.custom=gobstopper Commander
Which two, placed on line 13, will produce the output gobstopper? (Choose two.)
A. System.load("prop.custom");
B. System.getenv("prop.custom");
C. System.property("prop.custom);
D. System.getProperty("prop.custom");
E. System.getProperties().getProperty("prop.custom");
答案:DE
參考:8-4 main()方法的參數傳遞與系統屬性設定

--------------------------------------------------

-D 代表設定系統屬性. 屬性名稱是 prop.custom, 對應值是 gobstopper.
所以用getProperty("prop.custom").
或是 用 getProperties() 物件 裡面的 getProperty("prop.custom")

第115題

Given:
11. public static void main(String[] args){
12. for(int i = 0; i <= 10; i++){
13. if(i > 6) break;
14. }
15. System.out.println(i);
16. }
What is the result?
A. 6
B. 7
C. 10
D. 11
E. Compilation fails.
F. An exception is thrown at runtime.
答案:E
參考:8-1 變數種類與其生命期

-------------------------------------------

15. 行要列出 i, i在 for 回圈結束就沒了, 所以編譯失敗.

第114題

Given:
10. class line{
11. public class Point{public int x, y;}
12. public Point getPoint(){return new Point();}
13. }
14. class Triangle{
15. public Triangle(){
16. //insert code here
17. }
18. }
Which code, inserted at line 16, correctly retrieves a local instance of a Point object?
A. Point p = Line.getPoint();
B. Line.Point p = Line.getPoint();
C. Point p = (new Line()).getPoint();
D. Line.Point p = (new Line()).getPoint();
答案:D
參考:8-5 內部類別

-----------------------------------------

Point 屬於 Line的實體內部類別, 所以要冠上外部類別名稱.
new Line().getPoint(), new 一個Line的物件,並呼叫getPoint(), 回傳 new Point(), 就得到Point 物件

第113題

Given:
10. public class Foo{
11. static int[] a;
12. static{ a[0] = 2;}
13. public static void main( String[] args){}
14. }
Which exception or error will be thrown when a programmer attempts to run this code?
A. java.lang.StackOverflowError
B. java.lang.IllegalStateException
C. java.lang.ExceptionInInitializerError
D. java.lang.ArrayIndexOutOfBoundsException
答案:C
參考:8-1 變數種類與其生命期、9-1 執行上的錯誤

--------------------------------------------------

11. 宣告一個static 陣列 但是沒有實體化
12. 屬於static 初始器, 但是a 沒有實體化, 所以a 根本不存在. 造成執行上的錯誤

2009年2月12日 星期四

第105題

Given:
1. public class A {
2.
3. private int counter = 0;
4
5. public static int getInstanceCount(){
6. return counter;
7. }
8.
9. public A(){
10. counter++;
11. }
12.
13. }
And given this code from Class B:
25. A a1 = new A();
26. A a2 = new A();
27. A a3 = new A();
28. System.out.println(A.getInstanceCount());
What is the result?
A. Compilation of class A fails.
B. Line 28 prints the value 3 to System.out.
C. Line 28 prints the value 1 to System.out.
D. A runtime error occurs when line 25 executes.
E. Compilation fails because of an error on line 28.
答案:A
參考:8-2 方法種類與呼叫方式

-------------------------------------

5行 屬於static 方法, 回傳 counter.
counter 是 實體變數, 不能放在static 區域範圍內使用.

第104題

Given:
10. class Line{
11. public static class Point{}
12. }
13.
14. class Triangle{
15. //insert code here
16. }
Which code, inserted at line 15, creates an instance of the Point class defined in Line?
A. Point p = new Point();
B. Line.Point p = new Line.Point();
C. The Point class cannot be instatiated at line 15.
D. Line l = new Line(); l.Point p = new l.Point();
答案:B
參考:8-5 內部類別

------------------------------------------------

產生static物件實體要冠上外部類別名稱,該類別名稱.

第103題

Given:
11. public enum Title{
12. MR("Mr."), MRS("Mrs."), MS("Ms.");
13. private final String title;
14. private Title(String t){title = t;}
15. public String format(String last, String first){
16. return title + " " + first + " " + last;
17. }
18. }
19. public static void main(String[] args){
20. System.out.println(Title.MR.format("Doe", "John"));
21. }
What is the result?
A. Mr. John Doe
B. An exception is thrown at runtime.
C. Compilation fails because of an error in line 12.
D. Compilation fails because of an error in line 15.
E. Compilation fails because of an error in line 20.
答案:A
參考:8-6 Java列舉類型

---------------------------------------------

20行先呼叫Title裡的MR, MR是列舉類型Title裡的屬性.
MR會呼叫建構子14行, 傳入"Mr.".
之後在乎叫format(String last, String first).

第102題

Given:
10. interface Foo{int bar();}
11. public class Sprite{
12. public int fubar(Foo foo){return foo.bar();}
13. public void testFoo(){
14. fubar(
15. //insert code here
16. );
17. }
18. }
Which code, inserted at line 15, allows the class Sprite to compile?
A. Foo{public int bar(){return 1;}}
B. new Foo{public int bar(){return 1;}}
C. new Foo(){public int bar(){return 1;}}
D. new class Foo{public int bar(){return 1;}}
答案:C
參考:8-5 內部類別

---------------------------------------

14 行要 呼叫 12 行public int fubar(Foo foo) , 此方法的參數是 Foo類型.
C是用暱名類別實做10. interface Foo{int bar();} 就可當作參數來傳遞.

第101題

Given:
10. package com.sun.scjp;
11. public class Geodetics {
12. public static final double DIAMETER = 12756.32; //kilometers
13. }
Which two correctly access the DIAMETER member of the Geodetics class? (Choose two.)
A. import com.sun.scjp.Geodetics;
public class TerraCarta{
public double halfway()
{return Geodetics.DIAMETER/2.0;}
B. import static com.sun.scjp.Geodetics;
public class TerraCarta{
public double halfway(){return DIAMETER/2.0;}}
C import static com.sun.scjp.Geodetics.*;
public class TerraCarta{
public double halfway(){return DIAMETER/2.0;}}
D. package com.sun.scjp;
public class TerraCarta{
public double halfway(){return DIAMETER/2.0;}}
答案:AC
參考:8-2 方法種類與呼叫方式

------------------------------------------------

DIAMETER 是 static 變數, 存取他要透過類別名稱.
A.
C. 直接import static

第100題

Given:

10. public class SuperCalc{
11. protected static int multiply(int a, int b){return a * b;}
12. }
and:
20. public class SubCalc extends SuperCalc{
21. public static int multiply(int a, int b){
22. int c = super.multiply(a, b);
23. return c;
24. }
25. }
and:
30. SubCalc sc = new SubCalc();
31. System.out.println(sc.multiply(3, 4));
32. System.out.println(SubCalc.multiply(2, 2));
What is the result?
A. 12
B. The code runs with no output.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 21.
E. Compilation fails because of an error in line 22.
F. Compilation fails because of an error in line 31.
答案:E
參考:8-2 方法種類與呼叫方式

-------------------------------------

public static int multiply(int a, int b) 是 static 方法, 裡面不可以放 super 或 this 關鍵字

第99題

Given:
3. interface Animal{void makeNoise();}
4. class Horse implements Animal{
5. Long weight = 1200L;
6. public void makeNoise(){System.out.println("whinny");}
7. }
8. public class lcelandic extends Horse{
9. public void makeNoise(){System.out.println("vinny");}
10. public static void main(String[] args) {
11. Icelandic i1 = new lcelandic();
12. Icelandic i2 = new lcelandic();
13. Icelandic i3 = new lcelandic();
14. i3 = i1; i1 = i2; i2 = null; i3 = i1;
15. }
16. }
When line 14 is reached, how many objects are eligible for the garbage collector?
A. 0
B. 1
C. 2
D. 3
E. 4
F. 6
答案:C
參考:8-7 資源回收機制

------------------------------------

i1, i2, i3 分別為三個實體.
i3 = i1; // i3 參照11行 i1的實體, i3 原本參照的變為資源回收的對象
i1 = i2; // i1 參照12行 i2的實體, 此時i1 原本的實體還是有i3參照
i2 = null; //i2 不在參照任何實體, 但i1仍然參照i2的實體
i3 = i1; //i3 再次參找目前i1的實體, 就是12行原本i2的實體.
//結果 i1 和 i3 參照12行i2 的實體, 11和13行的就沒有參照,變回資源回收的對象.

2009年2月11日 星期三

第91題

A class games.cards.Poker is correctly defined in the jar file Poker.jar. A user wants to execute the main method of Poker on a UNIX system using the command:
java games.cards.Poker
What allows the user to do this?
A. put Poker.jar in directory /stuff/java, and set the CLASSPATH to include /stuff/java
B. put Poker.jar in directory /stuff/java, and set the CLASSPATH to include /stuff/java/*.jar
C. Put Poker.jar in directory /stuff/java, and set the CLASSPATH to include /stuff/java/Poker.jar
D. put Poker.jar in directory /stuff/java/games/cards, and set the CLASSPATH to include /stuff/java
E. put Poker.jar in directory /stuff/java/games/cards, and set the CLASSPATH to include /stuff/java/*.jar
F. put Poker.jar in directory /stuff/java/games/cards, and set the CLASSPATH to include /stuff/java/Poker.jar

答案:C
參考:7-2 編譯Java 專案套件

----------------------------------------

把Poker.jar放入/stuff/java 用 CLASSPATH 設定完整的外部路徑 /stuff/java/Poker.jar

第112題

Given:
12. public class Test{
13. public enum Dogs{collie, harrier);
14. public static void main(String[] args){
15. Dogs myDog = Dogs.collie;
16. switch(myDog){
17. case collie:
18. System.out.print("collie ");
19. case harrier:
20. System.out.print("harrier ");
21. }
22. }
23. }
What is the result?
A. collie
B. harrier
C. Compilation fails.
D. collie harrier
E. An exception is thrown at runtime.
答案:D
參考:4-1 條件控制、8-6 Java列舉類型
-----------------------------------------------------------
15. Dogs myDog = Dogs.collie;
17. case collie: 比對成功
18. System.out.print("collie "); //collie
19. case harrier: //不會執行
20. System.out.print("harrier "); //harrier

第111題

Given:
15. public class Pass2{
16. public void static main(String[] args){
17. int x = 6;
18. Pass2 p = new Pass2();
19. p.doStuff(x);
20. System.out.print(" main x = " + x);
21. }
22.
23. void doStuff(int x){
24. System.out.print(" doStuff x = " + x++);
25. }
26. }
And the command-line invocations:
javac Pass2.java
java Pass2 5
What is the result?

A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuff x = 6 main x = 6
D. doStuff x = 6 main x = 7
E. doStuff x = 7 main x = 6
F. doStuff x = 7 main x = 7

答案:C
參考:4-1 條件控制、8-2 方法種類與呼叫方式
-----------------------------------------------------------
17. int x = 6;
19. p.doStuff(x); //傳值6
23. void doStuff(int x){ //接到6
24. System.out.print(" doStuff x = " + x++); //先列印doStuff x = 6後x再+1
25. }//結束}後回到原呼叫式的後面20. System.out.print(" main x = " + x); //main x = 6

第90題

Given:
11. interface DeclareStuff{
12. public static final int EASY = 3;
13. void doStuff(int t);}
14. public class TestDeclare implements DeclareStuff{
15. public static void main(String[] args){
16. int x = 5;
17. new TestDeclare().doStuff(++x);
18. }
19. void doStuff(int s){
20. s += EASY + ++s;
21. System.out.println("s " + s);
22. }
23. }

What is the result?
A. s 14
B. s 16
C. s 10
D. Compilation fails.
E. An exception is thrown at runtime.

答案:D
參考:7-6 介面

-----------------------------------------

19. void doStuff(int s) 企圖改寫 13. void doStuff(int t); 但是13因為在interface裡面所以預設權限是public, 而19 行是在 public class 裡面, 預設是default. Default 不能改寫public.

第110題

Given:
11. public static void test(Sting str){
12. int check = 4;
13. if(check = str.length()){
14. System.out.print(str.charAt(check -= 1) + ", ");
15. }else{
16. System.out.print(str.charAt(O) + ", ");
17. }
18. }
and the invocation:
21. test("four");
22. test("tee");
23. test("to");
What is the result?
A. r, t, t,
B. r, e, o,
C. Compilation fails.
D. An exception is thrown at runtime.
答案:C
參考:4-1 條件控制、8-2 方法種類與呼叫方式
------------------------------------------------------------
13. if(check = str.length()){ //if(check == str.length())

第89題

Given:
1. public class Car{
2. private int wheelCount;
3. private String vin;
4. public Car(String vin){
5. this.vin = vin;
6. this.wheelCount = 4;
7. }
8. public String drive(){
9. return "zoom-zoom";
10. }
11. public String getInfo(){
12. return "VIN: " + vin + "wheels: " + wheelCount;
13. }
14. }
And:
1. public class MeGo extends Car{
2. public MeGo(String vin){
3. this.wheelCount = 3;
4. }
5. }

What two must the programmer do to correct the compilation errors? (Choose two.)
A. insert a call to this() in the Car constructor
B. insert a call to this() in the MeGo constructor
C. insert a call to super() in the MeGo constructor
D. insert a call to super(vin) in the MeGo constructor
E. change the wheelCount variable in Car to protected
F. change line 3 in the MeGo class to super.wheelCount = 3;
答案:DE
參考:6-5 繼承、7-3 存取修飾詞的使用

-----------------------------------------------------

D. 加個 super(vin) 在MeGo的建構式裡, 如果不加程式會自己加super(); 但是父類別裡沒有無參數的建構子.
E. MeGo 裡面是存取 父類別 Car的 WheelCount,但是 Car的 WheelCount 是 private,是無法存取.
所以改成protected.

第109題

Given:
5. class Payload{
6. private int weight;
7. public Payload (int w){weight = w;}
8. public void setWeight(int w){weight = w;}
9. public String toString(){return Integer.toString(weight);}
10. }
11. public class TestPayload{
12. static void changePayload(Payload p){/* insert code */}
13. public static void main(String[] args){
14. Payload p = new Payload(200);
15. p.setWeight(1024);
16. changePayload(p);
17. System.out.println("p is " + p);
18. }}
Which code fragment, inserted at the end of line 12, produces the output p is 420?

A. p.setWeight(420);
B. p.changePayload(420);
C. p = new Payload(420);
D. Payload.setWeight(420);
E. p = Payload.setWeight(420);

答案:A

參考:8-2 方法種類與呼叫方式

第108題


Given:
11. class Snoochy {
12. Boochy booch;
13. public Snoochy(){booch = new Boochy(this);}
14 }
15.
16. class Boochy{
17. Snoochy snooch;
18. public Boochy(Snoochy s){snooch = s;}
19. }
And the statements.
21. public static void main(String[] args){
22. Snoochy snoog = new Snoochy();
23. snoog = null;
24. //more code here
25. }

Which statement is true about the objects referenced by snoog, snooch, and booch immediately after line 23
executes?

A. None of these objects are eligible for garbage collection.
B. Only the object referenced by booth is eligible for garbage collection.
C. Only the object referenced by snoog is eligible for garbage collection.
D. Only the object referenced by snooch is eligible for garbage collection.
E. The objects referenced by snooch and booth are eligible for garbage collection.

答案:E
參考:8-7 資源回收機制
-----------------------------------------------------------------------------------


第88題

第88題
Which Three statements are true? (Choose Three.)
A. A final method in class X can be abstract if and only if X is abstract.
B. A protected method in class X can be overridden by any subclass of X.
C. A private static method can be called only within other static methods in class X.
D. A non-static public final method in class X can be overridden in any subclass of X.
E. A public static method in class X can be called by a subclass of X without explicitly referencing the class X.
F. A method with the same signature as a private final method in class X can be implemented in a subclass of X.
G. A protected method in class X can be overridden by a subclass of X only if the subclass is in the same package as X.

答案:BEF
參考:6-5 繼承、7-3 存取修飾詞的使用、8-2 方法種類與呼叫方式

-----------------------------------------------------------------

B. 一個 protected 的 method 可以被任何子類別改寫. 不論是否在相同的package裡
E. 呼叫 static的方法 不需要透過物件來呼叫(explicitly referencing )
F. 此處只是簽章相同, 並不是用改寫, 所以OK

第107題

Given:
10. class Inner{
11. private int x;
12. public void setX(int x){this.x = x;}
13. public int getX(){return x;}
14. }
15.
16. class Outer{
17. private Inner y;
18. public void setY(Inner y){this.y = y;}
19 public Inner getY(){return y;}
20. }
21.
22. public class Gamma{
23. public static void main(String[] args){
24. Outer o = new Outer();
25. Inner i = new Inner();
26. int n = 10;
27. i.setX(n);
28. o.setY(i);
29. //insert code here
30. System.out.println(o.getY().getX());
31. }
32. }
Which three code fragments, added individually at line 29, produce the output 100? (Choose three.)
A. n = 100;
B. i.setX(100);
C. o.getY().setX(100);
D. i = new Inner(); i.setX(100);
E. o.setY(i); i = new Inner(); i.setX(100);
F. i = new Inner(); i.setX(100); o.setY(i);
答案:BCF
----------------------------------------------------------------------------------
B. i.setX(100);
C. o.getY().setX(100); //o.getY()=i >>同b
參考:7-4 封裝、8-1 變數種類與其生命期

第87題

A team of programmers is involved in reviewing a proposed design for a new utility class, After some
discussion, they realize that the current design allows other classes to access methods in the utility class that
should be accessible only to methods within the utility class itself. What design issue has the team
discovered?
A. Tight coupling
B. Low cohesion
C. High cohesion
D. Loose coupling
E. Weak encapsulation
F. Strong encapsulation
答案:E
參考:7-4 封裝

---------------------------------

一隊程式員發現他們的utility class裡面有些功能目前是能讓其他class作存取的. 但是那些應該只能在utility class裡面存取. 這樣代表了什麼樣的設計問題?

E. Weak encapsulation (低的封裝).

第106題

Given classes defined in two different files:
1. package util;
2. public class BitUtils{
3. public static void process(byte[] b){/* more code here */}
4. }
1. package app;
2. public class SomeApp{
3. public static void main(String[] args){
4. byte[] bytes = new byte[256];
5. //insert code here
6. }
7. }
What is required at line 5 in class SomeApp to use the process method of BitUtils?
A. process(bytes);
B. BitUtils.process(bytes);
C. util.BitUtils.process(bytes);
D. SomeApp cannot use methods in BitUtils.
E. import util.BitUtils.*; process(bytes);

答案:C
參考:7-1 Java套件、8-3 類別成員的匯入

第98題

Given:
15. public class Yippee{
16. public static void main(String[] args){
17. for(int x = 1; x < args.length; x++){
18. System.out.print(args[x] + " ");
19. }
20. }
21. }
and two separate command line invocations:
java Yippee
java Yippee 1 2 3 4
What is the result?

A. No output is produced. 123
B. No output is produced. 234
C. No output is produced. 1234
D. An exception is thrown at runtime. 123
E. An exception is thrown at runtime. 234
F. An exception is thrown at runtime. 1234
答案:B
參考:8-4 main()方法的參數傳遞與系統屬性設定
-------------------------------------------------------------------
java Yippee //沒傳參數No output is produced.
java Yippee 1 2 3 4 //x從1開始 234

第86題

Given:
10. abstract class A{
11. abstract void a1();
12. void a2(){}
13. }
14. class B extends A{
15. void a1(){}
16. void a2(){}
17. }
18. class C extends B{void c1(){}}
and:
A x = new B(); C y = new C(); A z = new C();
What are four valid examples of polymorphic method calls? (Choose four.)
A. x.a2();
B. z.a2();
C. z.c1();
D. z.a1();
E. y.c1();
F. x.a1();
答案:ACEF
參考:7-9 多型

-----------------------------------------

x, y, z 的實體類型 分別是 B, C, C.
錯誤:

B. z.a2();// c 裡面沒有a2()
D. z.a1(); // c 裡面沒有 a1()

第97題

Which statement is true?
A. A class's finalize() method CANNOT be invoked explicitly.
B. super.finalize() is called implicitly by any overriding finalize() method.
C. The finalize() method for a given object is called no more than once by the garbage collector.
D. The order in which finalize() is called on two objects is based on the order in which the
two objects became finalizable.
答案:C
參考:8-7 資源回收機制
-------------------------------------------------------------------
A. A class's finalize() method CANNOT be invoked explicitly. //可以被明確呼叫
B. super.finalize() is called implicitly by any overriding finalize() method. //不會自動執行
D. The order in which finalize() is called on two objects is based on the order in which the

two objects became finalizable. //資源回收機制的順序沒有一定

第96題

Given a class Repetition:
1. package utils;
2.
3. public class Repetition {
4. public static String twice(String s){return s + s;}
5.
}
and given another class Demo:
1. // insert code here
2.
3. public class Demo {
4. public static void main(String[] args){
5. System.out.println(twice("pizza"));
6. }
7. }
Which code should be inserted at line 1 of Demo.java to compile and run Demo to print "pizzapizza"?
A. import utils.*;
B. static import utils.*;
C. import utils.Repetition.*;
D. static import utils.Repetition.*;
E. import utils.Repetition.twice();
F. import static utils.Repetition.twice;
G. static import utils.Repetition.twice;
答案:F
參考:8-3 類別成員的匯入
-------------------------------------------------------------------
第一行插入程式碼讓程式可以執行
5. System.out.println(twice("pizza")); //呼叫 twice的方法並傳入"pizza",試圖call 第4行
因此 System.out.println(Repetition.twice("pizza"));
沒有的話第一行要加F. import static utils.Repetition.twice;

第95題

Given:
1. interface TestA{String toString();}
2. public class Test{
3. public static void main(String[] args){
4. System.out.println(new TestA(){
5. public String toString(){return "test";}
6. });
7. }
8. }
What is the result?
A. test
B. null
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 1.
E. Compilation fails because of an error in line 4.
F. Compilation fails because of an error in line 5.
答案:A
參考:8-5 內部類別
-------------------------------------------------------------------
4. System.out.println(new TestA(){
5. public String toString(){return "test";}
6. }); //命名類別實做TestA的toString方法,所以在print時會列出test

第85題

Given:
11. class Animal{public String noise(){return "peep";}}
12. class Dog extends Animal{
13. public String noise(){return "bark";}
14 }
15. class Cat extends Animal{
16. public String noise(){return "meow";}
17. }
...
30. Animal animal = new Dog();
31. Cat cat = (Cat)animal;
32. System.out.println(cat.noise());
What is the result?
A. peep
B. bark
C. meow
D. Compilation fails.
E. An exception is thrown at runtime.
答案:E
參考:7-8 物件的轉型

---------------------------------------


animal實體為dog, animal不能轉型為貓

第94題

Given:
11. public class Rainbow {
12. public enum MyColor {
13. RED(0xff0000), GREEN(0x00ff00), BLUE(0x0000ff);
14. private final int rgb;
15. MyColor(int rgb){this.rgb = rgb;}
16. public int getRGB(){return rgb;}
17. }
18. public static void main(String[] args){
19. //insert code here
20. }
21. }
Which code fragment inserted at line 19, allows the Rainbow class to compile?
A. MyColor skyColor = BLUE;
B. MyColor treeColor = MyColor.GREEN;
C. if(RED.getRGB() < BLUE.getRGB()){}
D. Compilation fails due to other error(s) in the code.
E. MyColor purple = new MyColor(0xff00ff);
F. MyColor purple = MyColor.BLUE + MyColor.RED;
答案:B
參考:8-5 內部類別、8-6 Java列舉類型
-------------------------------------------------------------------

A. MyColor skyColor = BLUE; //MyColor skyColor = MyColor.BLUE;
C. if(RED.getRGB() < BLUE.getRGB()){} //不可以直接用比較運算
D. Compilation fails due to other error(s) in the code. //不會編譯失敗
E. MyColor purple = new MyColor(0xff00ff); //類舉類型不可以實體化
F. MyColor purple = MyColor.BLUE + MyColor.RED; //類舉類型不可以用在加法運用上

第93題

Given:
10. class Nav{
11. public enum Direction { NORTH, SOUTH, EAST, WEST }
12. }
13. public class Sprite{
14. //insert code here
15. }
Which code, inserted at line 14, allows the Sprite class to compile?
A. Direction d = NORTH;
B. Nav.Direction d = NORTH;
C. Direction d = Direction.NORTH;
D. Nav.Direction d = Nav.Direction.NORTH;
答案:D
參考:8-5 內部類別、8-6 Java列舉類型
-------------------------------------------------------------------
在14行插入一行程式碼讓程式編譯成功
10. class Nav{
11. public enum Direction { NORTH, SOUTH, EAST, WEST }
12. } //列舉類型在Nav中所以為內部類別,所以在存取上要用外部類別的名稱

第92題

Given a correctly compiled class whose source code is:

1. package com.sun.sjcp;
2. public class Commander {
3. public static void main(String[] args) {
4. // more code here
5. }
6. }
Assume that the class file is located in /foo/com/sun/sjcp/, the current directory is /foo/, and that the classpath
contains "." (current directory)
.
Which command line correctly runs Commander?

A. java Commander
B. java com.sun.sjcp.Commander
C. java com/sun/sjcp/Commander
D. java -cp com.sun.sjcp Commander
E. java -cp com/sun/sjcp Commander
答案:B
參考:7-2 編譯Java 專案套件
-------------------------------------------------------------------
執行時打內部路徑即可

打符號即 show 出 html 碼

http://leftlogic.com/lounge/articles/entity-lookup/

第84題

Given:
11. class Alpha{
12. public void foo(){System.out.print("Afoo ");}
13. }
14. public class Beta extends Alpha{
15. public void foo(){System.out.print("Bfoo ");}
16. public static void main(String[] args){
17. Alpha a = new Beta();
18. Beta b = (Beta)a;
19. a.foo();
20. b.foo();
21. }
22. }
What is the result?
A. Afoo Afoo
B. Afoo Bfoo
C. Bfoo Afoo
D. Bfoo Bfoo
E. Compilation fails.
F. An exception is thrown at runtime.
答案:D
參考:7-9 多型
-----------------------------------------------------------
17. Alpha a = new Beta();
18. Beta b = (Beta)a;
19. a.foo(); //15. public void foo(){System.out.print("Bfoo ");}
20. b.foo(); //15. public void foo(){System.out.print("Bfoo ");}

第83題

Given:
10. interface Foo{
11. int bar();
12. }
13.
14. public class Beta {
15.
16. class A implements Foo{
17. public int bar(){return 1;}
18. }
19.
20. public int fubar(Foo foo){return foo.bar();}
21.
22. public void testFoo(){
23.
24. class A implements Foo{
25. public int bar() {return 2;}
26. }
27.
28. System.out.println(fubar(new A()));
29. }
30.
31. public static void main(String[] argv){
32. new Beta().testFoo();
33. }
34. }
Which three statements are true? (Choose three.)

A. Compilation fails.
B. The code compiles and the output is 2.
C. If lines 16, 17 and 18 were removed, compilation would fail.
D. If lines 24, 25 and 26 were removed, compilation would fail.
E. If lines 16, 17 and 18 were removed, the code would compile and the output would be 2.
F. If lines 24, 25 and 26 were removed, the code would compile and the output would be 1.
答案:BEF
參考:7-6 介面、8-5 內部類別
-------------------------------------------------
32. new Beta().testFoo();
>>22. public void testFoo(){
>>28. System.out.println(fubar(new A()));
>>20. public int fubar(Foo foo){return foo.bar();}
>>24. class A implements Foo{
>>25. public int bar() {return 2;} //B. The code compiles and the output is 2.


E. If lines 16, 17 and 18 were removed, the code would compile and the output would be 2.
lines 16, 17 and 18 和選項b無關故一樣output is 2


lines 24, 25 and 26 移除的話
>>28. System.out.println(fubar(new A()));
>>16. class A implements Foo{
>>17. public int bar(){return 1;} //output would be

第82題

Given:
11. public interface A111{
12. String s = "yo";
13. public void method1();
14. }
17. interface B{}
20. interface C extends A111, B{
21. public void method1();
22. public void method1(int x);
23. }
What is the result?
A. Compilation succeeds.
B. Compilation fails due to multiple errors.
C. Compilation fails due to an error only on line 20.
D. Compilation fails due to an error only on line 21.
E. Compilation fails due to an error only on line 22.
F. Compilation fails due to an error only on line 12.
答案:A
參考:7-6 介面
-------------------------------------------------------
20. interface C extends A111, B{ //介面c要繼承二介面是合法的

第81題

Given:
1. interface DoStuff2{
2. float getRange(int low, int high);}
3.
4. interface DoMore {
5. float getAvg(int a, int b, int c);}
6.
7. abstract class DoAbstract implements DoStuff2, DoMore{}
8.
9. class DoStuff implements DoStuff2{
10. public float getRange(int x, int y){return 3.14f;}}
11.
12. interface DoAll extends DoMore{
13. float getAvg(int a, int b, int c, int d);}
What is the result?
A. The file will compile without error.
B. Compilation fails. Only line 7 contains an error.
C. Compilation fails. Only line 12 contains an error.
D. Compilation fails. Only line 13 contains an error.
E. Compilation fails. Only lines 7 and 12 contain errors.
F. Compilation fails. Only lines 7 and 13 contain errors.
G. Compilation fails. Lines 7, 12, and 13 contain errors.
答案:A
參考:7-5 抽象類別、7-6 介面
------------------------------------------------------------
7. abstract class DoAbstract implements DoStuff2, DoMore{} //抽象類別實做二個介面但不實做二個方法是沒有關係的

9. class DoStuff implements DoStuff2{
10. public float getRange(int x, int y){return 3.14f;}} //正常類別實做介面的話要把介面實做出來

12. interface DoAll extends DoMore{ //介面繼承介面是沒有問題的
13. float getAvg(int a, int b, int c, int d);} //不是實做第5行,由參數可知

第80題

Given:
3. interface Fish{}
4. class Perch implements Fish{}
5. class Walleye extends Perch{}
6. class Bluegill{}
7. public class Fisherman {
8. public static void main(String[] args) {
9. Fish f = new Walleye();
10. Walleye w = new Walleye()
11. Bluegill b = new Bluegill();
12. if(f instanceof Perch) System.out.print("f-p ");
13. if(w instanceof Fish) System.out.print("w-f ");
14. if(b instanceof Fish) System.out.print("b-f ");
15. }
16. }
What is the result?
A. w-f
B. f-p w-f
C. w-f b-f
D. f-p w-f b-f
E. Compilation fails.
F. An exception is thrown at runtime.
答案:B
參考:7-8 物件的轉型解析
---------------------------------------------------------
考instanceof 的運算符號
12. if(f instanceof Perch) System.out.print("f-p ");
>>9. Fish f = new Walleye();
>>5. class Walleye extends Perch{} //Walleye 和Perch是父子關係故(f instanceof Perch)=true
13. if(w instanceof Fish) System.out.print("w-f ");
>>10. Walleye w = new Walleye()
>>5. class Walleye extends Perch{} //Walleye 和Fish是父子關係
>>4. class Perch implements Fish{} //Walleye 和Fish是父子關係故(w instanceof Fish)=true
14. if(b instanceof Fish) System.out.print("b-f "); //b 和Fish沒任何關係

第79題

Given classes defined in two different files:
1. package packageA;
2. public class Message{
3. String getText(){return "text";}
4. }
And:
1. package packageB;
2. public class XMLMessage extends packageA.Message{
3. String getText(){return "<msg>text</msg> ";}
4. public static void main(String[] args) {
5. System.out.println(new XMLMessage().getText());
6. }
7. }
What is the result of executing XMLMessage.main?
A. text
B. Compilation fails.
C. <msg>text</msg>
D. An exception is thrown at runtime.
答案:C
參考:6-5 繼承、7-3 存取修飾詞的使用

------------------------------------------------------------
5. System.out.println(new XMLMessage().getText());
>>3. String getText(){return "<msg>text</msg> ";} //<msg>text</msg>

第78題

A developer is creating a class Book, that needs to access class Paper. The Paper class is deployed in a JAR
named myLib.jar. Which three, taken independently, will allow the developer to use the Paper class while
compiling the Book class? (Choose Three.)

A. The JAR file is located at $JAVA_HOME/jre/classes/myLib.jar.
B. The JAR file is located at $JAVA_HOME/jre/lib/ext/myLib.jar.
C. The JAR file is located at /foo/myLib.jar and a classpath environment variable is set that
includes /foo/myLib.jar/Paper.class.
D. The JAR file is located at /foo/myLib.jar and a classpath environment variable is set that
includes /foo/myLib.jar.
E. The JAR file is located at /foo/myLib.jar and the Book class is compiled using javac -cp
/foo/myLib.jar/Paper Book.java
F. The JAR file is located at /foo/myLib.jar and the Book class is compiled using
javac -d /foo/myLib.jar Book.java
G. The JAR file is located at foo/myLib.jar and the Book class is compiled using javac
-classpath /foo/myLib.jar Book.java
答案:BDG
參考:7-2 編譯Java 專案套件

第77題

Given:
11. public static void main(String[] args) {
12. Object obj = new int{1, 2, 3};
13. int[] someArray = (int[])obj;
14. for (int i: someArray) System.out.print(i + " ");
15. }
What is the result?
A. 1 2 3
B. Compilation fails because of an error in line 12.
C. Compilation fails because of an error in line 13.
D. Compilation fails because of an error in line 14.
E. A ClassCastException is thrown at runtime.
答案:A
參考:7-8 物件的轉型

------------------------------

12行 , 陣列是物建的一種所以可以轉型為Object.
13, obj可以強迫轉型為原型int陣列.
14, for each時把someArray列印出來,結果為1 2 3.

第76題

Given:
1. class TestA{
2. public void start(){System.out.println("TestA");}
3. }
4. public class TestB extends TestA{
5. public void start(){System.out.println("TestB");}
6. public static void main(String[] args){
7. ((TestA)new TestB()).start();
8. }
9. }
What is the result?
A. TestA
B. TestB
C. Compilation fails.
D. An exception is thrown at runtime.
答案:B
參考:7-9 多型

--------------------------------------------------------

7. ((TestA)new TestB()).start(); //實體為 TestB, 即使轉型為TestA,實體還是TestB. 所以會呼叫public void start(){System.out.println("TestB");}

第75題

Given:
11. public interface A{ public void m1(); }
13. class B implements A{ }
14. class C implements A{ public void m1(){}}
15. class D implements A{ public void m1(int x){}}
16. abstract class E implements A {}
17. abstract class F implements A { public void m1(){} }
18. abstract class G implements A { public void m1(int x){} }
What is the result?
A. Compilation succeeds.
B. Exactly one class does NOT compile.
C. Exactly two classes do NOT compile.
D. Exactly four classes do NOT compile.
E. Exactly three classes do NOT compile.
答案:C
參考:7-6 介面

----------------------------------------------------------

13. class B implements A{ } // 實作了介面A就必須把A的抽象方法實作出來.
15. class D implements A{ public void m1(int x){}} // m1的參數不同,所以不是實作.

第74題

Which two classes correctly implement both the java.lang.Runnable and the java.lang.Cloneable interfaces?
(Choose two.)
A. public class Session implements Runnable, cloneable {
public void run();
public Object clone();
}
B. public class Session extends Runnable, Cloneable {
public void run(){/* do something */}
public Object clone(){/* make a copy */}
}
C. public class Session implements Runnable, Cloneable {
public void run(){/* do something */}
public Object clone() {/* make a copy */}
}
D. public abstract class Session implements Runnable, Cloneable {
public void run(){/* do something */}
public Object clone(){/* make a copy */}
}
E. public class Session implements Runnable, implements Cloneable {
public void run(){/* do something */}
public Object clone() {/* make a copy */}
}
答案:CD
參考:7-6 介面

--------------------------------------

哪兩個class 正確的實做 java.lang.Runnable 和 java.lang.Cloneable 介面.
Runnable 包含了一個 run() 的 method, Cloneable 有個 clone()的method
A.沒有實作method.
B.錯的關鍵字extends. (針對介面使用 implements)
C: 正確了使用implements的關鍵字 和 實做了 兩個 method, 有大括號 {} 就算實作.
D: 設定為abstract(抽象類別) 就可以實作或者不實作.
E. implements Runnable, implements Cloneable

第73題

Given:
10. interface Data { public void load(); }
11. abstract class Info { public abstract void load(); }
Which class correctly uses the Data interface and Info class?
A. public class Employee extends Info implements Data {
public void load(){ /* do something */ }
}
B. public class Employee implements Info extends Data {
public void load(){ /* do something */ }
}
C. public class Employee extends Info implements Data
public void load(){ /* do something */ }
public void Info.load(){ /* do something */ }
}
D. public class Employee implements Info extends Data {
public void Data.load(){ /* do something */ }
public void load(){ /* do something */ }
}
E. public class Employee implements Info extends Data {
public void load(){ /* do something */ }
public void Info.load(){ /* do something */ }
F. public class Employee extends Info implements Data{
public void Data.load(){ /* do something */ }
public void Info.load(){ /* do something */ }
}
答案:A
參考:7-5 抽象類別、7-6 介面

--------------------------------------------------------

不管繼承抽象類別或實做介面,必須把裡面的抽象方法實做出來.
抽象類別(abstract) 用 extends, 介面(interface) 使用 implements 關鍵字.

第72題

Given:
1. package geometry;
2. public class Hypotenuse {
3. public InnerTriangle it = new InnerTriangle();
4. class InnerTriangle {
5. public int base;
6. public int height;
7. }
8. }
Which statement is true about the class of an object that can reference the variable base?
A. It can be any class.
B. No class has access to base.
C. The class must belong to the geometry package.
D. The class must be a subclass of the class Hypotenuse.
答案:C
參考:7-3 存取修飾詞的使用

-----------------------------------------------

要讀取變數 base,必須使用inner class Inner Triangle, 因 InnerTriangle是 default, 所以必須在一樣的package裡面.

第71題

Given:
1. interface A{public void aMethod();}
2. interface B { public void bMethod(); }
3. interface C extends A, B { public void cMethod(); }
4. class D implements B {
5. public void bMethod(){}
6. }
7. class E extends D implements C {
8. public void aMethod(){}
9. public void bMethod(){}
10. public void cMethod(){}
11. }
What is the result?
A. Compilation fails because of an error in line 3.
B. Compilation fails because of an error in line 7.
C. Compilation fails because of an error in line 9.
D. If you define D e = new E(), then e.bMethod() invokes the version of bMethod() defined in Line 5.
E. If you define D e = (D)(new E()), then e.bMethod() invokes the version of bMethod() defined in Line 5.
F. If you define D e = (D)(new E()), then e.bMethod() invokes the version of bMethod() defined in Line 9.
答案:F
參考:7-9 多型

----------------------------------------------

D e = (D)(new E()) 實體類別是 E, 所以呼叫method時,是看實體類別的method.

2009年2月10日 星期二

第63題

Given:
11. class ClassA{}
12. class ClassB extends ClassA{}
13. class ClassC extends ClassA{}
and:
21. ClassA p0 = new ClassA();
22. ClassB p1 = new ClassB();
23. ClassC p2 = new ClassC();
24. ClassA p3 = new ClassB();
25. ClassA p4 = new ClassC();
Which three are valid? (Choose three.)
A. p0 = p1;
B. p1 = p2,
C. p2 = p4;
D. p2 = (ClassC)p1;
E. p1 = (ClassB)p3;
F. p2 = (ClassC)p4;
答案:AEF
參考:7-9 多型

----------------------------------

A. p0 = p1; //p1 Class B 跟 p0 Class A 有繼承的關係, 父類別po 可以承接 子類別 p1.
E. p1 = (ClassB)p3; // p3 的實體是 Class B,所以可以強迫轉型, p1的實體市 Class B 所以可以承接 實體為class B 的p3
F. p2 = (ClassC)p4; //同上;

第62題

Given:
31. class Foo{
32. public int a = 3;
33. public void addFive(){ a += 5; System.out.print("f "); }
34. }
35. class Bar extends Foo{
36. public int a = 8;
37. public void addFive(){this.a += 5; System.out.print("b ");}
38. }

Invoked with:
Foo f = new Bar();
f.addFive();
System.out.println(f. a);
What is the result?
A. b 3
B. b 8
C. b 13
D. f 3
E. f 8
F. f 13
G. Compilation fails,
H. An exception is thrown at runtime.
答案:A
參考:7-9 多型

-----------------------------------------

f 的實體類型(Bar()) 跟 宣告類型不同 (Foo), 呼叫方法時會呼叫實體類型的方法.
存取屬性時會呼叫宣告類型.
37. public void addFive(){this.a += 5; System.out.print("b ");}
32. public int a = 3;

第61題

Given two files, GrizzlyBear.java and Salmon.java:
1. package animals.mammals;
2.
3. public class GrizzlyBear extends Bear{
4. void hunt() {
5. Salmon s = findSalmon();
6. s.consume();
7. }
8. }
1. package animals.fish;
2.
3. public class Salmon extends Fish {
4. public void consume() { /* do stuff */ }
5. }
If both classes are in the correct directories for their packages, and the Mammal class
correctly defines the findSalmon() method, which change allows this code to compile?
A. add import animals. mammals.*; at line 2 in Salmon.java
B. add import animals.fish.*; at line 2 in GrizzlyBearjava
C. add import animals.fish.Salmon.*; at line 2 in GrizzlyBear.java
D. add import animals. mammals.GrizzlyBear*; at line 2 in Salmon.java
答案:B
參考:7-1 Java 套件

-------------------------------------------------------

5. Salmon s = findSalmon(); 用到了這支魚的方法, 所以要import這個類別

第60題

Given:
1. package com.company.application;
2.
3. public class MainClass{
4. public static void main(String[] args){}
5. }
And MainClass exists in the /apps/com/company/application directory. Assume the CLASSPATH
environment variable is set to "." (current directory).

Which two java commands entered at the command line will run MainClass? (Choose two.)
A. java MainClass if run from the /apps directory
B. java com.company.application.MainClass if run from the /apps directory
C. java -classpath /apps com.company.application.MainClass if run from any directory
D. java-classpath . MainClass if run from the /apps/com/company/application directory
E. java -classpath /apps/com/company/application:. MainClass if run from the /apps directory
F. java com.company.application.MainClass if run from the /apps/com/company/application directory
答案:BC
參考:7-2 編譯Java 專案套件

----------------------------------------------------

MainClass 放置於 /apps/com/company/application 下, CLASSPATH設為 "."代表存取現行目錄(current directory).
B. java com.company.application.MainClass if run from the /apps directory //在外部路徑下指定內部路徑
C. java -classpath /apps com.company.application.MainClass if run from any directory //已指示外部路徑

第59題

Given the following directory structure:

bigProject
¦--source
¦ ¦--Utils.java
¦
¦--classes
¦

And the following command line invocation:
javac –d classes source/Utils.java
Assume the current directory is bigProject, what it the result?
A. If the compile is successful, Utils.class is added to the source directory.
B. The compiler returns an invalid flag error.
C. If the compile is successful, Utils.class is added to the classes directory.
D. If the compile is successful, Utils.class is added to the bigProject directory.
答案:C
參考:7-2 編譯Java 專案套件

-------------------------------------------------------

javac –d classes source/Utils.java , -d 會把編譯成功的java檔放入 -d 後面所指定的目錄

第58題

Given:

10. interface Foo{}
11. class Alpha implements Foo{}
12. class Beta extends Alpha{}
13. class Delta extends Beta{
14. public static void main(String[] args){
15. Beta x = new Beta();
16. //insert code here
17. }
18. }
Which code, inserted at line 16, will cause a java.lang.ClassCastException?
A. Alpha a = x;
B. Foo f = (Delta)x;
C. Foo f = (Alpha)x;
D. Beta b = (Beta)(Alpha)x;
答案:B
參考:7-8 物件的轉型

------------------------------------------------------

B. Foo f = (Delta)x; // x 為 Delta 的 父類別 Beta, 父類別不可強制轉型為子類別.

第57題

Given:
21. class Money{
22. private String country = "Canada";
23. public String getC(){return country;}
24. }
25. class Yen extends Money{
26. public String getC(){return super.country;}
27. }
28. public class Euro extends Money{
29. public String getC(){return super.getC();}
30. public static void main(String[] args){
31. System.out.print(new Yen().getC() + " " + new Euro().getC());
32. }
33. }
What is the result?
A. Canada
B. null Canada
C. Canada null
D. Canada Canada
E. Compilation fails due to an error on line 26.
F. Compilation fails due to an error on line 29.
答案:E
參考:7-3 存取修飾詞的使用

-------------------------------------------------

26. public String getC(){return super.country;} 編譯失敗, 父類別22. private String country = "Canada"; 為private,不開放外部存取.

2009年2月9日 星期一

Open ModelSphere v3.0

網路上收尋到的免費資料庫模組軟體. OpenModelSphere V3.0, 放上 192.168.1.5 分享.

file://192.168.1.5/ssd_data/OpenModelSphereSetup.exe

設定:

  1. 先設定ODBC.
  2. 控制台>系統管理工具>ODBC (沒有ODBC問MURPHY).
  3. 選TAB上的 "系統資料來源名稱".
  4. 新增>IBM DB2 ODBC DRIVER>完成.
  5. 資料名稱來源 : Treasury.
  6. 資料庫別名: Treasury > 確定.
  7. 輸入資料庫使用者和密碼 > 按連接 測試一下,成功後確定,完成ODBC設定.

OMS連線設定:

開啟OMS > 新增一個Project.
  1. TOOL > DATABASE > CONNECT.
  2. New.
  3. Name : (隨便).
  4. Description: (隨便).
  5. Default User: (資料庫User). 例: db2admin.
  6. Default Password: (資料庫密碼).
  7. ODBC : (勾起來). 這時JDBC Driver Class Name 會顯出DriverName, 不勾選則自己輸入. 可按一下TEST測試連線.
  8. Date Source Name: 剛在ODBC設定的名字 (資料名稱來源: Treasury).
  9. Apply (完成) > Select 連線.
Create Tables:
  1. TOOL > DATABASE > Reverse Engineering...
  2. Next > Next > (選擇你要的TABLE) Proceed.
  3. 資料庫TABLES產生.
  4. 剩下自己摸索,有新發現在更新上來,3Q

第70題


Given the fully-qualified class names:
com.foo.bar.Dog
com.foo.bar.blatz.Book
com.bar.Car
com.bar.blatz.Sun
Which graph represents the correct directory structure for a JAR file from which those classes can be used by
the compiler and JVM?

A. JarA
B. JarB
C. JarC
D. JarD
E. JarE
答案:A
參考:7-1 Java套件

第69題

11. public interface Status {
12. /* insert code here */ int MY_VALUE = 10;
13. }
Which three are valid on line 12? (Choose three.)
A. final
B. static
C. native
D. public
E. private
F. abstract
C. protected
答案:ABD
參考:7-6 介面
------------------------------------------------------------------
介面裡的屬性的修飾詞預設會加上public和final,
加了static不會影響

第68題

Given the following six method names:
addListener
addMouseListener
setMouseListener
deleteMouseListener
removeMouseListener
registerMouseListener
How many of these method names follow JavaBean Listener naming rules?

A. 1
B. 2
C. 3
D. 4
E. 5
答案:B
參考:7-4 封裝
------------------------------------------------------------------
符合JavaBean Listener的命名規則
addListener
addMouseListener

第67題

10. abstract public class Employee {
11. protected abstract double getSalesAmount();
12. public double getCommision() {
13. return getSalesAmount() * 0.15;
14. }
15. }
16. class Sales extends Employee {
17. //insert method here
18. }
Which two methods, inserted independently at line 17, correctly complete the Sales class? (Choose two.)

A. double getSalesAmount() { return 1230.45; }
B. public double getSalesAmount() { return 1230.45; }
C. private double getSalesAmount() { return 1230.45; }
D. protected double getSalesAmount() { return 1230.45; }
答案:BD
參考:6-5 繼承、7-5 抽象類別
---------------------------------------------------------------
實做的意思是要改寫一種...
A. double getSalesAmount() { return 1230.45; } //子類別存取修飾詞要大於父類別
C. private double getSalesAmount() { return 1230.45; } //子類別存取修飾詞要大於父類別

第66題

5. class Thingy{ Meter m = new Meter(); }
6. class Component {void go() { System.out.print("c");}}
7. class Meter extends Component {void go() { System.out.print("m"); }}
8.
9. class DeluxeThingy extends Thingy {
10. public static void main(String[] args) {
11. DeluxeThingy dt = new DeluxeThingy();
12. dt.m.go();
13. Thingy t = new DeluxeThingy();
14. t.m.go();
15. }
16. }
Which two are true? (Choose two.)
A. The output is mm.
B. The output is mc.
C. Component is-a Meter.
D. Component has-a Meter.
E. DeluxeThingy is-a Component.
F. DeluxeThingy has-a Component.
答案:AF
參考:6-5 繼承、7-9 多型
-------------------------------------------------------------------------
9. class DeluxeThingy extends Thingy { //DeluxeThingy 是Thingy 的子類別
7. class Meter extends Component {void go() { System.out.print("m"); }} //Meter 是Component 的子類別
12. dt.m.go(); //print m
14. t.m.go(); //print m

9. class DeluxeThingy extends Thingy { 繼承Thingy
5. class Thingy{ Meter m = new Meter(); } Thingy 的屬性有Meter ,有Meter表示有
7. class Meter extends Component {void go() { System.out.print("m"); }} 有Meter表示有component

第65題

Replace two of the Modifiers that appear in the Single class to make the code compile.
Note: Three modifiers will not be used and four modifiers in the code will remain unchanged.

Code
public class Single {
private static Single instance;
public static Single getInstance() {
if (instance == null) instance = create();
return instance;
}
private Single() { }
protected Single create() { return new Single(); }
}
class SingleSub extends Single {
}
Modifiers
final
protected
private
abstract
static

答案:

1.class Single{
2.private static Single instance;
3.public static Single getInstance(){
4.if(instance == null) instance = create();
5.return instance;
6.}
7.
8.protected Single(){}
static Single create(){return new Single();}
9.}
10.class SingleSub extends Single{
11.}

參考:7-3 存取修飾詞的使用、8-2 方法種類與呼叫方式

第64題

Given:
class A {
String name = "A";
String getName() {
return name;
}
String greeting()
{ return "class A"; }
}
class B extends A {
String name = "B";
String greeting()
{ return "class B"; }
}
public class Client {
public static void main( String[] args ) {
A a = new A();
A b = new B();
System.out.println(a.greeting() + "has name" + a.getName());
System.out.println(b.greeting() + "has name" + b.getName());
}
}

Place the names "A" and "B" in the following output Names
class Place here has name Place here
class Place here has name Place here
Names
A B
答案:

class A has name A
class B has name A


參考:7-9 多型
-------------------------------------------------------------------
{ return "class A"; }
return name;
class A has name A
{ return "class B"; }
沒有getName...所以用父類別class B extends A {
String getName() {
return name;}
class B has name A

SCJP考題中的陷阱

SCJP考題中的陷阱
原著 Ajith Kallambella

(1) Two public classes in the same file. (illegal)
 一個source file只能有一個public class

(2) Main method calling a non-static method. (illegal)
 static 不能夠存取非static成員。(程式進入點的main(),是static method)

(3) Methods with the same name as the constructor(s). (這種題常有)
 方法名稱可以跟Constructor和Class名稱相同
 constructor不能有回傳值、也不能夠被繼承

(4) Thread initiation with classes that do not have a run() method. (常考之題)
 繼承自Thread的類別,必須要override Thread class的run()(預設是無
內容)

(5) Local inner classes trying to access non-final vars. (illegal)
 Local inner class 絕對不能夠存取非final的 local var

(6) Case statements with values out of permissible range. (byte,int, short, chat)
 注意「四大金剛」的值的範圍
 範圍:
byte :
char :
short :
int :
double 8 bytes,變精度,不精確 15 位十進制數字精度,有效位數 15~16位
long 8 bytes,大範圍的整數,-9223372036854775808 到 9223372036854775807 (19位)
int 4 bytes,常用的整數,-2147483648 到 +2147483647 (10位)
short 2 bytes,小範圍整數,-32768 到 +32767 (5位)
byte byte, -128~127
(7) Math class being an option for immutable classes !! (totally wrong!)
 Math Class無法改變,也無法覆寫。它的方法是static、final的method

(8) instanceOf is not same as instanceof. (注意O大小寫之分)
 instanceof是用來判斷某物件屬於何種類別物件的運運算元。

(9) Private constructors. (legal)
 Constructor可以用 public、private、protected、(default)修飾

(10) An assignment statement which looks like a comparison.
 比如說if(a=true) [應該是if(a = = true)]
 在Java中, 「= =」比較的回傳值是boolean,所以a = = b = = c這種敘述可能會造成exception,因為 c不一定是boolean value。

(11) System.exit() in try-catch-finally blocks. (finally block不會執行)
 finally block一定會執行,而且會蓋掉前面try / catch block所執行的結果。
 finally block 除非執行前,遇到System.exit(),否則一定會執行。
(12) Order of try-catch-finally blocks matters. (若順序錯的話: error: No try before catch)
 try / catch / finally 這三個block的順序不可顛倒

(13) main() can be declared final. (OK)
 main()當然可以宣告final,因為這樣是overloading 的main()

(14) -0.0 = = 0.0 is true.

(15) A class without abstract methods can still be declared abstract.
 abstract類別可以有已經實作的方法(但是必須至少要有一個abstract method)

(16) RandomAccessFile descends from Object and implements DataInput and DataOutput.

(17) Map does not implement Collection.
 Map 介面並不屬於Collection介面的子介面,更不會實作Collection介面方法

(18) Dictionary is a class, not an interface.

(19) Collection is an Interface where as Collections is a helper class. (這題我倒沒見過,但還真容易看混)
 Collection是集合介面
 Collections 是類別不是介面

(20) Class declarations can come in any order.
 Java 是free style的語言



(21) Forward references to variables gives compiler error.

(22) Multi dimensional arrays can be sparce.
(這句話是說: 多維陣列中子陣列不一定必須有一定個數的元素,比如我們把一個二維陣列看成一個矩陣,那麼行與列中的元素可以不完整,可以不對齊.)

(23) Arrays, whether local or class-level, are always initialized.
 陣列不論是在區域或是類別都必須要初始化(廢話…=.=)

(24) Strings are initialized to null, not 「empty」 String.
 String類別初始化為null,並非為「空的」String(只是尚未賦予reference)

(25) An empty String is NOT the same as a null String.
 String = “” 和 String = null 是不同東西

(26) A declaration cannot be labelled.
 宣告不能夠「標籤」

(27) "continue" must be in a loop(for, do, while). It cannot appear in case constructs.
 continue必須要在loop迴圈(像是for、do、while)內

(28) Primitive array types can never be assigned to each other, eventhough the primitives themselves can be assigned.
 Array of Long Primitives = Array of Integer Primitives 會編譯出錯,但 long
var = int var 是合法的

(29) A constructor can throw any exception.
 建構子不會丟出任何例外

(30) Initilializer blocks are executed in the order of declaration.
 初始區塊的執行順序依照宣告時的順序而定

(31) Instance initializer(s) gets executed ONLY IF the objects are constructed.
 實體的實體化方法只有在物件建立時才會執行

(32) All comparisons involving NaN and a non-Nan would always result false.
 所以牽涉到NaN(not a number)和非NaN的比較運算,一律回傳false

(33) Default type of a numeric literal with a decimal point is double.
成員變數類型 取值
byte 0
short 0
int 0
long 0L
char '\u0000'
float 0.0F
double 0.0D
boolean false
所有參考型別 null

(34) integer (and long ) operations / and % can throw ArithmeticException while float / and % will never, even in case of division by zero.

(35) = = gives compiler error if the operands are cast-incompatible.
 比較運算(==)會編譯出錯的原因常出於不相容的型別轉換

(36) You can never cast objects of sibling classes( sharing the same parent ), even with an explicit cast.
 「兄弟類別」(同一父類別)無法做型別轉換

(37) equals returns false if the object types are different.It does not raise a compiler
error.
 當物件不相同時,equal()會回傳false,這並不會造成編譯錯誤

(38) No inner class can have a static member.(but static inner class can)
 一般Inner Class不能夠宣告有類別成員(static member),但是static inner
class當然可以宣告有類別成員。

(39) File class has NO methods to deal with the contents of the file.(also the existing directory)
(40) InputStream and OutputStream are abstract classes, while DataInput and DataOutput are interfaces.

當然以上這些都是從題目中總結出來的技巧,其實書上也都有,大家還是多看看書噢.
本文章來自於神魂顛倒論壇 http://bbs.flash2u.com.tw
原文網址:http://bbs.flash2u.com.tw/dispbbs_65_17347.html

一些教學的blog 有blogger的教學

http://save-coco.blogspot.com/

第49題

Place code framgmets into position so the output is: The quantity is 420




答案:

public int update(int quantity, int adjust){
quantity = quantity + adjust;
return quantity;
}
public void callUpdate(){
int quant = 100;
quant = update(quant, 320);
System.out.println("The quantity is " + quant);
}

參考:6-2 Java 方法

第47題

Place the Types in one of the Type columns, and the Relationships in the Relationship column, to defineappropriate has-a and is-a relationships:

答案:
Dog is-a Animal
Forest has-a Tree
Rectangle has-a Side
Java Book is-a Programming Book



-----------------------------------
參考:6-5 繼承

第56題

5. class Building{}
6. public class Barn extends Building{
7. public static void main(String[] args){
8. Building build1 = new Building();
9. Barn barn1 = new Barn();
10. Barn barn2 = (Barn)build1;
11. Object obj1 = (Object)build1;
12. String str1 = (String)build1;
13. Building build2 = (Building)barn1;
14. }
15. }
Which is true?
A. if line 10 is removed, the compilation succeeds.
B. if line 11 is removed, the compilation succeeds.
C. if line 12 is removed, the compilation succeeds.
D. if line 13 is removed, the compilation succeeds.
E. More than one line must be removed for compilation to succeed.
答案:C
參考:7-8 物件的轉型
------------------------------------------------------------------
8. Building build1 = new Building();
12. String str1 = (String)build1;
//build1 和String 沒有任何繼承關係...

第55題

11. abstract class Vehicle{public int speed(){return 0;}}
12. class Car extends Vehicle{public int speed(){return 60;}}
13. class RaceCar extends Car{public int speed(){return 150;}}
...
21. RaceCar racer = new RaceCar();
22. Car car = new RaceCar();
23. Vehicle vehicle = new RaceCar();
24. System.out.println(racer.speed() + ", " + car.speed()
25. + ", " + vehicle.speed());
What is the result?
A. 0, 0, 0
B. 150, 60, 0
C. Compilation fails.
D. 150, 150, 150
E. An exception is thrown at runtime.
答案:D
參考:7-9 多型
-------------------------------------------------------------
21. RaceCar racer = new RaceCar();
22. Car car = new RaceCar();
23. Vehicle vehicle = new RaceCar();

//racer ,car ,vehicle 實體皆為RaceCar
24. System.out.println(racer.speed() + ", " + car.speed()
25. + ", " + vehicle.speed());
//皆call 13. class RaceCar extends Car{public int speed(){return 150;}}
都回傳150

第54題

1. package test;
2.
3. class Target{
4. public String name = "hello";
5. }
What can directly access and change the value of the variable name?
A. any class
B. only the Target class
C. any class in the test package
D. any class that extends Target
答案:C
參考:7-3 存取修飾詞的使用
-------------------------------------------------------------------
誰可存取name這一個變數?
C. any class in the test package

第53題

Insert six modifiers into the code such that it meets all of these requirements:
1. It must be possible to create instances of Alpha and Beta from outside the packages in which
they are defined.
2. When an object of type Alpha (or any potential subclass of Alpha) has been created, the
instance variable alpha may never be changed.
3. The value of the instance variable alpha must always be "A" for objects of type Alpha.

Code
package alpha;
Place here class Alpha{
Place here String alpha;
Place here Alpha(String a){alpha = a;}
Place here Alpha(){this("A"); }
}
package beta;
Place here class Beta extends alpha.Alpha{
Place here Beta(String a){super(a);}
}

Modifiers
private
protected
public
答案:

package alpha;
public class Alpha{
private String alpha;
public Alpha(){this("A");}
protected Alpha(String a){alpha = a;}
}
package beta;

public class Beta extends alpha.Alpha{
public Beta(String a){super(a);}
}
參考:6-5 繼承、7-3 存取修飾詞的使用
-------------------------------------------------
1. It must be possible to create instances of Alpha and Beta from outside the packages in which
they are defined.
//套件外部要能建立Alpha and Beta 類別的物件,代表Alpha and Beta的存取修飾詞的類別
要為public 且 Beta的建構式要為public
2. When an object of type Alpha (or any potential subclass of Alpha) has been created, the

instance variable alpha may never be changed.
//如果要建立Alpha 物件或Alpha 子類別的物件,則實體變數Alpha 不能改變,表示Alpha 的值不能被外部改變,因此要宣告成private 只能開放讓建構式存取,因此建構式要定為protected
3. The value of the instance variable alpha must always be "A" for objects of type Alpha.
要建立alpha 物件且實體變數alpha 值要恆為A,也就是說Alpha(){this("A");} 這一個建構式要開放給外部存取

第48題

Given:
1. public class Venus{
2. public static void main(String[] args){
3. int[] x = {1, 2, 3};
4. int y[] = {4, 5, 6};
5. new Venus().go(x, y);
6. }
7. void go(int[]... z){
8. for(int[] a : z)
9. System.out.print(a[0]);
10. }
11. }
What is the result?
A. 1
B. 12
C. 14
D. 123
E. Compilation fails.
F. An exception is thrown at runtime.
答案:C
參考:5-1 陣列基本概念、6-2 Java 方法

---------------------------------------------

5. new Venus().go(x, y);
>7. void go(int[]... z){ //z has int[] x = {1, 2, 3}; int y[] = {4, 5, 6};
>8. for(int[] a : z) //for each z, x array in first loop, y array in second loop.
>9. System.out.print(a[0]); //output 1 (x[0]) then output 4 (y[0]).

第52題

Place the code fragments in position to complete the Displayable interface.

interface Reloadable{
public void reload();
}
class Edit{
public void edit(){/* Edit Here */}
}
interface Displayable
Place here Place here{
Place here
}
Code Fragments
extends
public void display();
Reloadable
implements
public void display(){/* Diaplay */}
Edit

答案:

interface Displayable
extends Reloadable{
public void display();
}
參考:6-5 繼承、7-6 介面
---------------------------------------
主要考介面的觀念
Displayable 是一個介面,介面只能繼承介面,繼承父介面後可以自己建立一個新的方法

第46題

Given:
10. public class Pizza{
11. ArrayList toppings;
12.
13. public final void addTopping(String topping){
14. toppings.add(topping);
15. }
16.
17. public void removeTopping(String topping){
18. toppings.remove(topping);
19. }
20. }
And:
30. class PepperoniPizza extends Pizza{
31. public void addTopping(String topping){
32. System.out.println("Cannot add Toppings");
33. }
34.
35. public void removeTopping(String topping){
36. System.out.println("Cannot remove pepperoni");
37. }
38. }
And:
50. Pizza pizza = new PepperoniPizza();
51. pizza.addTopping("Mushrooms");
52. pizza.removeTopping("Pepperoni");

What is the result?
A. Compilation fails.
B. Cannot add Toppings
C. The code runs with no output.
D. A NullPointerException is thrown in Line 4.
答案:A
參考:6-5 繼承

-------------------------------------------------

31. public void addTopping(String topping) , try to override
13. public final void addTopping(String topping), which cannot be override coz of final

第51題

1. public interface A{
2. public void doSomething(String thing);
3. }
1. public class AImpl implements A{
2. public void doSomething(String msg){}
3. }
1. public class B{
2. public A doit(){
3. //more code here
4. }
5.
6. public String execute(){
7. //more code here
8. }
9. }
1. public class C extends B{
2. public AImpl doit(){
3. //more code here
4. }
5.
6. public Object execute(){
7. //more code here
8. }
9. }
Which statement is true about the classes and interfaces?
A. Compilation will succeed for all classes and interfaces.
B. Compilation of class C will fail because of an error in line 2.
C. Compilation of class C will fail because of an error in line 6.
D. Compilation of class AImpl will fail because of an error in line 2.
答案:C
參考:6-5 繼承、7-6 介面
--------------------------------------------------------
6. public Object execute(){ 試圖要實做
6. public String execute(){ 但是回傳型別不同...

第50題

1. public abstract class Shape{
2. private int x;
3. private int y;
4. public abstract void draw();
5. public void setAnchor(int x, int y){
6. this.x = x;
7. this.y = y;
8. }
9. }
Which two classes use the Shape class correctly? (Choose two.)
A. public class Circle implements Shape{
private in radius; }

B. public abstract class Circle extends Shape{
private in radius; }

C.
public class Circle extends Shape{
private in radius;
public void draw(); }

D.
public abstract class Circle implements Shape{
private in radius;
public void draw(); }

E.
public class Circle extends Shape{
private in radius;
public void draw(){/* code here */}
}

F.
public abstract class Circle implements Shape{
private in radius;
public void draw(){/* code here */}
}
答案:BE
參考:6-5 繼承、7-6 介面
--------------------------------------------------------
抽象類別
A. public class Circle implements Shape{ //Circle 是一個類別,類別針對Shape這一個抽象類別要用繼承
C. public class Circle extends Shape{
private in radius;
public void draw(); //Circle 是一個類別,即然繼承Shape了就要實做出來...這沒有實做
D. public abstract class Circle implements Shape{ //類別不能實做類別,而是要繼承
F. public abstract class Circle implements Shape{ //類別不能實做類別,而是要繼承

第45題

Given that:

Gadget has-a Sprocket and
Gadget has-a Spring and
Gadget is-a Widget and
Widget has-a Sprocket

Which two code fragments represent these relationships? (Choose two.)

A. class Widget{Sprocket s;}
class Gadget extends Widget{Spring s;}
B. class Widget{}
class Gadget extends Widget{Spring s1; Sprocket s2;}
C. class Widget{Sprocket s1; Spring s2;}
class Gadget extends Widget{}
D. class Gadget{Spring s;}
class Widget extends Gadget{Sprocket s;}
E. class Gadget{}
class Widget extends Gadget{Sprocket s1; Spring s2;}
F. class Gadget{Spring s1; Sprocket s2;}
class Widget extends Gadget{}
答案:AC
參考:6-5 繼承

-------------------------------------------------

A: class Widget{Sprocket s;} //Widget has-a Sprocket
class Gadget extends Widget{Spring s;} //Gadget has-a Spring, also extend Sprocket from Widget, so Gadget is-a Widget and Gadget has-a Sprocket.

C. class Widget{Sprocket s1; Spring s2;} //Widget has-a Sprocket
class Gadget extends Widget{} //Gadget extend both Sprocket and Spring from Widget,
so Gadget has-a Sprocket and Gadget has-a Spring and Gadget is-a Widget.

第44題

Given:
1. class Employee{
2. String name; double baseSalary;
3. public Employee(String name, double baseSalary){
4. this.name = name;
5. this.baseSalary = baseSalary;
6. }
7. }
8. public class SalesPerson extends Employee{
9. double commission;
10. public SalesPerson(String name,
11. double baseSalary, double commission){
12. //insert code here
13. }
14. }

Which two code fragments, inserted independently at line 12, will compile? (Choose two.)
A. super(name, baseSalary);
B. this.commission = commission;
C. super();
this.commission = commission;
D. this.commission = commission;
super();
E. super(name, baseSalary);
this.commission = commission;
F. this.commission = commission;
super(name, baseSalary);
G. super(name, baseSalary, commission);
答案:AE
參考:6-5 繼承

------------------------------------------------------

B. this.commission = commission; //父類別沒有預設建構式,編譯失敗
C. super(); //父類別沒有預設建構式,編譯失敗
this.commission = commission;
D. this.commission = commission; //呼叫建構式寫法必須放在第一行
super();
E. super(name, baseSalary);
this.commission = commission;
F. this.commission = commission; //呼叫建構式寫法必須放在第一行 super(name, baseSalary); G. super(name, baseSalary, commission); //父類別沒有三個參數的建構式

第43題

Given:
1. class Plant{
2. private String name;
3. public Plant(String name){this.name = name;}
4. public String getName(){return name;}
5. }
6. public class Tree extends Plant{
7. public void growFruit(){}
8. public void dropLeaves(){}
9. }

What statement is true?
A. The code will compile without changes.
B. The code will compile if public Tree(){Plant();} is added to the Tree class.
C. The code will compile if public Plant(){Tree();} is added to the Plant class.
D. The code will compile if public Plant(){this("fern");} is added to the Plant class.
E. The code will compile if public Plant(){Plant("fern");} is added to the Plant class.
答案:D
參考:6-5 繼承

---------------------------------------------------

class Tree 裡面沒有建構式,所以預設super();
但class Plant裡面沒有 Plant()的建構子, 所以加入一行 this("fern") 去呼叫Plant(String name)