aspose file tools*
The moose likes Features new in Java 7 and the fly likes Multi-D Arrays java se7 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Features new in Java 7
Bookmark "Multi-D Arrays java se7" Watch "Multi-D Arrays java se7" New topic
Author

Multi-D Arrays java se7

Objsooj Ram
Greenhorn

Joined: Oct 23, 2012
Posts: 9

Hi
I am stuck on a logic in multidimensional arrays in SE 7. Can someone help me understand why the first Eg. throws a ton of errors while the second one which IMO is similar, works fine.
=====Eg1==================

int[][] arr;
arr = new int[2][2];
arr = {{1,2},{3,4}};

=====Eg2==================
int[][] arr = {{1,2},{3,4}};


Thanks!
Kemal Sokolovic
Bartender

Joined: Jun 19, 2010
Posts: 825
    
    5

Welcome to the Ranch!

What you are refering to is an array literal, and the first one is not a valid form of it because array literal works only when you are declaring a variable of array type.

Where you also might find array literal useful is when, for example, you want to pass an array to a method, but don't want to assign it to a specific variable since that's the only place you need it:


JLS probably contains some more detailed information on the topic, but this is basically it.
Also, this is not a characteristic of Java 7, since array literals were introduced a long time ago.


The quieter you are, the more you are able to hear.
Objsooj Ram
Greenhorn

Joined: Oct 23, 2012
Posts: 9

Thanks Kemal;

So is it just a syntax constraint?
I was merely practicing multi-D arrays and stumbled upon it.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39884
    
  28
That is a feature of the grammar which has been there for as long as I can remember.
You need to look up declarations and array initialisers in the Java Language Specification (JLS). If you are lucky, you will see part of the grammar there. It has always been the case that a declaration permits you to miss out new Foo[] from the initialiser.
I think I have linked to the correct parts of the JLS, but am not absolutely certain.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Multi-D Arrays java se7