Java Programming - Declarations and Access Control - Discussion

Discussion Forum : Declarations and Access Control - General Questions (Q.No. 16)
16.
Which two cause a compiler error?
  1. float[ ] f = new float(3);
  2. float f2[ ] = new float[ ];
  3. float[ ]f1 = new float[3];
  4. float f3[ ] = new float[3];
  5. float f5[ ] = {1.0f, 2.0f, 2.0f};
2, 4
3, 5
4, 5
1, 2
Answer: Option
Explanation:

(1) causes two compiler errors ( '[' expected and illegal start of expression) because the wrong type of bracket is used, ( ) instead of [ ]. The following is the correct syntax: float[ ] f = new float[3];

(2) causes a compiler error ( '{' expected ) because the array constructor does not specify the number of elements in the array. The following is the correct syntax: float f2[ ] = new float[3];

(3), (4), and (5) compile without error.

Discussion:
7 comments Page 1 of 1.

Sris said:   1 decade ago
1 is absolutely wrong, I do agree with that. But 2, I have a confusion that is it compulsory to mention the size? I heard if we won't specify the size it will take the value how many we are going to add to the array. Clarify please.

Nitin said:   1 decade ago
What is the error in 2nd one? Its absolutely correct.

Abhishek said:   10 years ago
I do Agree that 2 will throw compile time error. Because as per Java API. We must have to give no of size of array. Array always work on fixed length.

ANUSHA said:   9 years ago
What is the error in 2nd one? Its absolutely correct, I do Agree that 2 will throw compile time error. Because as per Java API. We must have to give no of size of array. Array always work on fixed length.

Rita said:   9 years ago
Option three shouldn't compile as well. I see no space between float[]f1.

Hasn't anyone noticed it? Please tell me.

Sanjog said:   8 years ago
How will option 5 be compiled?

Hindustan said:   4 years ago
Hi ,
2 nd one won't compile because we do not set size explicitly.

package JAVA_PROGRAMS;

public class immutable
{

public static void main(String[] args)
{
float f5[ ] = {1.0f, 2.0f, 2.0f}; //ok
float[ ]f1 = new float[3];//ok
float f2[ ] = new float[ ]; //invalid
}

}

Post your comments here:

Your comments will be displayed after verification.