HwangHub

[Java] scope rule 본문

DEV-STUDY/Java

[Java] scope rule

HwangJerry 2023. 7. 3. 07:51

만약 지역 변수와 전역 변수의 이름이 동일할 경우,

 

예를 들어

public class Main {
    public static int a = 10, b = 20;

    public static void printAandB() {
        System.out.println(a + " " + b);
    }

    public static void modify(int a, int b) {
        System.out.println(a + " " + b);
        printAandB();
        int temp = a;
        a = b;
        b = temp;
    }

    public static void main(String[] args) {
        modify(50, 60);
        printAandB();
    }
}

위와 같이 전역 변수에도 int a, int b가 정의되어 있는데, modify라는 함수의 파라미터(지역변수)도 int a, int b라고 선언된 경우에, modify 함수 실행 안에서 표기되는 a와 b는 지역변수의 값을 사용하게 된다.

 

즉, 지역 변수와 전역 변수가 같은 변수 이름을 갖는 경우 실행 시점에 가장 가까이에 있는 변수를 사용하게 됩니다.

Comments