Array

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
ashishrai.kv
Posts: 33
Joined: Tue Jan 09, 2018 2:12 am
Contact:

Array

Post by ashishrai.kv »

Which of the following code fragments will successfully initialize a two-dimensional array of chars named cA with a size such that cA[2][3] refers to a valid element?

1.
char[][] cA = { { 'a', 'b', 'c' }, { 'a', 'b', 'c' } };
2.
char cA[][] = new char[3][];
for (int i=0; i<cA.length; i++) cA = new char[4];
3.
char cA[][] = { new char[ ]{ 'a', 'b', 'c' } , new char[ ]{ 'a', 'b', 'c' } };
4
char cA[3][2] = new char[][] { { 'a', 'b', 'c' }, { 'a', 'b', 'c' } };
5.
char[][] cA = { "1234", "1234", "1234" };

Ans:- 1 and 3 declare a two dimensional array alright but they create the array of size 2, 3. And cA[2][3] means we need an array of
size 3, 4 because the numbering starts from 0.

5.,This is a one dimensional array and that too of strings. Note that a java String is not equivalent to 1 dimensional array of chars.
This leaves us with only one choice 2.


can anyone please explain the above two answers , i am not able to figure it out.

admin
Site Admin
Posts: 10043
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Array

Post by admin »

Remember that array indexing starts with 0, therefore, to access element cA[2][3], cA must refer to an array whose length in the first dimension must be at least 3 and in the second dimension must be at least 4.

Options 1 and 3 declare a two dimensional array correctly but they create the dimensions of the array that they create are [2][3]. Thus, trying to access cA[2] will cause an ArrayIndexOutOfBoundsException.

Option 5 is a one dimensional array. So you cannot access cA[2][3] in this array.
If you like our products and services, please help us by posting your review here.

ashishrai.kv
Posts: 33
Joined: Tue Jan 09, 2018 2:12 am
Contact:

Re: Array

Post by ashishrai.kv »

thank you :)

Post Reply

Who is online

Users browsing this forum: No registered users and 34 guests