Array
Posted: Mon Feb 19, 2018 2:30 pm
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.
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.