# 변수의 초기화

> ### 수동 / 자동 초기화
>
> * <mark style="color:blue;">지역 변수</mark>는 <mark style="color:blue;">수동으로 초기화</mark> 해야합니다.
>   * 지역 변수가 동작하는 스택 메모리는 재사용이 빈번하기 때문에 매번 초기화 해주면 성능이 떨어집니다.
>   * 그래서 그냥 해당 메모리에 있는 값으로 덮어 씌웁니다.
>   * 근데 해당 주소에 어떠한 값이 있는지 모르기 때문에 Java는 개발자에게 <mark style="color:blue;">수동으로 초기화</mark> 하라고 요구합니다.
>   * C 언어에서는 이를 *<mark style="color:blue;">garbage value</mark> 라 부릅니다.(<mark style="color:blue;">C언어와 Java의 차이</mark>를 비교하면 이해가 쉽습니다.)*
> * 멤버변수(<mark style="color:blue;">인스턴스 변수, 클래스 변수</mark>)는 <mark style="color:blue;">자동으로 초기화</mark> 됩니다.
>
> ### 멤버 변수의 초기화
>
> * 클래스 변수 : 클래스가 <mark style="color:blue;">처음 로딩</mark>될 때 <mark style="color:blue;">단 한번</mark>만 초기화 됩니다.
> * 인스턴스 변수 : <mark style="color:blue;">인스턴스가 생성</mark>될 때 마다 초기화 됩니다.

## 초기화 방법

### 명시적 초기화(=)

```java
class Tv11_1 {
    boolean power = false;    // 기본형 변수의 초기화
    int channel = 1;          // 기본형 변수의 초기화
    Audio audi = new Audio(); // 참조형 변수의 초기화, 참조형은 객체주소 or null 로 초기화!!
    // 참조형의 기본값은 null 입니다!!
    ...
}
```

### 초기화 블럭

```java
class Tv11_2 {
    static boolean power;
    int channel; 
    
    // 클래스 초기화 블럭
    static 
    {
        power = false;
    }
    
    // 인스턴스 초기화 블럭
    {
        channel = 1;  
    }
    ...
}
```

### 생성자 초기화

```java
class Tv11_3 {
    // 속성 : 변수 선언
    boolean power; // 전원상태
    int channel;  // 채널
    String color; // 색깔
    long price; // 가격
    
    // 위 속성에서 필수로 초기값이 필요한 값들을 초기화 해주는 기본 생성자
    Tv11_3() {
        this.power = false;
        this.channel = 1;
    }
    ... 
}
```

{% hint style="info" %}
Ref. Java의 정석 기초편 Chapter6(38, 39, 40, 41)

Ref. [변수의 초기화](https://www.youtube.com/watch?v=ayRKMT6x-ms\&list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp\&index=69)
{% 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-05./undefined-8.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.
