Java/CS

[Java] 변수(Variables)

annovation 2025. 4. 21. 23:11

변수(Variables)

자바에서 변수란 데이터를 저장하고 조작하기 위해 사용되는 이름이 붙은 메모리 공간입니다. 변수는 특정 타입을 가지며, 이 타입은 변수에 저장될 수 있는 값의 종류와 수행할 수 있는 연산을 결정합니다.​ [각주:1]


변수가 필요한 이유

  • 자바는 정적 타입 언어로, 모든 변수와 표현식은 컴파일 시점에 타입이 결정됩니다. 이는 변수의 타입이 컴파일 타임에 알려져 있어야 함을 의미합니다. 이러한 강한 정적 타이핑은 컴파일 시점에 오류를 감지하는 데 도움을 줍니다. [각주:2]
The Java programming language is also a strongly typed language, because types limit the values that a variable (§4.12) can hold or that an expression can produce, limit the operations supported on those values, and determine the meaning of the operations. Strong static typing helps detect errors at compile time.
  • 똑같은 값을 사용하는 경우 값이 바뀌었을 때, 오류를 줄이기 위해 사용할 수 있습니다.

💡 예시

1) 변수 사용하지 않은 코드

public class WithoutVariable {
    public static void main(String[] args) {
        // 할인율이 0.1로 고정되어 있음 (10%)
        double price1 = 10000 * (1 - 0.1);
        double price2 = 20000 * (1 - 0.1);
        double price3 = 30000 * (1 - 0.1);

        System.out.println("가격 1: " + price1);
        System.out.println("가격 2: " + price2);
        System.out.println("가격 3: " + price3);
    }
}

 

2) 변수 사용한 코드

public class WithVariable {
    public static void main(String[] args) {
        double discountRate = 0.1; // 할인율 변수

        double price1 = 10000 * (1 - discountRate);
        double price2 = 20000 * (1 - discountRate);
        double price3 = 30000 * (1 - discountRate);

        System.out.println("가격 1: " + price1);
        System.out.println("가격 2: " + price2);
        System.out.println("가격 3: " + price3);
    }
}

변수는 어디에 저장되나요?

  • 자바에서 변수는 메모리 공간에 특정 데이터를 저장하며, 이 공간은 변수의 이름을 통해 접근됩니다. 변수는 메모리 내의 특정 위치를 참조하며, 해당 위치에 저장된 값을 읽거나 쓸 수 있습니다.

로컬 변수 초기화의 중요성

  • 자바에서는 지역 변수를 선언 후 초기화하지 않으면 컴파일 오류가 발생합니다. 이는 메모리의 해당 위치에 어떤 값이 저장되어 있는지 알 수 없기 때문에, 명시적으로 초기화를 통해 값을 지정해야 합니다. [각주:3]
​Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
  • 메모리는 여러 시스템이 함께 사용하는 공간이므로 이전에 어떤 값이 있었는지 알 수 없기 때문에 초기화하는 것이 필수입니다.

변수 타입 별 메모리 사용

  • 자바는 다양한 데이터 타입을 제공하여 메모리 사용을 최적화할 수 있도록 합니다. 예를 들어, byte는 8비트를 사용하고, int는 32비트를 사용합니다. 이러한 타입 선택은 프로그램의 메모리 효율성과 성능에 영향을 미칩니다.
  • 이렇듯 변수는 표현 범위에 따라서 메모리 공간을 차지하므로 필요에 맞도록 다양한 타입을 제공합니다.

출처

반응형

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

[Java] GC(Garbage Collection)  (0) 2025.04.26
Gradle VS Maven  (0) 2025.03.01
[Java 이론] 영속성 컨텍스트(Persistence Context)  (0) 2025.02.27
Java VS Kotlin  (1) 2025.02.21
[Java 이론] 메모리 구조 JVM (업데이트 중..)  (0) 2024.11.19