Reputation: 847
public static void main(String[] args)
{
int [][]shatner = new int[1][1];
int []rat = new int[4];
shatner[0] = rat;
System.out.println(shatner[0][3]);
}
surprised, The output is 0, why Java doesn't check this kind of indexOutOfBound error?
Upvotes: 3
Views: 232
Reputation: 346260
Where do you see an "indexOutOfBound error"? The code does the following:
int
arrays (size 1), i.e. a 2D array, contents are intialized with 0int
, size 4, content is intialized with 0Upvotes: 5
Reputation: 77995
Arrays need not be rectangular in Java. This is a jagged array and is perfectly fine.
Upvotes: 0
Reputation: 4033
I'm thinking it's because java's arrays are working a bit differently than expected. You initialize shatner
to [1][1], meaning something like, {{0},{0}}
in memory.
However, you then assign an integer to the first element, turning it into {{0,0,0,0},{0}}
in memory, so Java is addressing the newly assigned index.
Upvotes: 0
Reputation: 14766
It's not that Java doesn't check the IndexOutOfBoundsException. It's that the answer SHOULD be zero. The key line is
shatner[0] = rat;
Since that means that the 0th index of shatner
is pointing to an array of length 4, shatner[0][4]
is totally valid.
Upvotes: 3
Reputation: 62027
There is no index out of bounds error. shatner is an array of arrays. You replaced the first array of length one with a new one of length four. So now shatner[0][3] is a perfectly legit place in memory.
Upvotes: 3
Reputation: 597016
There is nothing going out of bounds.
The 0th row in the shatner
array gets reinitialized to int[4]
.
Upvotes: 4
Reputation: 16220
Don't be surprised. shatner[0] is an array (rat) and happens to be of length 4. So shartner[0][3] is rat[3] which happens to be 0..
Upvotes: 6