[Java] OCP題庫 -Array陣列

Boom
BOOM ⭐ 程式自學之旅
2 min readOct 22, 2020

<排版順序>

題目->答案->個人解題方式->重點整理

【題目】

1.

Which two array initialization statements are valid?

A.int array[3] = new int[] {1, 2, 3};

B.int array[] = new int[] {1,2,3};

C.int array[] = new int[3];

array = {1, 2, 3};

D.int array[] = new int[3] {1, 2, 3};

E.int array[] = new int[3];

array[0] = 1;

array[1] = 2;

array[2] = 3;

2.

Given the code fragment:

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 (String[] c : shirts) {

for (String s : c) {

System.out.print(s + “:”);

}

}

B)

for (int index = 1; index < 2; index++) {

for (int idx = 1; idx < 2; idx++) {

System.out.print(shirts[index][idx] + “:”);

}

}

C)

for (int index = 0; index < 2; ++index) {

for (int idx = 0; idx < index; ++idx) {

System.out.print(shirts[index][idx] + “:”);

}

}

D)

for (int index = 0; index <= 2;) {

for (int idx = 0; idx <= 2;) {

System.out.print(shirts[index][idx] + “:”);

}

index++;

}

3.

Given:public class Test {public static void main(String[] args) {String[][] chs = new String[5][2];chs[0] = new String[2];chs[1] = new String[5];int i = 97;for (int a = 0; a < chs.length; a++) {for (int b = 0; b < chs.length; b++) {chs[a][b] = "" + i;i++;}}for (String[] ca : chs) {for (String c : ca) {System.out.print(c + " ");}System.out.println();}}}What is the result?A. NullPointerException is thrown at runtime.//呼叫的變數沒有值B.97 9899 100 null null nullC.97 9899 100 101 102 103D.Compilation fails.E.An ArrayIndexOutOfBoundsException is thrown at runtime.

/////////////////////////////////

【答案】

1.B.E

2.A

3.E

/////////////////////////////////

【個人解題方式】

主要講解第三題

3.因為空間不夠

chs[0] = new String[2];//chs項下只有2個,chs[0][0]、chs[0][1]chs[1] = new String[5];for (int a = 0; a < chs.length; a++) {for (int b = 0; b < chs.length; b++) {chs[a][b] = "" + i;i++;}}

所以在這段程式碼的時候,會在

chs[0][0]、chs[0][1]、chs[0][2]……chs[0][4]放值進去

可是跑到chs[0][2]的時候,因為沒有宣告這個陣列,所以會跑出沒有陣列空間的Exception。

/////////////////////////////////

如果這篇文章對你幫助、或有任何有問題,歡迎底下留言或拍手讓我知道唷 🐻

--

--

Boom
BOOM ⭐ 程式自學之旅

Boom Engineer | BOOM ⭐ 程式自學之旅 | 透過筆記釋放記憶體,記錄自己的程式筆記,『內化』成為這段旅程的養分,也分享給路過,正在經歷這趟旅程的你 | Java note begin at 2020.09 | Python note begin at 2021.03