Java Programming - Declarations and Access Control - Discussion

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};

[A]. 2, 4
[B]. 3, 5
[C]. 4, 5
[D]. 1, 2

Answer: Option D

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.


Sris said: (Jul 3, 2014)  
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: (Jun 30, 2015)  
What is the error in 2nd one? Its absolutely correct.

Abhishek said: (Dec 5, 2015)  
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: (Aug 23, 2016)  
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: (Nov 16, 2016)  
Option three shouldn't compile as well. I see no space between float[]f1.

Hasn't anyone noticed it? Please tell me.

Sanjog said: (Oct 20, 2017)  
How will option 5 be compiled?

Hindustan said: (Aug 29, 2021)  
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:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.