Java Programming - Declarations and Access Control - Discussion

8. 

Which cause a compiler error?

[A]. int[ ] scores = {3, 5, 7};
[B]. int [ ][ ] scores = {2,7,6}, {9,3,45};
[C]. String cats[ ] = {"Fluffy", "Spot", "Zeus"};
[D]. boolean results[ ] = new boolean [] {true, false, true};
[E]. Integer results[ ] = {new Integer(3), new Integer(5), new Integer(8)};

Answer: Option B

Explanation:

Option B generates a compiler error: <identifier> expected. The compiler thinks you are trying to create two arrays because there are two array initialisers to the right of the equals, whereas your intention was to create one 3 x 3 two-dimensional array.

To correct the problem and make option B compile you need to add an extra pair of curly brackets:

int [ ] [ ] scores = { {2,7,6}, {9,3,45} };


Akash said: (Jul 18, 2013)  
How we can find the error is compile time or run time?

Rajan said: (Jul 21, 2013)  
If your program is compiled successfully without errors then its ok and no compile time error is there. If it gives error when you compile it means the errors are compile time errors.

If your program is compiled successfully without errors but causes some exception during running it means its a run time error.

Yatendra Singh Chauhan said: (Aug 12, 2013)  
boolean results[ ] = new boolean [] {true, false, true};

What is the meaning of this line?

What exactly it perform?

LeitrimDroid said: (Sep 10, 2013)  
Hi Yatendra,

I believe it puts three boolean values in a new array called results, such that

results[0] = true.
results[1] = false.
results[2] = true.

Vinodhini said: (Oct 3, 2013)  
But boolean is just a keyword. So how can we create an object for a keyword! If you say boolean is a wrapper class it should be Boolean and not boolean!

RF Fan said: (Nov 5, 2013)  
@Vinodhini .

Its allocating memory (of course through object creation). And We all know int a[]=new int[2] can be used its nothing but we are allocating an array of values to a (here its 2) then there aint no problem in writing Boolean the same.

boolean a[]= new boolean[2];

Riya said: (Jun 20, 2015)  
Integer results[ ] = {new Integer(3), new Integer(5), new Integer(8)};

How it allocates memory to the variable results?

Cheenu said: (Mar 16, 2016)  
Please explain how last option is correct?

Saurabh Gupta said: (Jun 7, 2017)  
I too think the last option is wrong.

Saba said: (Jul 5, 2017)  
In the last option it follows like this:

results[0]=new integer(3)
results[1]=new integer(5)
results[2]=new integer(8)

That is each and every element of results[] is also a single dimensional array and as all the elements of result array are even integers hence there will be no error.

Hope you understand.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.