chun
chun

Reputation: 847

How does this Java code work?

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

Answers (7)

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

Where do you see an "indexOutOfBound error"? The code does the following:

  • Initalize an array (size 1) of int arrays (size 1), i.e. a 2D array, contents are intialized with 0
  • Initalize a array of int, size 4, content is intialized with 0
  • set the single element of the 2D array to the size 4 1D array
  • access the last element of the first array in the 2D array, which is 0

Upvotes: 5

JRL
JRL

Reputation: 77995

Arrays need not be rectangular in Java. This is a jagged array and is perfectly fine.

Upvotes: 0

Tarka
Tarka

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

justkt
justkt

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

Matt Greer
Matt Greer

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

Bozho
Bozho

Reputation: 597016

There is nothing going out of bounds.

The 0th row in the shatner array gets reinitialized to int[4].

Upvotes: 4

nc3b
nc3b

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

Related Questions