• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Multi-D Arrays java se7

 
Greenhorn
Posts: 9
Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
 
Bartender
Posts: 825
5
Python Ruby Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Objsooj Ram
Greenhorn
Posts: 9
Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Kemal;

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

 
Marshal
Posts: 79180
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic