Java Programming - Language Fundamentals - Discussion
Discussion Forum : Language Fundamentals - General Questions (Q.No. 6)
6.
Which three are legal array declarations?
- int [] myScores [];
- char [] myChars;
- int [6] myScores;
- Dog myDogs [];
- Dog myDogs [7];
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 2 of 4.
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}};
int []arr[] = new [2][2];
int arr[][] = new [2][2];
int var[][] = new int [][]{{1,2},{3,4}};
Rajendra Verma said:
1 decade ago
Why first is correct ? int [] myScores [];
Avinash said:
1 decade ago
1st is correct because in 2D or multi dimensional array, we can place the square bracket like this.
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.
Eg: int[10] arr; -- not allowed.
Instead we can use new while using array size
Therefore int[] arr= new int[0]; is valid.
Raushan said:
1 decade ago
Why 4th option is wrong ? Explain.
Bharathraj said:
1 decade ago
Why 5 option is wrong?
Govardhan said:
1 decade ago
Even option 4 is wrong it gives compilation error saying that Dog can not resolve array type.
Guru said:
1 decade ago
4 is not correct you can verify by making program and declare like this.
Nidhin said:
1 decade ago
Please explain in detail why 4 & 5 are wrong.
Akshay Hegde said:
1 decade ago
4 is not wrong because it represents an array of user-defined objects (objects of 'Dog' class). You can try initializing as "Dog myDog[] = new Dog[10];" this will create an array of size ten which can store ten 'Dog' objects in it.
5 is wrong because you can't declare array size during declaration. You can do that only during initialization "Dog myDog[]" is declaration and "new Dog[10]" is initialization.
5 is wrong because you can't declare array size during declaration. You can do that only during initialization "Dog myDog[]" is declaration and "new Dog[10]" is initialization.
(1)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers