# 변수

> ### 단 하나의 값을 저장할 수 있는 메모리 공간을 의미합니다.
>
> * 변수 공간에 기록된 값은 고정되어 있지 않고, 다른 값이 기록되면 자동으로 덮어 씌워질 수 있습니다.

<figure><img src="https://1460556410-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3hxjcsx6VFJEpkIV3dzZ%2Fuploads%2FHQzWzfDAodGptoE4mwdw%2Fimage.png?alt=media&#x26;token=c1f485f0-a060-47cb-b599-42afc3a6dda9" alt=""><figcaption></figcaption></figure>

* 메모리 공간은 정보처리의 기초 단위인 <mark style="color:blue;">1Byte</mark> 로 구성되어 있습니다.
* 메모리 공간은 각각이 구분될 수 있도록 <mark style="color:blue;">'메모리 주소'</mark>를 가지고 있습니다.

> ### 메모리에 값을 저장하거나 읽을 때 해당 <mark style="color:blue;">메모리 주소</mark>를 사용해야 하는데&#x20;
>
> ### 사람이 사용하기에는 불편하기 때문에
>
> ### <mark style="color:blue;">특정 메모리 영역</mark>에 이름을 붙이고 <mark style="color:blue;">주소 대신에 이름</mark>을 사용해서&#x20;
>
> ### 메모리에 값을 저장하고 읽을 수 있게 한 것이 <mark style="color:blue;">변수</mark>입니다.

<figure><img src="https://1460556410-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3hxjcsx6VFJEpkIV3dzZ%2Fuploads%2FQ0xQpTnszrMaWSQIxzxI%2Fimage.png?alt=media&#x26;token=c535c03a-804b-42b7-b6af-c63c48f19c53" alt=""><figcaption></figcaption></figure>

* 위 이미지 처럼 저장되는 <mark style="color:blue;">값의 종류(타입)에 따라</mark>, 변수의 메모리 공간 크기가 결정됩니다.

## 변수의 선언

* 선언을 하는 이유 : <mark style="color:blue;">메모리에 값을 저장할 공간</mark>을 마련하기 위해서 선언을 합니다.
* 선언 방법 : <mark style="color:blue;">`변수타입 변수이름;`</mark>
  * <mark style="color:blue;">`int age; int num;`</mark> or <mark style="color:blue;">`int age, num;`</mark>

{% code lineNumbers="true" %}

```java
class Variable1_1 {
        boolean flag;
        char grade;
        byte val;
        short sval;
        int num;
        long price;
        float tax;
        double score;
}
```

{% endcode %}

### 변수 생성 규칙

> * 대소문자가 구분되며 길이에 제한이 없음
> * 예약어(ex->true) 사용 불가
> * 숫자로 시작 불가
> * 특수문자 \_ 와 $ 만 허용

### 변수의 여러가지 형태

> * Camel case
>   * varTest
> * Snake case
>   * var\_test
> * Pascal case (Java 에는 클래스명만 대문자로 시작하자는 암묵적인 규칙이 있어서 추천 X)
>   * VarTest
> * Kebab case (Java 에서는 변수명에 - 기호 사용 불가)
>   * var-test

## 변수의 초기화

* 변수에 값을 저장하는 방법 : <mark style="color:blue;">`변수타입 변수이름 = 값;`</mark>
  * <mark style="color:blue;">`int age; age = 23;`</mark> or <mark style="color:blue;">`int age = 23;`</mark> or <mark style="color:blue;">`int age = 23, num = 32768;`</mark>
* 초기화 : 변수에 처음으로 값을 저장하는 것을 의미합니다.

{% code lineNumbers="true" %}

```java
class Variable1_2 {
    public static void main(String[] args) {
        boolean flag = false;
        char grade = 'A';
        byte val = 127;
        short sval = 128;
        int num = 32768;
        long price = 2_147_483_648L;
        float tax = 3.14f;
        double score = 3.14159265358979;
        
        System.out.println("boolean = " + flag);
        System.out.println("char = " + grade);
        System.out.println("byte = " + val);
        System.out.println("short = " + sval);
        System.out.println("int = " + num);
        System.out.println("long = " + price);
        System.out.println("float = " + tax);
        System.out.println("double = " + score);
    }
}
```

{% endcode %}

## 변수의 값 읽기

{% code lineNumbers="true" %}

```java
class Variable1_3 {
    public static void main(String[] args) {
        int year, age = 23;

        year = age + 2000;
        System.out.println("year = " + year); // 2023

        // 변수의 값을 읽어오는 과정
        // year = age + 2000;
        // year = 23 + 2000;
        // year = 2023;

        age = age + 1;
        System.out.println("age = " + age); // 24
        System.out.println("year = " + year); // 2023

        // 변수의 값을 읽어오는 과정
        // age = age + 1;
        // age = 23 + 1;
        // age = 24;
        // 프로그램은 순차적으로 코드가 실행되기 때문에
        // 여기서 age의 값이 바뀌었다고 year에 영향을 주지 않는다.
    }
}
```

{% endcode %}

## 변수의 종류

* 변수의 종류에는 <mark style="color:blue;">클래스, 인스턴스, 지역 변수</mark>가 있습니다.
* 뒤에서 다시 학습하기 때문에 간단하게 아래 예제코드로 정리하겠습니다.

{% code lineNumbers="true" %}

```java
class Variable1_4 {
    static int classVal = 100; // 클래스 변수
    int instanceVal = 200; // 인스턴스 변수

    public static void main(String[] args) {
        int num; // 지역 변수
//        System.out.println("int = " + num); // Error 발생
        num = 300;
        System.out.println("int = " + num); // 100

        // 인스턴스 변수
//        System.out.println("instanceVal = " + instanceVal); // Error 발생
        Variable1_4 instance = new Variable1_4 (); // 인스턴스 변수 사용을 위해 객체 생성
        System.out.println("instanceVal = " + instance.instanceVal); // 100

        // 클래스 변수
        System.out.println("classVal = " + classVal);
        // 같은 크래스 내부는 바로 접근 가능
        System.out.println("Main.classVal = " + Variable1_4.classVal);
        // 클래스 변수 : 클래스명.클래스변수명 으로 접근 or
    }
}
```

{% endcode %}

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

Ref. [변수](https://www.youtube.com/watch?v=yjRnG1iju1U\&list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp\&index=11), [타입](https://www.youtube.com/watch?v=WL4lR3GrIto\&list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp\&index=12)
{% 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-01.-hello-world/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.
