• Post Reply Bookmark Topic Watch Topic
  • New Topic

2 dimensional arrays  RSS feed

 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI guys, with this code

I created a 2 dimensional array. Now as I specified only the first dimension, I thought that it meant that in the second dimension I could only specify 2 arrays, like so

meaning that now I have 2 arrays and one contains 3 strings and the other one 2
But it seems like I can continue to declare more arrays in the second dimension like so

and I'm not sure I understand that, I thought I'd get an index out of bound exception because in my initial declaration I said I wanted only 2 arrays...
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

you should get an index out of bounds exception upon running the program. If not, can you provide us a SSCCE?

Henry
 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that's what I thought. OK so I removed the offending lines completely,saved, compiled, then put them back, saved compiled and run the program and now I get the exception. Must have been some kind of glitch, it works the way it should. For a moment I thought I understood absolutely nothing about arrays...glad I was wrong, sorry for the useless post, but I couldn't figure out what was going on and panicked!
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason Attin wrote:. . . now I have 2 arrays and one contains 3 strings and the other one 2
But it seems like I can continue to declare more arrays . . .

and I'm not sure I understand that, I thought I'd get an index out of bound exception because in my initial declaration I said I wanted only 2 arrays...
No, you have three arrays. Remember that despite what people tell you, there is no such thing as a 2D array in Java®. What you have is an array of arrays. You have one array which contains two arrays one of 4 places for Strings and the other with 3 places for Strings,
Where did you say you the error doesn't occur? That code will compile all right because the compiler doesn't keep a record of the size of arrays. Why should it? It believes you know what you are doing. The size of an array is recorded inside the array itself as the length field(←Beware: that link may be difficult to read.) and that is queried at runtime and you can have lots of nice out of bounds exceptions if you try to execute that code. Remember: you never get exceptions at compile time.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!