0

I have a problem in the code below:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone {
    public static void main (String[] args) throws java.lang.Exception {
        int[] map = new int[100 * 100];
        System.out.println("Works : " + map[10 * 100 + 5]);
        System.out.println("Works? : " + map[99 * 100 + 99]);
        System.out.println("Works?! : " + map[20 * 100 + 100]);
        //System.out.println("And this?? : " + map[99 * 100 + 100]);
    }
}

As you can see the last line (the comment) doesn't work; it throws an ArrayIndexOutOfBoundsException.

But I dont get it; it should be in the array's bounds. The array's size is 100*100 so 99 * 100 + 100 = 100*100 so index 100*100 is in the array.

I've already fixed the problem; I would just like to know why I get an exception on the above line.

Link to code: http://ideone.com/ydgU9s

3 Answers 3

4

It throws that exception because the index of an array are from 0 to length -1.

So if you declared it to have a length of 100*100, the indexes are from 0 to 100*100 -1.

And what you tried:

map[99 * 100 + 100]

is equal to

map[100*100]

which cannot be accesed.

Sign up to request clarification or add additional context in comments.

1 Comment

ok too many comments.. yeah that's what i thought, just wanted to be sure, thanks and accepted :D in 9 minutes
1

You are trying to access Map[10000]. Array index starts with 0 , so the array with size 10,000 means 0 to 9999.

Comments

1

Arrays are 0 base indexed.

So you can access the elements in map from index 0 to map.length - 1.

I.e : map[0] to map[100*100-1]

Or 99 * 100 + 100 = 10000 > 9999, that's why you got an IOOBE.

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.