# 배열의 길이와 초기화

## 배열의 길이

> ### <mark style="color:blue;">`배열이름.length`</mark>&#x20;
>
> * 배열의 길이 : int 타입 상수
> * <mark style="color:blue;">`int[] arr = new int[5];`</mark>  : 배열의 길이가 5인 int 배열
> * <mark style="color:blue;">`int len = arr.length;`</mark>       : <mark style="color:blue;">arr.length</mark> 의 값은 5이고 len 변수에 저장된다.
>
> ### <mark style="color:blue;">배열은 한번 생성되면 컴파일 후 실행되는 동안은 그 길이(크기)를 바꿀 수 없습니다.</mark>

## 배열의 한계점

### 배열의 크기를 바꿀 수 없는 이유?

* <mark style="color:blue;">`new int[5];`</mark>로 배열을 생성하면 int 가 4byte 이기 때문에\
  총 20byte 를 저장하기 위한 <mark style="color:blue;">연속적인 메모리 공간</mark>을 찾습니다.
* <mark style="color:blue;">연속적인 공간을 찾아서 주소를 배정</mark>합니다.
* 배정이 끝난 후 크기를 5가 아닌 10으로 늘려야 한다고 가정해 봤을 때\
  배정받은 주소 뒤에 20byte 를 추가적으로 배정해야 하는데 뒤에 연속적인 메모리 공간이 존재한다는 보장이 없습니다.
* 따라서 크기를 바꿀 수 없습니다.

### 배열의 크기가 부족할 때의 방법

* 필요한 만큼의 크기의 배열을 새롭게 만듭니다.

* <mark style="color:blue;">새로 만든 배열에 기존 배열의 값을 복사</mark>해서 저장합니다.

* 아래 예제코드로 학습해 보겠습니다.

{% code lineNumbers="true" %}

```java
class Arrays2_1 {
    public static void main(String[] args) {
        int[] arr = new int[10];
        System.out.println("배열의 길이 = " + arr.length);

        for (int i = 0; i < arr.length; i++) {
            System.out.println("arr[" + i + "] = " + arr[i]);
        }
        System.out.println();
        // index 범위를 벗어나는 경우 Error 발생
        for (int i = 0; i < arr.length + 1; i++) {
            System.out.println("arr[" + i + "] = " + arr[i]);
        }
    }
}
```

{% endcode %}

## 배열의 초기화

> ### 배열의 각 요소에 처음으로 값을 저장하는 것을 의미합니다.

### 자동 초기화

|          자료형(변수 타입)          |    기본값   |
| :--------------------------: | :------: |
|             byte             |     0    |
|             short            |     0    |
|              int             |     0    |
|             long             |    0L    |
|             float            |   0.0f   |
|            double            |   0.0d   |
|             char             | '\n0000' |
|            boolean           |   false  |
| 참조형 변수(String or any Object) |   null   |

* 배열은 기본적으로 저장 하려는 값의 <mark style="color:blue;">타입의 기본값</mark>으로 <mark style="color:blue;">자동 초기화</mark> 해줍니다.

### 초기화 방법

1. <mark style="color:blue;">`int[] num = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};`</mark>
2. <mark style="color:blue;">`int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9};`</mark>&#x20;
   * <mark style="color:blue;">new int\[]</mark> 를 <mark style="color:blue;">생략</mark>할 수 있습니다.

* 아래 예제코드로 학습해 보겠습니다.

{% code lineNumbers="true" %}

```java
class Arrays2_2 {
    public static void main(String[] args) {
        int[] num1 = new int[]{1,2,3,4,5,6,7,8,9};
        int[] num2 = {1,2,3,4,5,6,7,8,9};

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

        System.out.println();
        
        // 주의 할 점!
        int[] num3;
        // num3 = {1,2,3,4,5,6,7,8,9}; // Error 발생합니다.

        // 위처럼 나눠서 표현을 해야 한다면 아래처럼 초기화 하셔야 합니다.
        int[] num4;
        num4 = new int[]{1,2,3,4,5,6,7,8,9};

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

{% endcode %}

{% hint style="info" %}
Ref. Java의 정석 기초편 Chapter5(4, 5)

Ref. [길이와 초기화](https://www.youtube.com/watch?v=r9m2jvElcNc\&list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp\&index=41)
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nbcamp.gitbook.io/java-handbook/part-04./undefined.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
