본문 바로가기
IT/JAVA

[Error] [JAVA] Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

by 뷰IGHT 2019. 2. 28.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 숫자

자바에서 위와같이 에러가 나는 경우는 선언되있는 배열의 크기보다 작거나 클 때 나오는 에러이다. 
예를들어 다음소스처럼 test라는 배열의 크기를 3으로 지정을 했으면 (0부터 2까지만 가져올 수 있는데) 4번째에 value를 1로 선언하려고 하니까 다음과 같이 에러가 난다.

public class Excercide5_7 {

    public static void main(String[] args) {
        
        int[] test = new int[3];
        test[4] = 1;
    }
}

만약 0, 1, 2 중에 하나를 입력한 다음 선언하려고하면 에러가 나지 않는다.

출처: https://88240.tistory.com/437 [shaking blog]