Java Programming - Language Fundamentals - Discussion

Discussion Forum : Language Fundamentals - General Questions (Q.No. 3)
3.
Which will legally declare, construct, and initialize an array?
int [] myList = {"1", "2", "3"};
int [] myList = (5, 8, 2);
int myList [] [] = {4,9,7,0};
int myList [] = {4, 3, 7};
Answer: Option
Explanation:

The only legal array declaration and assignment statement is Option D

Option A is wrong because it initializes an int array with String literals.

Option B is wrong because it use something other than curly braces for the initialization.

Option C is wrong because it provides initial values for only one dimension, although the declared array is a two-dimensional array.

Discussion:
18 comments Page 1 of 2.

Hasan said:   8 years ago
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
(
Note :\' The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

So we can say that D is correct.
(3)

Mohammadi said:   8 years ago
@Sonee Gupta.

I agree with your answer. That's the right method.
(1)

Aslam said:   9 years ago
Frustrated with your answers, is it a correct syntax for array declaration and initialization. Completely wrong I thought. My known declaration is:

DataType [] ReferenceVariable = {Elements Separated by Comma}
(2)

Deep Vakharia said:   9 years ago
@Puru.

C is Incorrect because 2d Array is not being initialized as the way they have give.

Puru said:   10 years ago
I don't understand why C is incorrect?

Zany said:   10 years ago
int ar[][] = {{1,2,3},{3,4,5}}; is 2d array initialization.

Pooja said:   1 decade ago
@Sonee Guptha.

int ar[2][3]= {1,1,1,2,2,2};

Is this 2d? 2d requires double braces right?
(1)

Khushbu ahuja said:   1 decade ago
I think option D should be correct as,

int a[3][3] = {1,2,3,4}

Than by default all other elements will be null.
(1)

Sonee gupta said:   1 decade ago
2-d initialisation of array:

int ar[2][3]={1,1,1,2,2,2};

or

int ar[][]={{1,2,3},{3,4,5}};

or

int ar[][]={
{1,2,3},
{2,3,4}
};

Arun said:   1 decade ago
Above option(C) would have been correct, if we had declared it this way.

int myList [] [] = {{4,9,7,0}};

One more opening and closing curly braces would be required for 2 dimensional array.
(1)


Post your comments here:

Your comments will be displayed after verification.