Java Programming - Language Fundamentals - Discussion

Discussion Forum : Language Fundamentals - General Questions (Q.No. 6)
6.
Which three are legal array declarations?
  1. int [] myScores [];
  2. char [] myChars;
  3. int [6] myScores;
  4. Dog myDogs [];
  5. Dog myDogs [7];
1, 2, 4
2, 4, 5
2, 3, 4
All are correct.
Answer: Option
Explanation:

(1), (2), and (4) are legal array declarations. With an array declaration, you can place the brackets to the right or left of the identifier. Option A looks strange, but it's perfectly legal to split the brackets in a multidimensional array, and place them on both sides of the identifier. Although coding this way would only annoy your fellow programmers, for the exam, you need to know it's legal.

(3) and (5) are wrong because you can't declare an array with a size. The size is only needed when the array is actually instantiated (and the JVM needs to know how much space to allocate for the array, based on the type of array and the size).

Discussion:
39 comments Page 3 of 4.

Nidhin said:   1 decade ago
Please explain in detail why 4 & 5 are wrong.

Guru said:   1 decade ago
4 is not correct you can verify by making program and declare like this.

Govardhan said:   1 decade ago
Even option 4 is wrong it gives compilation error saying that Dog can not resolve array type.

Bharathraj said:   1 decade ago
Why 5 option is wrong?

Raushan said:   1 decade ago
Why 4th option is wrong ? Explain.

Federer said:   1 decade ago
Memory is not allocated at the time of declaration.
Eg: int[10] arr; -- not allowed.

Instead we can use new while using array size
Therefore int[] arr= new int[0]; is valid.

Avinash said:   1 decade ago
1st is correct because in 2D or multi dimensional array, we can place the square bracket like this.

Rajendra Verma said:   1 decade ago
Why first is correct ? int [] myScores [];

Vinoth.g said:   1 decade ago
int [][]arr = new [2][2];
int []arr[] = new [2][2];
int arr[][] = new [2][2];
int var[][] = new int [][]{{1,2},{3,4}};

Sonia said:   1 decade ago
You can specify the range of subscripts in an array with the
notation start:finish. For example, the declaration:
array income{1997:2000} in1 - in4;
would allow you to refer to income{1997}, income{1998}, etc.
The functions lbound and hbound will return the lowest and
highest indices de ned for an array.


Post your comments here:

Your comments will be displayed after verification.