Forums Register Login

2 dimensional arrays

+Pie Number of slices to send: Send
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...
+Pie Number of slices to send: Send

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

Henry
+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send
 

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.
Arthur, where are your pants? Check under this tiny ad.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 311 times.
Similar Threads
"empty" array declarations
Question on array declaration:
A SCJP exam question (about array variable assign)
multi-dimesional arrays
can't get JTable(vector, vector) constructor to work
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 08:28:41.