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.
Array
Moderator: admin
-
- Site Admin
- Posts: 10043
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Array
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.
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.
-
- Posts: 33
- Joined: Tue Jan 09, 2018 2:12 am
- Contact:
Re: Array
thank you
Who is online
Users browsing this forum: No registered users and 38 guests