> For the complete documentation index, see [llms.txt](https://leeans-dev-book.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leeans-dev-book.gitbook.io/docs/lecture/java/section2./array.md).

# Array

#### 배열

* 특정 타입의 데이터를 묶음으로 다루기 위해 사용
* 지정된 자료형과 개수만큼 메모리 공간을 나란히 확보
  * ⚠️ 개수의 변경이 불가능함

<table><thead><tr><th width="100">도</th><th width="113">개</th><th width="89">걸</th><th width="102">윷</th><th>모</th></tr></thead><tbody><tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td></tr></tbody></table>

```java
package sec03.chap08;

public class Ex01 {
    public static void main(String[] args) {
        //  💡 사용할 자료형 뒤에 []를 붙여 선언
        char[] yutnori = {'도', '개', '걸', '윷', '모'};
        //char[] yutnori = new char[];
        //  💡 length : 배열의 길이 반환
        int length = yutnori.length;

        //  💡 [] 안에 인덱스 정수를 넣어 접근
        //  ⭐ 0부터 시작
        char first = yutnori[0];
        char last = yutnori[yutnori.length - 1];
    }
}

```

```java
        //  💡 초기화하지 않고 일단 선언하기
        //  ⭐ 어떤 값으로 초기화되는지 확인
        boolean[] boolAry = new boolean[3];
        int[] intAry = new int[3];
        double[] dblAry = new double[3];
        char[] chrAry = new char[3]; // 아래 확인
        String[] strAry = new String[3];

        //  아스키 코드의 0번 글자. 문자열의 끝을 표시하는데 사용
        char NUL = chrAry[0];

```

<pre class="language-java"><code class="lang-java"><strong>        //  다음과 같이 원하는 위치의 값 변경
</strong>        intAry[0] = 123;
        intAry[1] = 456;
        intAry[2] = 789;
</code></pre>

원시자료형의 배열은 그 값이 직접 담기고,

참조자료형의 배열은 그것이 저장된 주소를 가지고 배열을 만든다.

배열 초기화

```java
package sec03.chap08;

public class Ex02 {
    public static void main(String[] args) {
        //  초기화 블록을 사용한 선언 동시 초기화
        //  두 가지 방법 사용 가능
        char[] dirAry1 = {'동', '서', '남', '북'};
        char[] dirAry2 = new char [] {'동', '서', '남', '북'};

        char[] dirAry3;

        //  선언만 먼저 한 상태에서는 두 번째 방법만 가능
        //dirAry3 = {'동', '서', '남', '북'}; // ⚠️ 불가
        dirAry3 = new char[] {'동', '서', '남', '북'};

        int [] intAry = {1, 2, 3, 4, 5};

        //  ⚠️ 런타임 에러: ArrayIndexOutOfBoundsException
        int outOfAry = intAry[intAry.length];
    }
}

```

다중 배열

```java
package sec03.chap08;

public class Ex03 {
    public static void main(String[] args) {
        //  이중 배열
        boolean[][] dblBoolAry = new boolean[3][3];

        int[][] dblIntAry = new int[][] {
                //  ⭐️ 요소 배열의 크기가 다를 수 있음
                {1, 2, 3},
                {4, 5},
                {6, 7, 8, 9},
        };

        //  삼중 배열
        char[][][] trpChrAry = {
                {{'자', '축'}, {'인', '묘'}},
                {{'진', '사'}, {'오', '미'}},
                {{'신', '유'}, {'술', '해'}},
        };

        int int1 = dblIntAry[0][1];
        int int2 = dblIntAry[2][3];
        int[] intAry = dblIntAry[1];

        char[][] dblChrAry = trpChrAry[0];
        char[] chrAry = dblChrAry[0];
        char chr1 = chrAry[1];
        char chr2 = trpChrAry[2][0][1];

    }
}

```

### 원시 자료형 primitive type vs 참조 자료형 reference type

```java
package sec03.chap08;

public class Ex04 {

    public static void main(String[] args) {
        //  🧪 디버깅해서 결과를 볼 것
        //  ⭐ 원시 자료형은 값 자체를 복사 - 별개의 값이 됨

        boolean bool1 = true;
        boolean bool2 = false;
        bool2 = bool1; // 🔴 bool2에 bool1의 값을 복사해서 넣어줌
        bool1 = false;

        int int1 = 1;
        int int2 = 2;
        int2 = int1;
        int2 = 3;

        char ch1 = 'A';
        char ch2 = 'B';
        ch2 = ch1;
        ch1 = '가';


        //  ⭐ 참조 자료형은 값 주머니의 주소를 복사
        //  두 변수가 같은 주머니를 가리키게 됨

        boolean[] boolAry1 = { true, true, true };
        boolean[] boolAry2 = { false, false, false };
        boolAry2 = boolAry1; // 🔴
        boolAry1[0] = false;
        //


        int[] intAry1 = { 1, 2, 3 };
        int[] intAry2 = { 4, 5 };
        intAry2 = intAry1;
        intAry2[1] = 100;

        char[] chAry1 = { 'A', 'B', 'C' };
        char[] chAry2 = { 'a', 'b', 'c', 'd', 'e' };
        chAry2 = chAry1;
        chAry1[2] = '다';
    }
}

```

<figure><img src="/files/GUZ1hsF57i3UjAKci6e1" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/NzgSEmBJz5upAIlRfYaJ" alt=""><figcaption></figcaption></figure>

문자열 배열

```java
package sec03.chap08;

public class Ex05 {
    public static void main(String[] args) {
        //  ⭐️ 문자열은 객체(참조형)지만 원시형처럼 다뤄짐
        String str1 = "코인 함";
        String str2 = "관심 없음";
        str2 = str1; // 🔴

        str1 = "고점에 익절";
    }
}

```

상수 배열

```java
package sec03.chap08;

public class Ex06 {
    public static void main(String[] args) {
        //  상수 배열의 경우
        final int[] NUMBERS = {1, 2, 3, 4, 5};

        //  ⚠️ 다른 배열을 할당하는 것은 불가
        //NUMBERS = new int[] {2, 3, 4, 5, 6};

        //  ⭐️ 배열의 요소를 바꾸는 것은 가능
        NUMBERS[0] = 11;
    }
}

```

문자열 배열 관련 String 기능

```java
package sec03.chap08;

public class Ex07 {
    public static void main(String[] args) {
        String[] strings = {"한놈", "두시기", "석삼", "너구리"};

        //  💡 join 정적 메소드 - 문자열(정확히는 CharSequence)의 배열을 하나로 이어붙임
        //  첫 번째 인자를 각 사이에 삽입
        String join1 = String.join(", ", strings);
        String join2 = String.join("-", strings);
        String join3 = String.join(" 그리고 ", strings);
        String join4 = String.join("", strings);
        
    }
}

```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://leeans-dev-book.gitbook.io/docs/lecture/java/section2./array.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.
