SUN認證Java2程式設計師考試(SCJP) 試題解析(2)

which of the following lines of code will compile without error?
a.
int i=0;
if (i) {
system.out.println(“hi”);
}
b.
boolean b=true;
boolean b2=true;
if(b==b2) {
system.out.println(“so true”);
}
c.
int i=1;
int j=2;
if(i==1|| j==2)
system.out.println(“ok”);
d.
int i=1;
int j=2;
if (i==1 &| j==2)
system.out.println(“ok”);
解答:b, c
點評:選項a錯,因為if語句後需要一個boolean類型的表達式。邏輯操作有^、&、| 和 &&、||,但是“&|”是非法的,所以選項d不正確。

例題5:
which two demonstrate a "has a" relationship? (choose two)
a. public interface person { }
public class employee extends person{ }
b. public interface shape { }
public interface rectandle extends shape { }
c. public interface colorable { }
public class shape implements colorable
{ }
d. public class species{ }
public class animal{private species species;}
e. interface component{ }
class container implements component{
private component[] children;
}
解答:d, e
點評: 在java中代碼重用有兩種可能的方式,即組合(“has a”關係)和繼承(“is a”關係)。“has a”關係是通過定義類的屬性的方式實現的;而“is a”關係是通過類繼承實現的。本例中選項a、b、c體現了“is a”關係;選項d、e體現了“has a”關係。

例題6:
which two statements are true for the class java.util.treeset? (choose two)
a. the elements in the collection are ordered.
b. the collection is guaranteed to be immutable.
c. the elements in the collection are guaranteed to be unique.
d. the elements in the collection are accessed using a unique key.

e. the elements in the collection are guaranteed to be synchronized
解答:a, c
點評:treeset類實現了set接口。set的特點是其中的元素惟一,選項c正確。由於採用了樹形存儲方式,將元素有序地組織起來,所以選項a也正確。

例題7:
true or false: readers have methods that can read and return floats and doubles.
a. ture
b. false
解答:b
點評: reader/writer只處理unicode字元的輸入輸出。float和double可以通過stream進行i/o.

例題8:
what does the following paint() method draw?
1. public void paint(graphics g) {
2. g.drawstring(“any question”, 10, 0);
3. }
a. the string “any question?”, with its top-left corner at 10,0
b. a little squiggle coming down from the top of the ;component.
解答:b
點評:drawstring(string str, int x, int y)方法是使用當前的顏色和字元,將str的內容顯示出來,並且最左的字元的基線從(x,y)開始。在本題中,y=0,所以基線位於最頂端。我們只能看到下行字母的一部分,即字母‘y’、‘q’的下半部分。