Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

배열의 길이와 인덱스 본문

Java/JAVA1

배열의 길이와 인덱스

빌드이너프 2023. 5. 19. 20:02

배열의 길이

배열은 한 번 생성하면 그 길이를 바꿀 수 없다

 

 

배열이름.length - 배열의 길이(int형 상수)

숫자로 안하고 length 사용하는 이유(배열과 출력이 맞지 않을 경우 에러 발생)

public class practice {
    public static void main(String[] args) {
        int[] score = new int[5]; // 길이가 5인 int 배열 score

        for (int i = 0; i < 6; i++) {
            System.out.println(score[i]);
        }
    }
}

0
0
0
0
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
	at practice.main(practice.java:6)

Process finished with exit code 1

 

length 사용

public class practice {
    public static void main(String[] args) {
        int[] score = new int[5]; // 길이가 5인 int 배열 score

        for (int i = 0; i < score.length; i++) {
            System.out.println(score[i]);
        }
    }
}

0
0
0
0
0

 

변경에 유리함

public class practice {
    public static void main(String[] args) {
        int[] score = new int[8]; // 길이가 8인 int 배열 score

        for (int i = 0; i < score.length; i++) {
            System.out.println(score[i]);
        }
    }
}

0
0
0
0
0
0
0
0

'Java > JAVA1' 카테고리의 다른 글

배열의 출력  (0) 2023.05.19
배열의 초기화  (0) 2023.05.19
배열의 선언과 생성  (0) 2023.05.19
이름 붙은 반복문  (0) 2023.05.19
continue 문  (0) 2023.05.18