This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question from - danchisholm.net

 
deepu Bhalotia
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MWC212 {
public static void main(String[] args) {
int[] a1[],a2[]; // 1
int []a3,[]a4; // 2
int []a5,a6[]; // 3
int[] a7,a8[]; // 4
}}

This question is given in http://www.danchisholm.net/july21/mybook/chapter4/exam1.html. They tell that the line number-2 will generate a compile time error.

Can anybody explain why line-2 will generate a compile time error. If line-2 makes a compile time error why not line-3..
 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The [] bracket is not allowed after the comma.
 
Joe Sondow
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The [] brackets must come directly AFTER a type or variable name. Either they come directly the after the type, as in
int[] a1;
or they come directly after the variable name, as in
int a1[];
So when you start declaring multiple variables in one statement, the legal places to put the [] include these:
int[] a1[], a2, a3[], a4[][];
The spacing is flexible, so these are fine:
int [] a1 [], a2,a3[],a4[] [];
int []a1, a2,a3 [],a4 [][];

What you CAN'T do is put the brackets directly after a comma:
int[] a1, []a2; // Compiler error: <identifier> expected
 
Parameswaran Thangavel
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi joe

in this case int [] a1 [], a2,a3[],a4[] [];
the actual representation is

a1[][]
a2[]
a3[][]
a4[][]][]

am i correct.... since all the variables are of type int array.
 
Joe Sondow
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paramesanwaran, apart from the extra ] you have in the a4 line, yes, I believe that's correct.
 
yoga eesh
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe,
Apart from the 'an' in paramesanwaran, everythings ok.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic