• Post Reply Bookmark Topic Watch Topic
  • New Topic

Int Array  RSS feed

 
Ryan Waggoner
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was playing the round up game and came across this question.

Something along the lines of, is this valid...

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

I did not think that it would compile, but after getting wrong and trying it out I found that it works. So my question is why do both of these work...


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

I would not think that java would look at the name of the int to determine whether or not it was an array. Anyone have some explanations to why java does this?

Thanks
 
Roger F. Gay
Ranch Hand
Posts: 408
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ryan Waggoner:

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


The java compiler accepts both type[] name and type name[] as having the same meaning.
 
Ryan Waggoner
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to make things easier, or make everyone happy?

Or is there a better reason?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think to make the transition from other languages (C/C++) easier. The "int[] myIntArray" form is more common in Java, so it improves the odds that future readers will figger it out quickly.
 
Roger F. Gay
Ranch Hand
Posts: 408
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ryan Waggoner:
Just to make things easier, or make everyone happy?

Or is there a better reason?


We might be speculating about what was on the minds of the compiler developers; but I think I've read somewhere that aiding the transition from other languages was involved in the decision - like Stan said.

The only other possible "better reason" I can think of is that no one has thought of a useful alternative interpretation. int[] describes type int array very nicely. int myArray[] says I want myArray to be an array of type int. Both are logical descriptions of the same thing, and it seems like it could be obscure to interpret either as something else.

Of course if you think of an alternative interpretation that would be very, very useful, you might want to promote a change request for the language.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!