Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multi-D Arrays java se7

 
Objsooj Ram
Greenhorn
Posts: 9
Java Ruby
  • Mark post as helpful
  • send pies
  • 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!
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • 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
Java Ruby
  • Mark post as helpful
  • send pies
  • 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.

 
Campbell Ritchie
Sheriff
Pie
Posts: 49760
69
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic